问:
Creation of file under /proc and using it
I'm trying to understand some example code my lecturer gave me.

It is a method of transferring data from user space into kernel space via a /proc file. This is the only code he gave me and I feel like I'm missing the user space program and I don't think he's explained what's going on very well.

He's trying to demonstrate locking files via semaphores, and also transferring the data I believe. The things I'm struggling to understand are:

what is the "reference count" (He mentions it in the comments for procfs_open and procfs_close)

Why would he use a proc file? It appears to do nothing.

What do module_put and try_module_get do? I can't find any remotely good explanations online.

How would I trigger the kernelWrite function from userspace? So that I know how I can actually transfer the data, not just receive it.

Here is the code:

```<code>#define BUFFERLENGTH 256
#define INCREASE_COUNTER 'I'
#define SHOW_COUNTER 'S'

#define PROC_ENTRY_FILENAME "kernelWrite"

DECLARE_RWSEM(counter_sem); /* semaphore to protect counter access */

static struct proc_dir_entry *Our_Proc_File;

int counter1 = 0;
int counter2 = 0;

/* displays the kernel table - for simplicity via printk */
void show_table (void) {

    int tmp1;
    int tmp2;

    down_read (&counter_sem); /* lock for reading */
    tmp1 = counter1;
    tmp2 = counter2;
    up_read (&counter_sem); /* unlock reading */
    printk (KERN_INFO "kernelWrite:The counters are %d, %d\n", tmp1, tmp2);

}

void increase_counter (void) {

    down_write (&counter_sem); /* lock for writing */
    counter1++;
    counter2++;
    up_write (&counter_sem);

}

/* This function reads in data from the user into the kernel */
ssize_t kernelWrite (struct file *file, const char __user *buffer, size_t count, loff_t *offset) {

    char command;

    printk (KERN_INFO "kernelWrite entered\n");

    if (get_user (command, buffer)) {
    return -EFAULT;
    }

  switch (command) {
    case INCREASE_COUNTER:
    increase_counter ();
    break;
    case SHOW_COUNTER:
    show_table ();
      break;
    default:
      printk (KERN_INFO "kernelWrite: Illegal command \n");
  }
  return count;
}

/*
 * The file is opened - we don't really care about
 * that, but it does mean we need to increment the
 * module's reference count.
 */
int procfs_open(struct inode *inode, struct file *file)
{
    printk (KERN_INFO "kernelWrite opened\n");
    try_module_get(THIS_MODULE);
    return 0;
}

/*
 * The file is closed - again, interesting only because
 * of the reference count.
 */
int procfs_close(struct inode *inode, struct file *file)
{
    printk (KERN_INFO "kernelWrite closed\n");
    module_put(THIS_MODULE);
    return 0;       /* success */
}

const struct file_operations File_Ops_4_Our_Proc_File = {
    .owner = THIS_MODULE,
    .write   = kernelWrite,
    .open    = procfs_open,
    .release = procfs_close,
};

int init_module(void)
{

    /* create the /proc file */
    Our_Proc_File = proc_create_data (PROC_ENTRY_FILENAME, 0644, NULL, &File_Ops_4_Our_Proc_File, NULL);

    /* check if the /proc file was created successfuly */
    if (Our_Proc_File == NULL){
    printk(KERN_ALERT "Error: Could not initialize /proc/%s\n",
           PROC_ENTRY_FILENAME);
    return -ENOMEM;
    }

    printk(KERN_INFO "/proc/%s created\n", PROC_ENTRY_FILENAME);

    return 0;   /* success */

}

void cleanup_module(void)
{

  remove_proc_entry(PROC_ENTRY_FILENAME, NULL);
  printk(KERN_INFO "/proc/%s removed\n", PROC_ENTRY_FILENAME);

  printk(KERN_INFO "kernelWrite:Proc module unloaded.\n");

}
</code>```

答:
Several questions, several answers:

1 Module reference count and try_module_get and module_put:
Each kernel module has usage count, in particular if it is referenced by any other module or used any other way. In this case, when doing opening file it will prevent module from being removed, and after closing the file, it will remove reference. Why it should not be used is explained here

2 Proc file:
Uses File_Ops_4_Our_Proc_File structure. You need to perform action in user space to trigger appropriate action on proc file (namely open, close and write).

3 Triggering actions.
For example (from bash):

```<code>echo 'I' > /proc/kernelWrite
</code>```

Which writes character 'I' to proc file, triggering File_Ops_4_Our_Proc_File.write, effectively calling kernelWrite.

Body:
I'm trying to understand some example code my lecturer gave me.

It is a method of transferring data from user space into kernel space via a /proc file. This is the only code he gave me and I feel like I'm missing the user space program and I don't think he's explained what's going on very well.

He's trying to demonstrate locking files via semaphores, and also transferring the data I believe. The things I'm struggling to understand are:

what is the "reference count" (He mentions it in the comments for procfs_open and procfs_close)

Why would he use a proc file? It appears to do nothing.

What do module_put and try_module_get do? I can't find any remotely good explanations online.

How would I trigger the kernelWrite function from userspace? So that I know how I can actually transfer the data, not just receive it.

Here is the code:

#define BUFFERLENGTH 256
#define INCREASE_COUNTER 'I'
#define SHOW_COUNTER 'S'

#define PROC_ENTRY_FILENAME "kernelWrite"

DECLARE_RWSEM(counter_sem); /* semaphore to protect counter access */

static struct proc_dir_entry *Our_Proc_File;

int counter1 = 0;
int counter2 = 0;

/* displays the kernel table - for simplicity via printk */
void show_table (void) {

    int tmp1;
    int tmp2;

    down_read (&counter_sem); /* lock for reading */
    tmp1 = counter1;
    tmp2 = counter2;
    up_read (&counter_sem); /* unlock reading */
    printk (KERN_INFO "kernelWrite:The counters are %d, %d\n", tmp1, tmp2);

}

void increase_counter (void) {

    down_write (&counter_sem); /* lock for writing */
    counter1++;
    counter2++;
    up_write (&counter_sem);

}

/* This function reads in data from the user into the kernel */
ssize_t kernelWrite (struct file *file, const char __user *buffer, size_t count, loff_t *offset) {

    char command;

    printk (KERN_INFO "kernelWrite entered\n");

    if (get_user (command, buffer)) {
    return -EFAULT;
    }

  switch (command) {
    case INCREASE_COUNTER:
    increase_counter ();
    break;
    case SHOW_COUNTER:
    show_table ();
      break;
    default:
      printk (KERN_INFO "kernelWrite: Illegal command \n");
  }
  return count;
}

/*
 * The file is opened - we don't really care about
 * that, but it does mean we need to increment the
 * module's reference count.
 */
int procfs_open(struct inode *inode, struct file *file)
{
    printk (KERN_INFO "kernelWrite opened\n");
    try_module_get(THIS_MODULE);
    return 0;
}

/*
 * The file is closed - again, interesting only because
 * of the reference count.
 */
int procfs_close(struct inode *inode, struct file *file)
{
    printk (KERN_INFO "kernelWrite closed\n");
    module_put(THIS_MODULE);
    return 0;       /* success */
}

const struct file_operations File_Ops_4_Our_Proc_File = {
    .owner = THIS_MODULE,
    .write   = kernelWrite,
    .open    = procfs_open,
    .release = procfs_close,
};

int init_module(void)
{

    /* create the /proc file */
    Our_Proc_File = proc_create_data (PROC_ENTRY_FILENAME, 0644, NULL, &File_Ops_4_Our_Proc_File, NULL);

    /* check if the /proc file was created successfuly */
    if (Our_Proc_File == NULL){
    printk(KERN_ALERT "Error: Could not initialize /proc/%s\n",
           PROC_ENTRY_FILENAME);
    return -ENOMEM;
    }

    printk(KERN_INFO "/proc/%s created\n", PROC_ENTRY_FILENAME);

    return 0;   /* success */

}

void cleanup_module(void)
{

  remove_proc_entry(PROC_ENTRY_FILENAME, NULL);
  printk(KERN_INFO "/proc/%s removed\n", PROC_ENTRY_FILENAME);

  printk(KERN_INFO "kernelWrite:Proc module unloaded.\n");

}

Body:
Several questions, several answers:

1 Module reference count and try_module_get and module_put:
Each kernel module has usage count, in particular if it is referenced by any other module or used any other way. In this case, when doing opening file it will prevent module from being removed, and after closing the file, it will remove reference. Why it should not be used is explained here

2 Proc file:
Uses File_Ops_4_Our_Proc_File structure. You need to perform action in user space to trigger appropriate action on proc file (namely open, close and write).

3 Triggering actions.
For example (from bash):

echo 'I' > /proc/kernelWrite

Which writes character 'I' to proc file, triggering File_Ops_4_Our_Proc_File.write, effectively calling kernelWrite.


来源: stackexchange

问:
IntelliJ dialog focus
Trying to control Android Studio by keyboard only, I do not know why, but when I focus "Cancel" button and press enter, it acts like I clicked on the default button (next tip is shown). The same scenario applies to WebStorm.

then I press Tab or right arrow (notice the blue glow around the button)

答: The solution, as LazyOne mentioned, is to use SPACE instead of ENTER.

ContentLicense: CC BY-SA 3.0

Title: IntelliJ dialog focus


问:
Bootstrap not compatible with angular 5
I am using Angular 5. After installing ng-bootstrap there are few errors. Is ng-bootstrap not compatible with Angular 5, or are their any other packages that are compatible?

答:
Update:

ng-bootstrap is now compatible with Angular 5 (since 5 Nov).

You may indeed be right about ng-bootstrap not being compatible with Angular 5:

Dependencies

Angular (tested with 4.0.3)

Bootstrap 4 (tested with 4.0.0-beta.2)

But I can verify npm install bootstrap@4.0.0-beta.2 is compatible with angular modules @5.0.5, along with npm@5.6.0, node@9.2.0 and typescript@2.4.2 here.

(Also no issues with my .angular-cli.json loading a custom styles.scss, which I use for a few selective imports like @import "~bootstrap/scss/functions".

Title: Bootstrap not compatible with angular 5


问:
Excel Random number from a set of options
In MS Excel, how can I randomly calculate a number number that is from one of a set of 5 options?

For example, in cell B1 I would like to have a random number that is either 15,30,50,75, or 100.

I would like a completely random output of these 5 numbers in cells B1:B100.

I was thinking that I could generate a random number in cell A1 using rand, then using a series of > or < IF statements to output only one of these numbers above.

答:
How about:

```<code>=SMALL({array containing numbers},RANDBETWEEN(1,COUNT({array containing numbers})))
</code>```

e.g. if you have an array containing the 5 numbers you want to use in $B$2:$B$6

```<code>=SMALL($B$2:$B$6,RANDBETWEEN(1,COUNT($B$2:$B$6)))
</code>```

This returns a random position in the list of numbers, with the total frequency of numbers being defined size of the array.

Body:
How about:

=SMALL({array containing numbers},RANDBETWEEN(1,COUNT({array containing numbers})))

e.g. if you have an array containing the 5 numbers you want to use in $B$2:$B$6

=SMALL($B$2:$B$6,RANDBETWEEN(1,COUNT($B$2:$B$6)))

This returns a random position in the list of numbers, with the total frequency of numbers being defined size of the array.


问:
Apache Redirect // to no //
An email went out with the wrong link (https://www.digitalmarketer.com/digital-marketing/content-marketing-strategy//) and we need to redirect the // to (https://www.digitalmarketer.com/digital-marketing/content-marketing-strategy/) but no matter what I try, the redirect isn't working.

They also want it to be redirected to always have https:///www at the beginning and to never have index.html at the end, so already in the .htaccess file I have:

```<code>RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^content\-marketing\-strategy/index\.html$ /digital-marketing/content-marketing-strategy/? [L,R=301]
</code>```

I've tried adding a new RewriteRule, but this won't work:

```<code>RewriteRule ^content\-marketing\-strategy//$ /digital-marketing/content-marketing-strategy/? [L,R=301]
</code>```

I'm very new to Apache and redirects so any help is much appreciated! Thank you!

Edit: Of note, this is in an .htaccess file inside of the digital-marketing folder (https://www.digitalmarketer.com/digital-marketing/.htaccess) which was done so all the above rules would only apply to the digital-marketing folder.

答:
You can use insert rule at the end of your other rules to strip multiple // into /:

```<code>RewriteCond %{THE_REQUEST} //
RewriteRule ^.*$ /digital-marketing/$0 [R=301,L,NE]
</code>```

Apache automatically strips down multiple // into one inside the pattern for RewriteRule thus captured value $0 will have all // converted into /

Title: Apache Redirect // to no //

Body:
An email went out with the wrong link (https://www.digitalmarketer.com/digital-marketing/content-marketing-strategy//) and we need to redirect the // to (https://www.digitalmarketer.com/digital-marketing/content-marketing-strategy/) but no matter what I try, the redirect isn't working.

They also want it to be redirected to always have https:///www at the beginning and to never have index.html at the end, so already in the .htaccess file I have:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^content\-marketing\-strategy/index\.html$ /digital-marketing/content-marketing-strategy/? [L,R=301]

I've tried adding a new RewriteRule, but this won't work:

RewriteRule ^content\-marketing\-strategy//$ /digital-marketing/content-marketing-strategy/? [L,R=301]

I'm very new to Apache and redirects so any help is much appreciated! Thank you!

Edit: Of note, this is in an .htaccess file inside of the digital-marketing folder (https://www.digitalmarketer.com/digital-marketing/.htaccess) which was done so all the above rules would only apply to the digital-marketing folder.

Body:
You can use insert rule at the end of your other rules to strip multiple // into /:

RewriteCond %{THE_REQUEST} //
RewriteRule ^.*$ /digital-marketing/$0 [R=301,L,NE]

Apache automatically strips down multiple // into one inside the pattern for RewriteRule thus captured value $0 will have all // converted into /


问:
sum of positive entries until a negative occurs in R
As an example I have a vector of 20 mixed positive and negative integers.
I would like a generate a new vector where every positive integer is added together until a negative integers occurs and then every negative is added until a positive occurs again.

e.g. 2 4 3 -4 -4 -3 -2 3 4 5 2 5 -4 -4 -3 -3 3 4 5  would become 9 -13 19 -14 12.

What sort of code should I use?  Is this even possible?

Body:
#DATA
set.seed(1)
x = sample(c(1, -1), 20, TRUE) * sample(1:20, 20, TRUE)
x
# [1]  19   5 -14  -3   6  -8  -1  -8 -18   7  10  12 -10   4 -17  14 -16  -3  15  -9

sapply(split(x, with(rle(x > 0), rep(1:length(values), lengths))), sum)
#  1   2   3   4   5   6   7   8   9  10  11  12
# 24 -17   6 -35  29 -10   4 -17  14 -19  15  -9


问:
How can I replace the "+" plus sign with its corresponding url encoding of "%2B"?
I'm having some trouble replacing the "+" sign with its urlencoded string of "%2B".  How can I do this?

This is what I've tried:

Text Entered into text box:

```<code>plus(+)
</code>```

I then urlencode the string:

```<code>$string = urlencode($string);
</code>```

String now looks like:

```<code>plus%28+%29
</code>```

I want to have the "+" urlencoded, or else when I urldecode() the data to display in browser I end up with:

```<code>plus( )
</code>```

because urldecode() interprets the "+" to be a space.

I tried using php's str_replace() but I keep getting a "NULL" returned as the value for "$new_string":

```<code>$new_string = str_replace('+', '%2B', $string);
</code>```

Any ideas?

Thanks in advance!

答:
That is strange. When I use urlencode on plus(+) I get plus%28%2B%29. Make sure you're using it correctly.

You might also try rawurlencode. It will encode spaces as %20 instead of +.

ContentLicense: CC BY-SA 2.5

Body:
I'm having some trouble replacing the "+" sign with its urlencoded string of "%2B".  How can I do this?

This is what I've tried:

Text Entered into text box:

plus(+)

I then urlencode the string:

$string = urlencode($string);

String now looks like:

plus%28+%29

I want to have the "+" urlencoded, or else when I urldecode() the data to display in browser I end up with:

plus( )

because urldecode() interprets the "+" to be a space.

I tried using php's str_replace() but I keep getting a "NULL" returned as the value for "$new_string":

$new_string = str_replace('+', '%2B', $string);

Any ideas?

Thanks in advance!


问:
Random days in date or datetime
Is it possible to random only days in date or Datetime within a range of days in sql server, t-sql.
For example if dates have days between 1to15 i want to randomise days creating a day number between 16 and 30. Example: 2017-7-10 to 2017-7-21(random day within 16to30). Thank you</p>

答:
```<code>DECLARE @dateA DATE = '2017-07-10'
DECLARE @dateB DATE

IF day(@dateA) < 16 --day number between 1 and 15
  SET @dateB = DATEFROMPARTS(year(@dateA), month(@dateA), FLOOR(RAND() * (30 - 16) + 16))
SELECT @dateA, @dateb
</code>```

DATEFROMPARTE SQL Server 2012+

No version specific:

```<code>DECLARE @dateA DATE = '2017-07-10'
DECLARE @dateB DATE
DECLARE @day INT

IF day(@dateA) < 16 --day number between 1 and 15
BEGIN
  SET @day = day(@dateA)
    SET @dateB = dateadd(day, - 1 * @day + FLOOR(RAND() * (30 - 16) + 16), @dateA)
END

SELECT @dateA, @dateb
</code>```

New request:

```<code>UPDATE yourTable
SET yourDateOrDatetimeColumn = dateadd(day, - 1 * day(yourDateOrDatetimeColumn) + FLOOR(RAND() * (30 - 16) + 16), yourDateOrDatetimeColumn)
WHERE day(yourDateOrDatetimeColumn) < 16
</code>```

Title: Random days in date or datetime

Body:
DECLARE @dateA DATE = '2017-07-10'
DECLARE @dateB DATE

IF day(@dateA) < 16 --day number between 1 and 15
  SET @dateB = DATEFROMPARTS(year(@dateA), month(@dateA), FLOOR(RAND() * (30 - 16) + 16))
SELECT @dateA, @dateb

DATEFROMPARTE SQL Server 2012+

No version specific:

DECLARE @dateA DATE = '2017-07-10'
DECLARE @dateB DATE
DECLARE @day INT

IF day(@dateA) < 16 --day number between 1 and 15
BEGIN
  SET @day = day(@dateA)
    SET @dateB = dateadd(day, - 1 * @day + FLOOR(RAND() * (30 - 16) + 16), @dateA)
END

SELECT @dateA, @dateb

New request:

UPDATE yourTable
SET yourDateOrDatetimeColumn = dateadd(day, - 1 * day(yourDateOrDatetimeColumn) + FLOOR(RAND() * (30 - 16) + 16), yourDateOrDatetimeColumn)
WHERE day(yourDateOrDatetimeColumn) < 16


答:
this code works just fine for me:

```<code>df_new <- df2$X__1
primary_ID <- "P20406-8"
secondary_ID <- "A0A024RBS2"

ID_Primary <- grepl(pattern = primary_ID, df_new)
ID_Secondary <- grepl(pattern = secondary_ID, df_new)

df_new[ID_Primary] <- substr(df_new[ID_Primary],
                              start = regexpr(primary_ID, df_new[ID_Primary]),
                              stop = 2000)

df_new[ID_Secondary & !ID_Primary] <- substr(df_new[ID_Secondary],
                                               start = regexpr(secondary_ID, df_new[ID_Secondary]),
                                               stop = 2000)

start <- regexpr(pattern = "\\[", text = df_new)  # find opening square bracket
end <- regexpr(pattern = "\\]", text = df_new)  # find closing square bracket
temp <- substr(df_new, start+1, end-1)  # only take values between opening and closing
temp <- strsplit(temp, "-")  # split values in two

result <- t(data.frame(temp))
rownames(result) <- NULL
</code>```

I hope this helps!

Title: how can I take values out of many strings

Body:
I have a data like below

df<-structure(list(X__1 = c("Q6NVC0 [197-213]", "A0A0A8UAS1 [48-64]",
"A0A0F0XK65 [8-17]", "A0A0G2JMX7 [481-491]; P20406-6 [106-116]; Q6UIN5 [7-17]; P20406-3 [70-80]; P20406-8 [164-174]",
"A0A0G2JMX7 [481-497]; P20406-6 [106-122]; Q6UIN5 [7-23]; P20406-3 [70-86]; P20406-8 [164-180]",
"P20406-6 [106-132]; Q6UIN5 [7-33]; P20406-3 [70-96]; P20406-8 [164-190]",
"H6VRG2 [603-616]", "P13645 [41-59]", "P35527 [488-513]", "P35908 [525-544]; H2R1Z0 [512-531]",
"H6VRG2 [550-588]", "A0A024RBS2 [150-162]", "A0A023L3M5 [83-110]",
"P10809 [143-156]", "V9HW22 [470-493]", "P20406-8 [379-392]",
"P19338 [524-537]", "A0A024L4P7 [46-57]", "G7YYH5 [45-55]", "Q86YZ3 [973-991]; [1443-1461]; [1913-1931]; [2383-2401]",
"P35527 [375-390]", "P35527 [375-391]", "D2TTS3 [41-50]")), .Names = "X__1", class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -23L))

I am trying to make an output like this
At first I try to get the value next to one two IDs P20406-8 and A0A024RBS2. If they dont exist in a row, we take the first two values of any other ID. if they exist together, we take the value next to the first one and if one of the ID is there, we take its value.

So at the end I want a two column of values like below

197 213
48  64
8   17
164 174
164 180
164 190
603 616
41  59
488 513
525 544
550 588
150 162
83  110
143 156
470 493
379 392
524 537
46  57
45  55
973 991
375 390
375 391
41  50

Body:
this code works just fine for me:

df_new <- df2$X__1
primary_ID <- "P20406-8"
secondary_ID <- "A0A024RBS2"

ID_Primary <- grepl(pattern = primary_ID, df_new)
ID_Secondary <- grepl(pattern = secondary_ID, df_new)

df_new[ID_Primary] <- substr(df_new[ID_Primary],
                              start = regexpr(primary_ID, df_new[ID_Primary]),
                              stop = 2000)

df_new[ID_Secondary & !ID_Primary] <- substr(df_new[ID_Secondary],
                                               start = regexpr(secondary_ID, df_new[ID_Secondary]),
                                               stop = 2000)

start <- regexpr(pattern = "\\[", text = df_new)  # find opening square bracket
end <- regexpr(pattern = "\\]", text = df_new)  # find closing square bracket
temp <- substr(df_new, start+1, end-1)  # only take values between opening and closing
temp <- strsplit(temp, "-")  # split values in two

result <- t(data.frame(temp))
rownames(result) <- NULL

I hope this helps!


问:
lxml: How do I pass a (python) tuple/list to etree.XSLT() object to dynamically generate the xml from the xslt?
lxml's documentation talks about passing parameters for the xslt. Here it is: http://lxml.de/xpathxslt.html#stylesheet-parameters But how do I pass a sequence/tuple/list to the same transform method so that my xslt will catch it and render it (to an xml) using xsl:for-each

If I pass it like this:

```<code>transform = etree.XSLT(xslt_content)
transform(input_xml_content,
          **{'items':('item1', 'item2')})
</code>```

All I get is:

```<code>  File "xslt.pxi", line 519, in lxml.etree.XSLT.__call__ (src/lxml/lxml.etree.c:119769)
  File "xslt.pxi", line 642, in lxml.etree._convert_xslt_parameters (src/lxml/lxml.etree.c:120985)
  File "xslt.pxi", line 634, in lxml.etree._convert_xslt_parameters (src/lxml/lxml.etree.c:120882)
  File "apihelpers.pxi", line 1364, in lxml.etree._utf8 (src/lxml/lxml.etree.c:22190)
TypeError: Argument must be bytes or unicode, got 'tuple'
</code>```

答:
Maybe a bit late, but i was looking for an answer for the same problem but couldn't find any. What I came up with is to load the xslt as xml and modify it before applying using transform</p>

```<code>def apply_xslt(xml_file, xslt_file_path, xslt_params):
    try:
        xslt = etree.parse(xslt_file_path)

        for key, value in xslt_params.iteritems():
            xslt.find("//{http://www.w3.org/1999/XSL/Transform}param[@name='" + key + "']").attrib['select'] = value

        transform = etree.XSLT(xslt)

        newdom = transform(xml_file)
        return newdom
    except Exception as e:
        raise e
</code>```

Body:
lxml's documentation talks about passing parameters for the xslt. Here it is: http://lxml.de/xpathxslt.html#stylesheet-parameters But how do I pass a sequence/tuple/list to the same transform method so that my xslt will catch it and render it (to an xml) using xsl:for-each

If I pass it like this:

transform = etree.XSLT(xslt_content)
transform(input_xml_content,
          **{'items':('item1', 'item2')})

All I get is:

  File "xslt.pxi", line 519, in lxml.etree.XSLT.__call__ (src/lxml/lxml.etree.c:119769)
  File "xslt.pxi", line 642, in lxml.etree._convert_xslt_parameters (src/lxml/lxml.etree.c:120985)
  File "xslt.pxi", line 634, in lxml.etree._convert_xslt_parameters (src/lxml/lxml.etree.c:120882)
  File "apihelpers.pxi", line 1364, in lxml.etree._utf8 (src/lxml/lxml.etree.c:22190)
TypeError: Argument must be bytes or unicode, got 'tuple'

Body:
Maybe a bit late, but i was looking for an answer for the same problem but couldn't find any. What I came up with is to load the xslt as xml and modify it before applying using transform

def apply_xslt(xml_file, xslt_file_path, xslt_params):
    try:
        xslt = etree.parse(xslt_file_path)

        for key, value in xslt_params.iteritems():
            xslt.find("//{http://www.w3.org/1999/XSL/Transform}param[@name='" + key + "']").attrib['select'] = value

        transform = etree.XSLT(xslt)

        newdom = transform(xml_file)
        return newdom
    except Exception as e:
        raise e


问:
Qt - Emit signal from callback
I am using the BGLib in my Qt application to communicate over BLE.

In the main thread the GUI is running (sensornode_gui.cpp). By clicking on a pushButton a different thread starts to scan for BLE devices (ble_connection). I get the resulting information from a callback function such as void ble_evt_gap_scan_response(const struct ble_msg_gap_scan_response_evt_t *msg). How can I emit signals from that callback function to update the GUI with some attributes from msg for example?

main.cpp

```<code>#include "sensornode_gui.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    SensorNode_GUI w;
    w.show();
    return a.exec();
}
</code>```

sensornode_gui.h

```<code>#ifndef SENSORNODE_GUI_H
#define SENSORNODE_GUI_H

#include <QMainWindow>
#include <QThread>
#include "ble_connection.h"

namespace Ui {
class SensorNode_GUI;
}

class SensorNode_GUI : public QMainWindow
{
    Q_OBJECT

public:
    explicit SensorNode_GUI(QWidget *parent = 0);
    ~SensorNode_GUI();
    void printText(std::string s);

private slots:
    void on_pushButtonStartScanning_clicked();

private:
    Ui::SensorNode_GUI *ui;
    QThread *thread;
    BLE_Connection *ble_worker;

};

#endif // SENSORNODE_GUI_H
</code>```

sensornode_gui.cpp

```<code>#include "sensornode_gui.h"
#include "ui_sensornode_gui.h"

SensorNode_GUI::SensorNode_GUI(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SensorNode_GUI)
{
    ui->setupUi(this);

    thread = new QThread();
    ble_worker = new BLE_Connection();
    ble_worker->setGUI(this);

    ble_worker->moveToThread(thread);
    connect(ble_worker, SIGNAL(valueChanged(QString)), ui->textEdit, SLOT(append(QString)));
    connect(ble_worker, SIGNAL(workRequested()), thread, SLOT(start()));
    connect(thread, SIGNAL(started()), ble_worker, SLOT(doWork()));
}

SensorNode_GUI::~SensorNode_GUI()
{
    delete thread;
    delete ble_worker;

    delete ui;
}

void SensorNode_GUI::printText(std::string s){
    ui->textEdit->append(QString::fromStdString(s));
}

void SensorNode_GUI::on_pushButtonStartScanning_clicked()
{
    ble_worker->requestWork();
}
</code>```

ble_connection.h

```<code>#ifndef BLE_CONNECTION_H
#define BLE_CONNECTION_H

#include <QObject>
#include <QMutex>
#include <QDebug>
#include <QThread>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "cmd_def.h"
#include "apitypes.h"
#include "sensornode_gui.h"

class SensorNode_GUI;

class BLE_Connection : public QObject
{
    Q_OBJECT

public:
    explicit BLE_Connection(QObject *parent = 0);
    static void output(uint8,uint8*,uint16,uint8*);
    int read_message();
    void connect();
    void disconnect();

    void requestWork();

private:
    bool _abort;
    bool _working;
    QMutex mutex;

signals:
    void workRequested();
    void valueChanged(const QString &value);

public slots:
    void doWork();
};

#endif // BLE_CONNECTION_H
</code>```

ble_connection.cpp

```<code>#include "ble_connection.h"

volatile HANDLE serial_handle;
uint8 connection_handle;

BLE_Connection::BLE_Connection(QObject *parent) :
    QObject(parent)
{
    char str[80];
    snprintf(str,sizeof(str)-1,"\\\\.\\%s","COM3");
    //open I/O device
    ...

    bglib_output = output;

}

void BLE_Connection::setGUI(SensorNode_GUI *g)
{
    gui = g;
}

void BLE_Connection::requestWork()
{
    mutex.lock();
    _working = true;
    _abort = false;
    qDebug()<<"Request worker start in Thread "<<thread()->currentThreadId();
    mutex.unlock();

    emit workRequested();
}

void BLE_Connection::doWork()
{
    while(true){
        read_message();
        qDebug() << "Within doWork";
        emit valueChanged(QString::fromStdString("Test"));
    }
}

void BLE_Connection::output(uint8 len1,uint8* data1,uint16 len2,uint8* data2)
{
    ...
}

int BLE_Connection::read_message()
{
    DWORD rread;
    const struct ble_msg *apimsg;
    struct ble_header apihdr;
    unsigned char data[256];//enough for BLE
    //read header

    if(!ReadFile(serial_handle,
               (unsigned char*)&apihdr,
               4,
               &rread,
               NULL))
        {
            return GetLastError();
        }
    if(!rread)return 0;
    //read rest if needed
    if(apihdr.lolen)
    {
        if(!ReadFile(serial_handle,
                   data,
                   apihdr.lolen,
                   &rread,
                   NULL))
            {
                return GetLastError();
            }
    }
    apimsg=ble_get_msg_hdr(apihdr);
    if(!apimsg)
    {
        printf("ERROR: Message not found:%d:%d\n",(int)apihdr.cls,(int)apihdr.command);
        return -1;
    }
    apimsg->handler(data);

    return 0;
}

//=============FUNCTIONS FOR HANDELING EVENTS AND RESPONSES====================

void ble_evt_gap_scan_response(const struct ble_msg_gap_scan_response_evt_t *msg)
{
    int i;
    std::string buffAsStdStr;
    char buff[100];
    char *name = NULL;
    for(i=0;i<6;i++){
        snprintf(buff, sizeof(buff), "%02x%s",msg->sender.addr[5-i],i<5?":":"");
        buffAsStdStr += buff;
    }

    snprintf(buff, sizeof(buff), "\t%d",msg->rssi);
    buffAsStdStr += buff;
    //HERE I WANT TO EMIT THE SIGNAL VALUECHANGED
    //emit valueChanged(QString::fromStdString(buffAsStdStr));

    free(name);
}
</code>```

Thanks in advance.

答:
I have faced to the same problem at using a different library. I have solved this issue by wrapping library class with mine (CameraWrapper), and put object of this class into my class (MeasurementSystem) inherited from QObject. So when this parent class creates wrapper for the class that sends callback, it passes pointer to itself QObject*. Child chass (CameraWrapper) stores this pointer and sends it within the callback.

Looks like this:

MeasurementSystem.h

```<code>#ifndef MEASUREMENTSYSTEM_H
#define MEASUREMENTSYSTEM_H
#include <vector>
#include "camerawrapper.h"
#include "qobject.h"

class MeasurementSystem : public QObject
{
    Q_OBJECT
public:
    MeasurementSystem();
    enum CamAlign {caTopInner = 0,caTopOuter,caBottomInner,caBottomOuter,caSide};   //cameras alignment in optical sysem

    void Connect();
    void Disconnect();
signals:
    void sigDataReceived(int,std::vector<int>);

private:
    std::vector<CameraWrapper*> _cams;
    friend void DataReceived(QObject * Sender, int &, std::vector<int>&);       //callback function for receiving data from any camera
};

#endif // MEASUREMENTSYSTEM_H
</code>```

MeasurementSystem.cpp

```<code>#include "measurementsystem.h"
#include <QApplication>
MeasurementSystem::MeasurementSystem()
{
    QString path = QApplication::applicationDirPath();
    _cams.push_back(new CameraWrapper(this,*DataReceived,(path+"/CameraSettings/Ranger D50 TopInner.icx").toStdString(),"192.168.1.11","CamTopInner",caTopInner));
    _cams.push_back(new CameraWrapper(this,*DataReceived,(path+"/CameraSettings/Ranger D50 TopInner.icx").toStdString(),"192.168.1.12","CamTopOuter",caTopOuter));
    _cams.push_back(new CameraWrapper(this,*DataReceived,(path+"/CameraSettings/Ranger D50 TopInner.icx").toStdString(),"192.168.1.13","CamBottomInner",caBottomInner));
    _cams.push_back(new CameraWrapper(this,*DataReceived,(path+"/CameraSettings/Ranger D50 TopInner.icx").toStdString(),"192.168.1.14","CamBottomOuter",caBottomOuter));
    _cams.push_back(new CameraWrapper(this,*DataReceived,(path+"/CameraSettings/Ranger D50 TopInner.icx").toStdString(),"192.168.1.15","CamSide",caSide));
}

void MeasurementSystem::Connect()
{
    foreach (CameraWrapper* cam, _cams)
    {
        cam->Connect();
    }
}

void MeasurementSystem::Disconnect()
{
    foreach (CameraWrapper* cam, _cams)
    {
        cam->Disconnect();
    }
}

void DataReceived(QObject * Sender, int & CamId, std::vector<int> & Profile)
{
    MeasurementSystem * CamSys = reinterpret_cast<MeasurementSystem*>(Sender);
    emit CamSys->sigDataReceived(CamId,Profile);
}
</code>```

CameraWrapper.h

```<code>#ifndef CAMERAWRAPPER_H
#define CAMERAWRAPPER_H

#include <QObject>
#include <icamerasystem.h>
#include <icamerasystemsubscriber.h>
#include <icon_error.h>
#include <windows.h>
typedef void CallbackDataT(QObject*,int&,std::vector<int>&);

class CameraWrapper : public icon::ICameraSystemSubscriber, public icon::ErrorHandler
{
public:
    CameraWrapper(QObject * Parent, CallbackDataT callback, std::string ConfigFileIcx, std::string IpAddr, std::string Name, int Id = -1);
    void Connect();
    void Disconnect();
    int AccessData(const icon::IconBuffer *buffer, std::string& resultString);
    virtual void onData(const icon::IconBuffer * buffer, const icon::IGrabStatus * status);
    virtual void onError(const icon::IError &error){};
    virtual void onStateChanged(const icon::IState * state){};

private:
    //IconAPI objects
    icon::ErrorCode _res;                                           //result of some camera operations
    icon::ICameraSystem * _camSystem;                               //the camera itself

    //callbacks
    void (*_callbackData)(QObject*,int&, std::vector<int>&);        //called when buffer is parsed

    //proprieties
    int _id;                                                        //camera identifier
    std::string _name;                                              //camera name

    //parent
    QObject * _parent;
};
#endif // CAMERAWRAPPER_H
</code>```

CameraWrapper.cpp

```<code>#include "camerawrapper.h"
#include <qdebug.h>             //qdebug()

CameraWrapper::CameraWrapper(QObject * Parent, CallbackDataT Callback, std::string ConfigFileIcx, std::string IpAddr, std::string Name, int Id):
    _parent(Parent), _callbackData(Callback), _id(Id), _name(Name)
{
    //Create the camera system object
    _camSystem = icon::createCameraSystem(icon::ICameraSystem::ETHERNET_CAMERA, Name.c_str());
    //smth else
}

void CameraWrapper::Connect()
{
    _res = _camSystem->subscribe(*this);
    _res = _camSystem->connect();
    _res = _camSystem->start();
}

void CameraWrapper::Disconnect()
{
    _res = _camSystem->stop();
    _res = _camSystem->disconnect();
}

int CameraWrapper::AccessData(const icon::IconBuffer * buffer, std::string& resultString)
{
    std::vector<int> vProfile;
    // Loop through all components in the buffer
    const icon::DataFormat *dataFormat = buffer->getDataFormat();
    for (unsigned int compIndex = 0; compIndex < dataFormat->numComponents(); compIndex++)
    {
        // Get handle to component.
        const icon::Component *component = dataFormat->getComponent(compIndex);

        // Loop through all subcomponents of the component.
        for (unsigned int subCompIndex = 0; subCompIndex < component->numSubComponents(); subCompIndex++)
        {
            const icon::SubComponent *subComponent = component->getSubComponent(subCompIndex);
            unsigned int subCompWidth = subComponent->getWidth();

            const unsigned short *wordData;
            unsigned short wordValue;
            buffer->getReadPointer(component->getName().c_str(), subComponent->getName().c_str(), 0, wordData);
            //rsv:push current scan into vector(profile view)
            for (size_t i = 0; i < subCompWidth; i++)
            {
                wordValue = *(wordData + i);
                vProfile.push_back(static_cast<int>(wordValue));
            }
        }
    }
    //callback is here
    _callbackData(_parent,_id,vProfile);
    return 0;
}

void CameraWrapper::onData(const icon::IconBuffer * buffer, const icon::IGrabStatus * status)
{
    if (!(status->allOK()))
    {
        return;
    }
    AccessData(buffer, outString);
}
</code>```

Title: Qt - Emit signal from callback

Body:
I am using the BGLib in my Qt application to communicate over BLE.

In the main thread the GUI is running (sensornode_gui.cpp). By clicking on a pushButton a different thread starts to scan for BLE devices (ble_connection). I get the resulting information from a callback function such as void ble_evt_gap_scan_response(const struct ble_msg_gap_scan_response_evt_t *msg). How can I emit signals from that callback function to update the GUI with some attributes from msg for example?

main.cpp

#include "sensornode_gui.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    SensorNode_GUI w;
    w.show();
    return a.exec();
}

sensornode_gui.h

#ifndef SENSORNODE_GUI_H
#define SENSORNODE_GUI_H

#include <QMainWindow>
#include <QThread>
#include "ble_connection.h"

namespace Ui {
class SensorNode_GUI;
}

class SensorNode_GUI : public QMainWindow
{
    Q_OBJECT

public:
    explicit SensorNode_GUI(QWidget *parent = 0);
    ~SensorNode_GUI();
    void printText(std::string s);

private slots:
    void on_pushButtonStartScanning_clicked();

private:
    Ui::SensorNode_GUI *ui;
    QThread *thread;
    BLE_Connection *ble_worker;

};

#endif // SENSORNODE_GUI_H

sensornode_gui.cpp

#include "sensornode_gui.h"
#include "ui_sensornode_gui.h"

SensorNode_GUI::SensorNode_GUI(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SensorNode_GUI)
{
    ui->setupUi(this);

    thread = new QThread();
    ble_worker = new BLE_Connection();
    ble_worker->setGUI(this);

    ble_worker->moveToThread(thread);
    connect(ble_worker, SIGNAL(valueChanged(QString)), ui->textEdit, SLOT(append(QString)));
    connect(ble_worker, SIGNAL(workRequested()), thread, SLOT(start()));
    connect(thread, SIGNAL(started()), ble_worker, SLOT(doWork()));
}

SensorNode_GUI::~SensorNode_GUI()
{
    delete thread;
    delete ble_worker;

    delete ui;
}

void SensorNode_GUI::printText(std::string s){
    ui->textEdit->append(QString::fromStdString(s));
}

void SensorNode_GUI::on_pushButtonStartScanning_clicked()
{
    ble_worker->requestWork();
}

ble_connection.h

#ifndef BLE_CONNECTION_H
#define BLE_CONNECTION_H

#include <QObject>
#include <QMutex>
#include <QDebug>
#include <QThread>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "cmd_def.h"
#include "apitypes.h"
#include "sensornode_gui.h"

class SensorNode_GUI;

class BLE_Connection : public QObject
{
    Q_OBJECT

public:
    explicit BLE_Connection(QObject *parent = 0);
    static void output(uint8,uint8*,uint16,uint8*);
    int read_message();
    void connect();
    void disconnect();

    void requestWork();

private:
    bool _abort;
    bool _working;
    QMutex mutex;

signals:
    void workRequested();
    void valueChanged(const QString &value);

public slots:
    void doWork();
};

#endif // BLE_CONNECTION_H

ble_connection.cpp

#include "ble_connection.h"

volatile HANDLE serial_handle;
uint8 connection_handle;

BLE_Connection::BLE_Connection(QObject *parent) :
    QObject(parent)
{
    char str[80];
    snprintf(str,sizeof(str)-1,"\\\\.\\%s","COM3");
    //open I/O device
    ...

    bglib_output = output;

}

void BLE_Connection::setGUI(SensorNode_GUI *g)
{
    gui = g;
}

void BLE_Connection::requestWork()
{
    mutex.lock();
    _working = true;
    _abort = false;
    qDebug()<<"Request worker start in Thread "<<thread()->currentThreadId();
    mutex.unlock();

    emit workRequested();
}

void BLE_Connection::doWork()
{
    while(true){
        read_message();
        qDebug() << "Within doWork";
        emit valueChanged(QString::fromStdString("Test"));
    }
}

void BLE_Connection::output(uint8 len1,uint8* data1,uint16 len2,uint8* data2)
{
    ...
}

int BLE_Connection::read_message()
{
    DWORD rread;
    const struct ble_msg *apimsg;
    struct ble_header apihdr;
    unsigned char data[256];//enough for BLE
    //read header

    if(!ReadFile(serial_handle,
               (unsigned char*)&apihdr,
               4,
               &rread,
               NULL))
        {
            return GetLastError();
        }
    if(!rread)return 0;
    //read rest if needed
    if(apihdr.lolen)
    {
        if(!ReadFile(serial_handle,
                   data,
                   apihdr.lolen,
                   &rread,
                   NULL))
            {
                return GetLastError();
            }
    }
    apimsg=ble_get_msg_hdr(apihdr);
    if(!apimsg)
    {
        printf("ERROR: Message not found:%d:%d\n",(int)apihdr.cls,(int)apihdr.command);
        return -1;
    }
    apimsg->handler(data);

    return 0;
}

//=============FUNCTIONS FOR HANDELING EVENTS AND RESPONSES====================

void ble_evt_gap_scan_response(const struct ble_msg_gap_scan_response_evt_t *msg)
{
    int i;
    std::string buffAsStdStr;
    char buff[100];
    char *name = NULL;
    for(i=0;i<6;i++){
        snprintf(buff, sizeof(buff), "%02x%s",msg->sender.addr[5-i],i<5?":":"");
        buffAsStdStr += buff;
    }

    snprintf(buff, sizeof(buff), "\t%d",msg->rssi);
    buffAsStdStr += buff;
    //HERE I WANT TO EMIT THE SIGNAL VALUECHANGED
    //emit valueChanged(QString::fromStdString(buffAsStdStr));

    free(name);
}

Thanks in advance.

Body:
I have faced to the same problem at using a different library. I have solved this issue by wrapping library class with mine (CameraWrapper), and put object of this class into my class (MeasurementSystem) inherited from QObject. So when this parent class creates wrapper for the class that sends callback, it passes pointer to itself QObject*. Child chass (CameraWrapper) stores this pointer and sends it within the callback.

Looks like this:

MeasurementSystem.h

#ifndef MEASUREMENTSYSTEM_H
#define MEASUREMENTSYSTEM_H
#include <vector>
#include "camerawrapper.h"
#include "qobject.h"

class MeasurementSystem : public QObject
{
    Q_OBJECT
public:
    MeasurementSystem();
    enum CamAlign {caTopInner = 0,caTopOuter,caBottomInner,caBottomOuter,caSide};   //cameras alignment in optical sysem

    void Connect();
    void Disconnect();
signals:
    void sigDataReceived(int,std::vector<int>);

private:
    std::vector<CameraWrapper*> _cams;
    friend void DataReceived(QObject * Sender, int &, std::vector<int>&);       //callback function for receiving data from any camera
};

#endif // MEASUREMENTSYSTEM_H

MeasurementSystem.cpp

#include "measurementsystem.h"
#include <QApplication>
MeasurementSystem::MeasurementSystem()
{
    QString path = QApplication::applicationDirPath();
    _cams.push_back(new CameraWrapper(this,*DataReceived,(path+"/CameraSettings/Ranger D50 TopInner.icx").toStdString(),"192.168.1.11","CamTopInner",caTopInner));
    _cams.push_back(new CameraWrapper(this,*DataReceived,(path+"/CameraSettings/Ranger D50 TopInner.icx").toStdString(),"192.168.1.12","CamTopOuter",caTopOuter));
    _cams.push_back(new CameraWrapper(this,*DataReceived,(path+"/CameraSettings/Ranger D50 TopInner.icx").toStdString(),"192.168.1.13","CamBottomInner",caBottomInner));
    _cams.push_back(new CameraWrapper(this,*DataReceived,(path+"/CameraSettings/Ranger D50 TopInner.icx").toStdString(),"192.168.1.14","CamBottomOuter",caBottomOuter));
    _cams.push_back(new CameraWrapper(this,*DataReceived,(path+"/CameraSettings/Ranger D50 TopInner.icx").toStdString(),"192.168.1.15","CamSide",caSide));
}

void MeasurementSystem::Connect()
{
    foreach (CameraWrapper* cam, _cams)
    {
        cam->Connect();
    }
}

void MeasurementSystem::Disconnect()
{
    foreach (CameraWrapper* cam, _cams)
    {
        cam->Disconnect();
    }
}

void DataReceived(QObject * Sender, int & CamId, std::vector<int> & Profile)
{
    MeasurementSystem * CamSys = reinterpret_cast<MeasurementSystem*>(Sender);
    emit CamSys->sigDataReceived(CamId,Profile);
}

CameraWrapper.h

#ifndef CAMERAWRAPPER_H
#define CAMERAWRAPPER_H

#include <QObject>
#include <icamerasystem.h>
#include <icamerasystemsubscriber.h>
#include <icon_error.h>
#include <windows.h>
typedef void CallbackDataT(QObject*,int&,std::vector<int>&);

class CameraWrapper : public icon::ICameraSystemSubscriber, public icon::ErrorHandler
{
public:
    CameraWrapper(QObject * Parent, CallbackDataT callback, std::string ConfigFileIcx, std::string IpAddr, std::string Name, int Id = -1);
    void Connect();
    void Disconnect();
    int AccessData(const icon::IconBuffer *buffer, std::string& resultString);
    virtual void onData(const icon::IconBuffer * buffer, const icon::IGrabStatus * status);
    virtual void onError(const icon::IError &error){};
    virtual void onStateChanged(const icon::IState * state){};

private:
    //IconAPI objects
    icon::ErrorCode _res;                                           //result of some camera operations
    icon::ICameraSystem * _camSystem;                               //the camera itself

    //callbacks
    void (*_callbackData)(QObject*,int&, std::vector<int>&);        //called when buffer is parsed

    //proprieties
    int _id;                                                        //camera identifier
    std::string _name;                                              //camera name

    //parent
    QObject * _parent;
};
#endif // CAMERAWRAPPER_H

CameraWrapper.cpp

#include "camerawrapper.h"
#include <qdebug.h>             //qdebug()

CameraWrapper::CameraWrapper(QObject * Parent, CallbackDataT Callback, std::string ConfigFileIcx, std::string IpAddr, std::string Name, int Id):
    _parent(Parent), _callbackData(Callback), _id(Id), _name(Name)
{
    //Create the camera system object
    _camSystem = icon::createCameraSystem(icon::ICameraSystem::ETHERNET_CAMERA, Name.c_str());
    //smth else
}

void CameraWrapper::Connect()
{
    _res = _camSystem->subscribe(*this);
    _res = _camSystem->connect();
    _res = _camSystem->start();
}

void CameraWrapper::Disconnect()
{
    _res = _camSystem->stop();
    _res = _camSystem->disconnect();
}

int CameraWrapper::AccessData(const icon::IconBuffer * buffer, std::string& resultString)
{
    std::vector<int> vProfile;
    // Loop through all components in the buffer
    const icon::DataFormat *dataFormat = buffer->getDataFormat();
    for (unsigned int compIndex = 0; compIndex < dataFormat->numComponents(); compIndex++)
    {
        // Get handle to component.
        const icon::Component *component = dataFormat->getComponent(compIndex);

        // Loop through all subcomponents of the component.
        for (unsigned int subCompIndex = 0; subCompIndex < component->numSubComponents(); subCompIndex++)
        {
            const icon::SubComponent *subComponent = component->getSubComponent(subCompIndex);
            unsigned int subCompWidth = subComponent->getWidth();

            const unsigned short *wordData;
            unsigned short wordValue;
            buffer->getReadPointer(component->getName().c_str(), subComponent->getName().c_str(), 0, wordData);
            //rsv:push current scan into vector(profile view)
            for (size_t i = 0; i < subCompWidth; i++)
            {
                wordValue = *(wordData + i);
                vProfile.push_back(static_cast<int>(wordValue));
            }
        }
    }
    //callback is here
    _callbackData(_parent,_id,vProfile);
    return 0;
}

void CameraWrapper::onData(const icon::IconBuffer * buffer, const icon::IGrabStatus * status)
{
    if (!(status->allOK()))
    {
        return;
    }
    AccessData(buffer, outString);
}


问:
How to make a photo frame over an image in android?
```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/ic_launcher" />

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:src="@drawable/ic_launcher" />
 </RelativeLayout>
</code>```

Here smaller image is on the top of larger image. I need the same size pictures but larger image should be on top of smaller image.Actually i want to make a photo frame app.The larger image is my photo frame. smaller image is my photo on which photo frame should appear.But in my app, photo is appearing on the photo frame.

i need exactly reverse. Please help me.

答:
Code provided by Noise Generator ( https://stackoverflow.com/a/22662631/5003906) works fine. But the code

```<code><?xml version="1.0" encoding="utf-8"?>
<nine-patch
xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center_horizontal|center_vertical"
android:src="@drawable/frame"
android:dither="true"
android:antialias="true" />
</code>```

Should be put in pf_frame.xml file.

PS : Sorry writing it as another answer because I don't have enough reputation to write comment.

Body:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/ic_launcher" />

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:src="@drawable/ic_launcher" />
 </RelativeLayout>

Here smaller image is on the top of larger image. I need the same size pictures but larger image should be on top of smaller image.Actually i want to make a photo frame app.The larger image is my photo frame. smaller image is my photo on which photo frame should appear.But in my app, photo is appearing on the photo frame.

i need exactly reverse. Please help me.

Body:
Code provided by Noise Generator ( https://stackoverflow.com/a/22662631/5003906) works fine. But the code

<?xml version="1.0" encoding="utf-8"?>
<nine-patch
xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center_horizontal|center_vertical"
android:src="@drawable/frame"
android:dither="true"
android:antialias="true" />

Should be put in pf_frame.xml file.

PS : Sorry writing it as another answer because I don't have enough reputation to write comment.


问:
How to automate AWS IAM instance profile creation with Ansible
I wanted to automate the creation of IAM instance profile with Ansible. I have looked at the module available in Ansible, but couldn't find any module that will do the job. I have managed to create an IAM role and attached a trust policy to it with the module

```<code>    iam_role:
      name: updatedns
      assum_role_policy_document: "{{ lookup('file', 'update-dns.json') }}
      state: present
</code>```

But as per AWS documentaiton when using AWSCLI we have to attach the role to an instance profile and that profile is then attached to the principal that we wish to attach it to, in my case EC2. Does anyone know about the Ansible module that will give me this functionality? or Should I use the shell command for awscli?

答:
Looks like that there is an open bug with Ansible on this issue:
https://github.com/ansible/ansible/issues/30036

Until resolved, I suggest you use the shell command for awscli.

Body:
I wanted to automate the creation of IAM instance profile with Ansible. I have looked at the module available in Ansible, but couldn't find any module that will do the job. I have managed to create an IAM role and attached a trust policy to it with the module

    iam_role:
      name: updatedns
      assum_role_policy_document: "{{ lookup('file', 'update-dns.json') }}
      state: present

But as per AWS documentaiton when using AWSCLI we have to attach the role to an instance profile and that profile is then attached to the principal that we wish to attach it to, in my case EC2. Does anyone know about the Ansible module that will give me this functionality? or Should I use the shell command for awscli?


问:
Dynamically set the config map name and values to read in helm?
I am new to helm charts. So please correct me if I am going wrong in understanding. I have a service which I am trying to deploy using helm charts. I want to change the config map name and its key values to read depending on deployment environment. Hence I want to add conditional logic in values.yaml.

Can someone point me to some document/link which explains how to add conditional logic in values.yaml?

答:
A chart's values.yaml is primarily used to set default values, regardless of the environment. It exists to fill chart templates with values. It is not designed to be a template itself, so there is no logic you can apply inside a values.yaml file.

Each environment should have its own values.yaml file. You could store those inside the chart itself, like:

```<code>.
├── Chart.yaml
├── README
├── templates
│   ├── config.yaml
│   ├── deployment.app.yaml
│   └── service.app.yaml
├── values.prod.yaml
├── values.test.yaml
└── values.yaml
</code>```

Now, when you deploy a chart, you can use the environment specific values.<env>.yaml to override the default values. For your test environment this may look like this:

```<code>helm upgrade --install my-chart path/to/my/chart --values path/to/my/chart/values.test.yaml
</code>```

Of course you could store the values.<env>.yaml files also outside of your chart directory. You just need to find a way to make them available at chart upgrade/install time to override the chart templates default values.yaml.

Body:
A chart's values.yaml is primarily used to set default values, regardless of the environment. It exists to fill chart templates with values. It is not designed to be a template itself, so there is no logic you can apply inside a values.yaml file.

Each environment should have its own values.yaml file. You could store those inside the chart itself, like:

.
├── Chart.yaml
├── README
├── templates
│   ├── config.yaml
│   ├── deployment.app.yaml
│   └── service.app.yaml
├── values.prod.yaml
├── values.test.yaml
└── values.yaml

Now, when you deploy a chart, you can use the environment specific values.<env>.yaml to override the default values. For your test environment this may look like this:

helm upgrade --install my-chart path/to/my/chart --values path/to/my/chart/values.test.yaml

Of course you could store the values.<env>.yaml files also outside of your chart directory. You just need to find a way to make them available at chart upgrade/install time to override the chart templates default values.yaml.


问:
Convert text in one line and write in a file (Python)
I'm trying to write some text in a file. These are email message and thus spanned over multiple line. What I want is that every message goes on a single line.
I'm using following code snippet:</p>

```<code>fh = open("hello.txt", "w")
fh.write(e.rstrip('\n'))

fh.close()
</code>```

答:
Assuming emails is a list of strings corresponding to your emails, you can do that :

```<code>emails = ["first email \n containing words and letters \n over several lines",
             "Second email \n same thing \n many words \n many lines"]
with open("hello.txt", "w") as fh:
    for email in emails:
        #we remove all newlines then add one at the end
        fh.write(email.replace("\n"," ")+"\n")
</code>```

Body:
I'm trying to write some text in a file. These are email message and thus spanned over multiple line. What I want is that every message goes on a single line.
I'm using following code snippet:

fh = open("hello.txt", "w")
fh.write(e.rstrip('\n'))

fh.close()

Body:
Assuming emails is a list of strings corresponding to your emails, you can do that :

emails = ["first email \n containing words and letters \n over several lines",
             "Second email \n same thing \n many words \n many lines"]
with open("hello.txt", "w") as fh:
    for email in emails:
        #we remove all newlines then add one at the end
        fh.write(email.replace("\n"," ")+"\n")


问:
Convert Image into byte array in Xamarin.Forms
I need to pass an image (Image _thresholdedImage) like byte array... I don't know how I can do this. Any idea? Thank you!

```<code>_thresholdedImage.Source = ImageSource.FromStream (() => photo.Source);

var tessResult = await _tesseractApi.SetImage(imageBytes);
</code>```

答:
Following code can use to convert image into byte array.Here CrossMedia plugin is used to capture image from camera.

```<code>public byte[] imageByte;
Stream imageStream = null;
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
       { Name = "pic.jpg"});
if (file == null) return;
imageStream = file.GetStream();
BinaryReader br = new BinaryReader(imageStream);
imageByte = br.ReadBytes((int)imageStream.Length);
</code>```

Body:
I need to pass an image (Image _thresholdedImage) like byte array... I don't know how I can do this. Any idea? Thank you!

_thresholdedImage.Source = ImageSource.FromStream (() => photo.Source);

var tessResult = await _tesseractApi.SetImage(imageBytes);

Body:
Following code can use to convert image into byte array.Here CrossMedia plugin is used to capture image from camera.

public byte[] imageByte;
Stream imageStream = null;
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
       { Name = "pic.jpg"});
if (file == null) return;
imageStream = file.GetStream();
BinaryReader br = new BinaryReader(imageStream);
imageByte = br.ReadBytes((int)imageStream.Length);


问:
Running Angular 2/4 Route instead of .net Core route
in my Angular Module I have the following Route:

```<code> { path: "something/:id", component: SomeComponent }
</code>```

which runs fine when using "routerLinks" frontend, but as soon as I manually write the ID in the URL and press Enter, It runs the C# backend method instead and ignores the angular route.

```<code>[HttpGet("{myid:guid}")]
</code>```

The backend method returns Json as it should but I cant get my Angular route to display my component, seeing I go straight to the Controller.

So my question is: How do I tell my application to run my frontend route instead of my backend route, or work my way around this problem when manually writing the id in the url?

Any help would be greatly appreciated.

答:
Have you tried configuring your startup.cs? On the configure method try:</p>

```<code> app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
</code>```

Body:
in my Angular Module I have the following Route:

 { path: "something/:id", component: SomeComponent }

which runs fine when using "routerLinks" frontend, but as soon as I manually write the ID in the URL and press Enter, It runs the C# backend method instead and ignores the angular route.

[HttpGet("{myid:guid}")]

The backend method returns Json as it should but I cant get my Angular route to display my component, seeing I go straight to the Controller.

So my question is: How do I tell my application to run my frontend route instead of my backend route, or work my way around this problem when manually writing the id in the url?

Any help would be greatly appreciated.

Body:
Have you tried configuring your startup.cs? On the configure method try:

 app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });


问:
Python, program that multiplies number by 2 til it's greater than 1000, having issue with syntax
When I put oursum outside of the loop it infinitely multiplies it by 2

```<code>usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
    print('Your number is '+str(usernum))
else:
     oursum=usernum*2
     while oursum<=1000:
          print('Multiplied by 2 equals '+str(oursum))
</code>```

When inside, it's not defined.

```<code>usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
   print('Your number is '+str(usernum))
else:

     while oursum<=1000:
          oursum=usernum*2
          print('Multiplied by 2 equals '+str(oursum))
</code>```

I understand the problems I'm making but I don't know how to rectify this without making it unnecessarily long and complicated. Thanks in advance.

答:
The issue is that you're saving the result of the multiplication inside oursum but you're not using oursum later to continue multiplicating.
The following should work and it doesn't add complexity to the code:

```<code>usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
    print('Your number is '+str(usernum))
else:
    oursum = usernum  # oursum starts from usernum and it will get bigger through each iteration
    while oursum<=1000:
        oursum=oursum*2
        print('Multiplied by 2 equals '+str(oursum))
</code>```

Body:
When I put oursum outside of the loop it infinitely multiplies it by 2

usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
    print('Your number is '+str(usernum))
else:
     oursum=usernum*2
     while oursum<=1000:
          print('Multiplied by 2 equals '+str(oursum))

When inside, it's not defined.

usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
   print('Your number is '+str(usernum))
else:

     while oursum<=1000:
          oursum=usernum*2
          print('Multiplied by 2 equals '+str(oursum))

I understand the problems I'm making but I don't know how to rectify this without making it unnecessarily long and complicated. Thanks in advance.

Body:
The issue is that you're saving the result of the multiplication inside oursum but you're not using oursum later to continue multiplicating.
The following should work and it doesn't add complexity to the code:

usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
    print('Your number is '+str(usernum))
else:
    oursum = usernum  # oursum starts from usernum and it will get bigger through each iteration
    while oursum<=1000:
        oursum=oursum*2
        print('Multiplied by 2 equals '+str(oursum))


问:
Can boost::smart_ptr be used in std containers?
Can boost::smart_ptr such as scoped_ptr and shared_ptr be used in std containers such as std::map?

```<code>class SomeClass
{
    std::map<int,boost::scoped_ptr<SomeOtherClass> > a_map;
};
</code>```

As boost::smart_ptr can be used for polymorphism, is it true in this case as well? Will the destruction of the container, trigger the correct destruction of the subclasses?

答:
scoped_ptr cannot be used in standard containers because it cannot be copied (which is required by the containers' interfaces). shared_ptr may be used, however.

If you can't use C++11 and you're using boost already, consider the pointer containers which will perform somewhat better than a container of shared pointers.

If you're using C++11, consider a container of unique_ptr, which should perform similarly to boost's pointer containers.

Body:
Can boost::smart_ptr such as scoped_ptr and shared_ptr be used in std containers such as std::map?

class SomeClass
{
    std::map<int,boost::scoped_ptr<SomeOtherClass> > a_map;
};

As boost::smart_ptr can be used for polymorphism, is it true in this case as well? Will the destruction of the container, trigger the correct destruction of the subclasses?


问:
Ignore visibility of outer elements and select the first visible child element in a jQuery selector
HTML:

```<code><div class="outer">
  <div id="inner1" class="inner" style="display: none"></div>
  <div id="inner2" class="inner"></div>
  <div id="inner3" class="inner"></div>
</div>
</code>```

JavaScript (fiddle):

```<code>var $first_visible = $("div.inner:visible:first");
</code>```

This returns the first visible inner div, which is inner2.

However, as soon as the outer div is hidden (let's say I want to fade it in at some later time):

```<code><div class="outer" style="display: none">
  <div id="inner1" class="inner" style="display: none"></div>
  <div id="inner2" class="inner"></div>
  <div id="inner3" class="inner"></div>
</div>
</code>```

all inner divs are considered hidden and the selector does not return inner2 any more.

How would I need to modify my jQuery selector to ignore the container's visibility?

答:
If I understood you correctly, you can simulate the effects of the parent being hidden using CSS like this.

HTML

```<code><div class="outer hide">
    <div id="inner1" class="inner hide">Inner 1</div>
    <div id="inner2" class="inner">Inner 2</div>
    <div id="inner3" class="inner">Inner 3</div>
</div>
</code>```

CSS

```<code>.hide {
    background: rgba(0,0,0,0);
    color: rgba(0,0,0,0);
    border-color: rgba(0,0,0,0);

    // For an SVG
    fill: rgba(0,0,0,0);
    stroke-opacity: 0;
}
</code>```

The reason why you can't use the visibility/display/opacity property is because as @Umesh mentioned that the all descendant elements will also get their display/visibility/opacity as not visible as if the element doesn't exist in the document tree.

But using this method you set the alpha to 0 of the element and this doesn't effect the descendants unless they have inherit set for those properties.

Hope this helps.

Body:
HTML:

JavaScript (fiddle):

var $first_visible = $("div.inner:visible:first");

This returns the first visible inner div, which is inner2.

However, as soon as the outer div is hidden (let's say I want to fade it in at some later time):

all inner divs are considered hidden and the selector does not return inner2 any more.

How would I need to modify my jQuery selector to ignore the container's visibility?

Body:
If I understood you correctly, you can simulate the effects of the parent being hidden using CSS like this.

HTML

<div class="outer hide">
    <div id="inner1" class="inner hide">Inner 1</div>
    <div id="inner2" class="inner">Inner 2</div>
    <div id="inner3" class="inner">Inner 3</div>
</div>

CSS

.hide {
    background: rgba(0,0,0,0);
    color: rgba(0,0,0,0);
    border-color: rgba(0,0,0,0);

    // For an SVG
    fill: rgba(0,0,0,0);
    stroke-opacity: 0;
}

The reason why you can't use the visibility/display/opacity property is because as @Umesh mentioned that the all descendant elements will also get their display/visibility/opacity as not visible as if the element doesn't exist in the document tree.

But using this method you set the alpha to 0 of the element and this doesn't effect the descendants unless they have inherit set for those properties.

Hope this helps.


问:
filter object_list in django template
I create a template with object_list table
I need filter by sub string then when the user will filter the table will updates online.

its not work. what the right way to do this?

I create view for this filter get the ajax request with substring value

def filters_points(request):

```<code>point_list = Point.objects.all()

try:

    req = request.GET.get("filterData")
    if req:
        point_list = Point.objects.filter(onsitePointName__icontains=req)

except AttributeError:
    print("failed")

#qs_json = serializers.serialize('json', point_list)
#return HttpResponse(qs_json, content_type='application/json')

return render_to_response('point/point_list_update.html', {'point_list': point_list})
</code>```

in HTML templete:

{% for point in point_list   %}
...
 {{ point.mangoId }}
 {{ point.onsitePointName }}
....

答:
option1:
you can use Custom template filter and tags from django docs

```<code> from django import template

 register = template.Library()

 @register.assignment_tag
 def get_filtered_points(qs, **kwargs):
   return qs.filter(**kwargs)
</code>```

template:
         {% get_filtered_points your_filter_query as new_point_list %}
          {% for book in new_point_list %}
            ...
          {% endfor %}

Note: Don't forget to load template tags in your template.

option 2: you can also use intercularjs for this as explained here

Title: filter object_list in django template

Body:
I create a template with object_list table
I need filter by sub string then when the user will filter the table will updates online.

its not work. what the right way to do this?

I create view for this filter get the ajax request with substring value

def filters_points(request):

point_list = Point.objects.all()

try:

    req = request.GET.get("filterData")
    if req:
        point_list = Point.objects.filter(onsitePointName__icontains=req)

except AttributeError:
    print("failed")

#qs_json = serializers.serialize('json', point_list)
#return HttpResponse(qs_json, content_type='application/json')

return render_to_response('point/point_list_update.html', {'point_list': point_list})

in HTML templete:

{% for point in point_list   %}
...
 {{ point.mangoId }}
 {{ point.onsitePointName }}
....

Body:
option1:
you can use Custom template filter and tags from django docs

 from django import template

 register = template.Library()

 @register.assignment_tag
 def get_filtered_points(qs, **kwargs):
   return qs.filter(**kwargs)

template:
         {% get_filtered_points your_filter_query as new_point_list %}
          {% for book in new_point_list %}
            ...
          {% endfor %}

Note: Don't forget to load template tags in your template.

option 2: you can also use intercularjs for this as explained here


问:
Java SWT exception : "java.lang.IllegalArgumentException" : Menu is not a POP_UP
I try to create a Menu using the SWT object "Menu".
Lines of codes are rather simple :

```<code>public static void main(String[] args) {

    createShell();
}

private static void createShell() {

    Display display = new Display();
    Shell shell = new Shell(display, SWT.SHELL_TRIM);

    Menu menu = new Menu(shell, SWT.BAR);
    shell.setMenu(menu);

    shell.open();

    while (! shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }

    display.dispose();

}
</code>```

At runtime, I get the following exception :

```<code>Exception in thread "main" java.lang.IllegalArgumentException: Menu is not a POP_UP
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.widgets.Widget.error(Unknown Source)
at org.eclipse.swt.widgets.Control.setMenu(Unknown Source)
at labo.Laboratory.createShell(Laboratory.java:25)
at labo.Laboratory.main(Laboratory.java:15)
</code>```

the swt code that seems to to be involved is the one from the "setMenu" method :

```<code>public void setMenu (Menu menu) {
checkWidget ();
if (menu != null) {
    if (menu.isDisposed()) error(SWT.ERROR_INVALID_ARGUMENT);
    if ((menu.style & SWT.POP_UP) == 0) {
        error (SWT.ERROR_MENU_NOT_POP_UP);
    }
    if (menu.parent != menuShell ()) {
        error (SWT.ERROR_INVALID_PARENT);
    }
}
this.menu = menu;
</code>```

}

Obvisously I go to the following line of code :

```<code>if ((menu.style & SWT.POP_UP) == 0) {
    error (SWT.ERROR_MENU_NOT_POP_UP);
}
</code>```

But I cannot understand why. The code I try to execute is given as a valid example everywhere, but it does not work for me.

I am using eclipse IDE, with a Java 8 JRE.
SWT library is the one provided by eclipse neon. The OS I am using is Windows 7.

I have reproduced this error with other computers and configurations, but curiously it seems that nobody else is facing it.

答:
The setMenu method sets the pop-up menu for any control. The menu style for this must be SWT.POP_UP.

You are probably looking for the setMenuBar method of Shell which sets to menu bar at the top of the window (top of the screen on macOS). This requires the menu style to be SWT.BAR.

Body:
I try to create a Menu using the SWT object "Menu".
Lines of codes are rather simple :

public static void main(String[] args) {

    createShell();
}

private static void createShell() {

    Display display = new Display();
    Shell shell = new Shell(display, SWT.SHELL_TRIM);

    Menu menu = new Menu(shell, SWT.BAR);
    shell.setMenu(menu);

    shell.open();

    while (! shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }

    display.dispose();

}

At runtime, I get the following exception :

Exception in thread "main" java.lang.IllegalArgumentException: Menu is not a POP_UP
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.widgets.Widget.error(Unknown Source)
at org.eclipse.swt.widgets.Control.setMenu(Unknown Source)
at labo.Laboratory.createShell(Laboratory.java:25)
at labo.Laboratory.main(Laboratory.java:15)

the swt code that seems to to be involved is the one from the "setMenu" method :

public void setMenu (Menu menu) {
checkWidget ();
if (menu != null) {
    if (menu.isDisposed()) error(SWT.ERROR_INVALID_ARGUMENT);
    if ((menu.style & SWT.POP_UP) == 0) {
        error (SWT.ERROR_MENU_NOT_POP_UP);
    }
    if (menu.parent != menuShell ()) {
        error (SWT.ERROR_INVALID_PARENT);
    }
}
this.menu = menu;

}

Obvisously I go to the following line of code :

if ((menu.style & SWT.POP_UP) == 0) {
    error (SWT.ERROR_MENU_NOT_POP_UP);
}

But I cannot understand why. The code I try to execute is given as a valid example everywhere, but it does not work for me.

I am using eclipse IDE, with a Java 8 JRE.
SWT library is the one provided by eclipse neon. The OS I am using is Windows 7.

I have reproduced this error with other computers and configurations, but curiously it seems that nobody else is facing it.


问:
Visual Studio OWIN Self-hosted App deployment
I've got an OWIN Self-Hosted SignalR app. I'm looking for a way to automatically deploy it to a different server (one is local, one is in Azure cloud) from Visual Studio. I'm not using IIS, I want to run it either as a normal app or as a Windows service.

What are my options?

答:
I advise you to consider using TopShelf

and here is the Nuget Package

All you need is to build and deploy the bin folder then just run one command


问:
Laravel 5 and Eloquent between two dates from database
I am a beginner with Laravel 5. I have a table: users with columns CreateDate, Type and Channel.

I have a list with users and I choose in View: Trans StartDate, Trans EndDate, Type and Channel.

I want to show: Tras StartDate < CreateDate < Trans EndDate with Type and Channel. name="time_start", "time_end", "type", "channel".

My Route:

```<code>Route::post('user', 'CSKHController@index');
</code>```

My Controller:

```<code>public function index() {

    $start = Input::get ( 'time_start' );
    $end = Input::get ( 'time_end' );

    $articles = KhachHang::all()->whereBetween('CreateDate', [$start, $end])->get();

    return view('admin/layouts/test', compact('stt','article'))->withDetails($articles);

}
</code>```

Help me please!

答:
Old question, but the answer isn't great. Use whereBetween(), which has been around since at least 5.0 docs

$articles = KhachHang::whereBetween('CreateDate', [$start, $end])->get();

Body:
I am a beginner with Laravel 5. I have a table: users with columns CreateDate, Type and Channel.

I have a list with users and I choose in View: Trans StartDate, Trans EndDate, Type and Channel.

I want to show: Tras StartDate < CreateDate < Trans EndDate with Type and Channel. name="time_start", "time_end", "type", "channel".

My Route:

Route::post('user', 'CSKHController@index');

My Controller:

public function index() {

    $start = Input::get ( 'time_start' );
    $end = Input::get ( 'time_end' );

    $articles = KhachHang::all()->whereBetween('CreateDate', [$start, $end])->get();

    return view('admin/layouts/test', compact('stt','article'))->withDetails($articles);

}

Help me please!


答:
In your second code, You are using oursum in the condition of the while statement before defining it. So, define oursum before the while loop and assign a value like 0

```<code>usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
   print('Your number is '+str(usernum))
else:
     oursum = 0 #like this
     while oursum<=1000:
          oursum=usernum*2
          print('Multiplied by 2 equals '+str(oursum))
</code>```

Title: Python, program that multiplies number by 2 til it's greater than 1000, having issue with syntax

Body:
In your second code, You are using oursum in the condition of the while statement before defining it. So, define oursum before the while loop and assign a value like 0

usernum=float(input('Enter a number: '))
if usernum<=0 or usernum>1000:
   print('Your number is '+str(usernum))
else:
     oursum = 0 #like this
     while oursum<=1000:
          oursum=usernum*2
          print('Multiplied by 2 equals '+str(oursum))


问:
Django Return Two Separate __str__ for a Model Form
I have a Task model that includes tasks and a foreign key to entities:

```<code>class Task(models.Model):
    task = models.CharField(max_length=500)
    entity = models.ForeignKey(Entity)
</code>```

I have a model that is related to one foreign key in Task:

```<code>class Entity(models.Model):
    entity = models.CharField(max_length=50)
    type = models.CharField(max_length=50)
    def __str__(self):
        return self.entity
</code>```

Task is placed into a Model Form:

```<code>class TaskForm(ModelForm):
    class Meta:
        model = Task
        fields = [
            'task',
            'entity'
        ]
</code>```

The Model Form is displayed in the template like this:

```<code>{{ form.task }}
{{ form.instance.entity }}
</code>```

How would I include the equivalent of {{ form.instance.type }}? This would involve somehow including two __str__ representations in the same model form. I have seen label_from_instance used in overriding the model form, but this looks like it's only possible with ModelChoiceFields. In addition, it would render the field as a widget rather than text (like form.instance).

答:
In the template, form.instance.entity is the instance's related entity. If you want to display the type field, you can simply use:

```<code>{{ form.instance.entity.type }}
</code>```

To answer the question in your title, each model can only have one __str__ method. You could define another method or property that returns a string, but there's no need to do this if you just want to display the type field.

Body:
I have a Task model that includes tasks and a foreign key to entities:

class Task(models.Model):
    task = models.CharField(max_length=500)
    entity = models.ForeignKey(Entity)

I have a model that is related to one foreign key in Task:

class Entity(models.Model):
    entity = models.CharField(max_length=50)
    type = models.CharField(max_length=50)
    def __str__(self):
        return self.entity

Task is placed into a Model Form:

class TaskForm(ModelForm):
    class Meta:
        model = Task
        fields = [
            'task',
            'entity'
        ]

The Model Form is displayed in the template like this:

{{ form.task }}
{{ form.instance.entity }}

How would I include the equivalent of {{ form.instance.type }}? This would involve somehow including two __str__ representations in the same model form. I have seen label_from_instance used in overriding the model form, but this looks like it's only possible with ModelChoiceFields. In addition, it would render the field as a widget rather than text (like form.instance).

Body:
In the template, form.instance.entity is the instance's related entity. If you want to display the type field, you can simply use:

{{ form.instance.entity.type }}

To answer the question in your title, each model can only have one __str__ method. You could define another method or property that returns a string, but there's no need to do this if you just want to display the type field.


问:
Passing an urlencoded URL as parameter to a controller / action at CakePHP
I'm fairly new on CakePHP and because of so, there are some basic things that I used to do with Zend Framework that I'm beaten up with Cake.

I'm working on a project where I have to pass a named parameter to a controller / action. Setting up the route and passing the parameter is fairly simple, my problem is when the parameter is a urlencoded url.

For example: http://www.cakephp.com/controller/action/http%3A%2F%2Fwww.google.com regardless of the controller and action setup, will throw a 404, but passing /controller/action/http://www.google.com work in some way, the only problem is that it identifies the http as a named parameter. In another way, if I do /controller/action?url=http://www.google.com it will work.

The work around that I had used for this is to pass the value as a base64 encoded string, but it brings some limitations. For instance, if it is an API, there is no way that you can guarantee that the system using the API can encode base64 a string.

Anyway the best solution would be still passing a url encoded string to a named parameter. Question is, why CakePHP does not accept a urlencoded string as a parameter and why does it throws a 404?

Thanks all in advance.

答:
I have added a work around this issue. The previous answer that pointed to a post actually answered why it was happening and one of the solutions. What happens is that the workaround for .htaccess on Apache is a bit dangerous because it will disable a security criteria.

There are 2 ways to work this out via code (and I'm using both):

Send all urls as base64 encoded strings

Accept the urls as named params, but, as you will notice, it converts any http:// to http:/, so is necessary to correctly identify when this happens and only then correct the string.

It is far from being a beautiful solution, but it is definitely a practical one.


问:
How to create a vector with components bigger than a number in numpy?
For example, I have a vector like this:

```<code>v = np.array([2, 4, 1, 7, 9, 3, 5])
</code>```

I want to compare each component to a number to obtain a new vector which components are bigger of equal to the number (in case if the original component is less). For the above example and limit=3 the result should be:

```<code>np.array([3, 4, 3, 7, 9, 3, 5])
</code>```

How can I do it with numpy?

答:
You can simply do

```<code>v[v <= 3] = 3
</code>```

which gives you the desired output:

```<code>array([3, 4, 3, 7, 9, 3, 5])
</code>```

Brief explanation:

```<code>v <= 3
</code>```

creates a Boolean array

```<code>array([ True, False,  True, False, False,  True, False], dtype=bool)
</code>```

and the command

```<code>v[v <= 3]
</code>```

sets all values to 3 where this Boolean array evaluates to True.

Body:
For example, I have a vector like this:

v = np.array([2, 4, 1, 7, 9, 3, 5])

I want to compare each component to a number to obtain a new vector which components are bigger of equal to the number (in case if the original component is less). For the above example and limit=3 the result should be:

np.array([3, 4, 3, 7, 9, 3, 5])

How can I do it with numpy?

Body:
You can simply do

v[v <= 3] = 3

which gives you the desired output:

array([3, 4, 3, 7, 9, 3, 5])

Brief explanation:

v <= 3

creates a Boolean array

array([ True, False,  True, False, False,  True, False], dtype=bool)

and the command

v[v <= 3]

sets all values to 3 where this Boolean array evaluates to True.


问:
How to get those unique lable in a mask with efficient with OpenCV
If I have a such label image

Then I have a such mask

I want to get those unique integer lables in the given mask(same size with the label image). The result is {0,1,2,3,6} in my this example. This is my current method

```<code>#include<opencv.hpp>
#include<string>
using namespace std;
using namespace cv;

int main() {
    uchar a[6][7] = { { 0,0,0,0,0,0,0 },{ 0,1,2,2,3,3,0 },{ 0,0,0,0,0,0,0 },{ 0,5,5,6,6,0,0 },{ 0,5,5,6,6,0,0 },{ 0,0,0,0,0,0,0 } };
    Mat label = Mat(6, 7, CV_8UC1, a);
    uchar b[6][7]= { { 0,0,0,0,0,0,0 },{ 0,255,255,255,255,0,0 },{ 255,255,255,0,0,0,0 },{ 0,0,0,255,255,0,0 },{ 0,0,0,255,255,0,0 },{ 0,0,0,0,0,0,0 } };
    Mat mask = Mat(6, 7, CV_8UC1, b);
    vector<int> list;
    for (int i = 0; i < mask.rows; i++) {
        uchar* mask_p = mask.ptr<uchar>(i);
        for (int j = 0; j < mask.cols; j++)
            if (mask_p[j] == 255)
                list.push_back(int(label.at<uchar>(i,j)));
    }
    sort(list.begin(), list.end());
    list.erase(unique(list.begin(), list.end()), list.end());

    return 0;
}
</code>```

But in my real case, I have just a small ROI in a huge mask image. I think the current method which iterate every pixel in the mask waste my time too much in my case. Can anyone give me some advice?

Body:
If I have a such label image

Then I have a such mask

I want to get those unique integer lables in the given mask(same size with the label image). The result is {0,1,2,3,6} in my this example. This is my current method

#include<opencv.hpp>
#include<string>
using namespace std;
using namespace cv;

int main() {
    uchar a[6][7] = { { 0,0,0,0,0,0,0 },{ 0,1,2,2,3,3,0 },{ 0,0,0,0,0,0,0 },{ 0,5,5,6,6,0,0 },{ 0,5,5,6,6,0,0 },{ 0,0,0,0,0,0,0 } };
    Mat label = Mat(6, 7, CV_8UC1, a);
    uchar b[6][7]= { { 0,0,0,0,0,0,0 },{ 0,255,255,255,255,0,0 },{ 255,255,255,0,0,0,0 },{ 0,0,0,255,255,0,0 },{ 0,0,0,255,255,0,0 },{ 0,0,0,0,0,0,0 } };
    Mat mask = Mat(6, 7, CV_8UC1, b);
    vector<int> list;
    for (int i = 0; i < mask.rows; i++) {
        uchar* mask_p = mask.ptr<uchar>(i);
        for (int j = 0; j < mask.cols; j++)
            if (mask_p[j] == 255)
                list.push_back(int(label.at<uchar>(i,j)));
    }
    sort(list.begin(), list.end());
    list.erase(unique(list.begin(), list.end()), list.end());

    return 0;
}

But in my real case, I have just a small ROI in a huge mask image. I think the current method which iterate every pixel in the mask waste my time too much in my case. Can anyone give me some advice?

Body:
This new method can avoid to iterate every pixel, which is more faster in the huge mask

#include<string>
#include<opencv.hpp>
using namespace std;
using namespace cv;

int main() {
    uchar a[6][7] = { { 0,0,0,0,0,0,0 },{ 0,1,2,2,3,3,0 },{ 0,0,0,0,0,0,0 },{ 0,5,5,6,6,0,0 },{ 0,5,5,6,6,0,0 },{ 0,0,0,0,0,0,0 } };
    Mat label = Mat(6, 7, CV_8UC1, a);
    uchar b[6][7] = { { 0,0,0,0,0,0,0 },{ 0,255,255,255,255,0,0 },{ 255,255,255,0,0,0,0 },{ 0,0,0,255,255,0,0 },{ 0,0,0,255,255,0,0 },{ 0,0,0,0,0,0,0 } };
    Mat mask = Mat(6, 7, CV_8UC1, b);

    Mat mat = label&mask;
    mat = mat.reshape(1, 1);
    vector<int> vec;
    mat.row(0).copyTo(vec);
    sort(vec.begin(), vec.end());
    vec.erase(unique(vec.begin(), vec.end()), vec.end());

    return 0;
}