text:
Q: Why does jemalloc take more time to allocate 4096 bytes of memory than other SMALL memory? In the process of testing the performance of jemalloc-5.2.0 to allocate small_class memory, it was found that the memory allocation time of 4096 bytes was significantly higher than that of other small class memory. Is there any special handling for 4096 bytes memory allocation in jemalloc? Or is there any other reason?
Test results:

*

*Use google benchmark with multithreaded test (24threads).

Run on (32 X 3400 MHz CPU s)
CPU Caches:
  L1 Data 32 KiB (x16)
  L1 Instruction 32 KiB (x16)
  L2 Unified 256 KiB (x16)
  L3 Unified 20480 KiB (x2)
Load Average: 15.72, 14.21, 14.26
-----------------------------------------------------------------------------------------
Benchmark                                               Time             CPU   Iterations
-----------------------------------------------------------------------------------------
BM_SomeFunction/1792/iterations:500/threads:24      0.095 ms         2.12 ms        12000
BM_SomeFunction/1856/iterations:500/threads:24      0.175 ms         4.10 ms        12000
BM_SomeFunction/1920/iterations:500/threads:24      0.178 ms         4.13 ms        12000
BM_SomeFunction/1984/iterations:500/threads:24      0.177 ms         4.14 ms        12000
BM_SomeFunction/2048/iterations:500/threads:24      0.181 ms         4.18 ms        12000
BM_SomeFunction/2048/iterations:500/threads:24      0.177 ms         4.16 ms        12000
BM_SomeFunction/2176/iterations:500/threads:24      0.116 ms         2.67 ms        12000
BM_SomeFunction/2304/iterations:500/threads:24      0.113 ms         2.64 ms        12000
BM_SomeFunction/2432/iterations:500/threads:24      0.118 ms         2.75 ms        12000
BM_SomeFunction/2560/iterations:500/threads:24      0.113 ms         2.65 ms        12000
BM_SomeFunction/2560/iterations:500/threads:24      0.114 ms         2.68 ms        12000
BM_SomeFunction/2688/iterations:500/threads:24      0.133 ms         3.13 ms        12000
BM_SomeFunction/2816/iterations:500/threads:24      0.132 ms         3.08 ms        12000
BM_SomeFunction/2944/iterations:500/threads:24      0.131 ms         3.09 ms        12000
BM_SomeFunction/3072/iterations:500/threads:24      0.132 ms         3.10 ms        12000
BM_SomeFunction/3072/iterations:500/threads:24      0.132 ms         3.11 ms        12000
BM_SomeFunction/3200/iterations:500/threads:24      0.117 ms         2.72 ms        12000
BM_SomeFunction/3328/iterations:500/threads:24      0.113 ms         2.66 ms        12000
BM_SomeFunction/3456/iterations:500/threads:24      0.111 ms         2.61 ms        12000
BM_SomeFunction/3584/iterations:500/threads:24      0.112 ms         2.63 ms        12000
BM_SomeFunction/3584/iterations:500/threads:24      0.112 ms         2.63 ms        12000
BM_SomeFunction/3712/iterations:500/threads:24      0.271 ms         6.35 ms        12000
BM_SomeFunction/3840/iterations:500/threads:24      0.270 ms         6.35 ms        12000
BM_SomeFunction/3968/iterations:500/threads:24      0.274 ms         6.42 ms        12000
BM_SomeFunction/4096/iterations:500/threads:24      0.276 ms         6.49 ms        12000
BM_SomeFunction/4096/iterations:500/threads:24      0.273 ms         6.41 ms        12000
BM_SomeFunction/4352/iterations:500/threads:24      0.151 ms         3.53 ms        12000
BM_SomeFunction/4608/iterations:500/threads:24      0.146 ms         3.45 ms        12000
BM_SomeFunction/4864/iterations:500/threads:24      0.142 ms         3.36 ms        12000
BM_SomeFunction/5120/iterations:500/threads:24      0.144 ms         3.40 ms        12000
BM_SomeFunction/5120/iterations:500/threads:24      0.146 ms         3.40 ms        12000
BM_SomeFunction/5376/iterations:500/threads:24      0.196 ms         4.57 ms        12000
BM_SomeFunction/5632/iterations:500/threads:24      0.187 ms         4.39 ms        12000
BM_SomeFunction/5888/iterations:500/threads:24      0.191 ms         4.47 ms        12000
BM_SomeFunction/6144/iterations:500/threads:24      0.188 ms         4.39 ms        12000

test report:
BM_SomeFunction/1792/iterations:500/threads:24      0.095 ms         2.12 ms        12000

means allocating 1792 byte of memory consumes 2.12 ms CPU time.
Test code
#include "benchmark/benchmark.h"
#include "jemalloc/jemalloc.h"

static size_t kBatchSize = 10000;

static void alloc_mem_n(size_t size) {
    std::vector<char*> kVec(kBatchSize, 0);
    for (int i = 0; i < kBatchSize; ++i) {
        auto p = new char[size];
        p[0] = i;
        benchmark::ClobberMemory();
        kVec[i] = p;
    }
    for (auto &p : kVec) {
        delete p;
        p = nullptr;
    }
}

static void BM_SomeFunction(benchmark::State& state) {
    for (auto _ : state) {
        alloc_mem_n(state.range(0));
    }
}

BENCHMARK(BM_SomeFunction)
    ->Unit(benchmark::kMillisecond)
    ->Iterations(500)
    ->Threads(24)
    ->DenseRange(1792, 2048, 64)
    ->DenseRange(2048, 2560, 128)
    ->DenseRange(2560, 3072, 128)
    ->DenseRange(3072, 3584, 128)
    ->DenseRange(3584, 4096, 128)
    ->DenseRange(4096, 5120, 256)
    ->DenseRange(5120, 6144, 256);

BENCHMARK_MAIN();

A: Jemalloc uses slab for allocating small sizes, and size of slab is equal to the least common multiple of the allocated size and page size.
In this case, allocated_size == page_size == slab_size == 4096, which means that a slab of 4096 bytes can satisfy only one allocation of 4096 bytes.


text:
Q: Cufon + jQuery hover not working Alright, here's the problem:
I'm building a  website, utilizing jQuery and Cufon. I'm having a problem with using jQuery's .hover() function alongside Cufon. When I hover over the Cufon'd text, nothing happens. The code of importance is:
Cufon.replace('div.nav', {hover:'true'});
$(document).ready(function() {
    $('div.nav').each(function() {
        $(this).hover(function() {
            $(this).css({
                "text-decoration": "underline;",
            });
        },
        function() {
            $(this).css({
                "text-decoration": "none;",
            });
        });
    });
});

and

        SLA ROBOTICS

            members

            robots

            sponsors

The rest of the code is visible by viewing the source of the above link. No PHP, so everything's visible.

A: Cufon is a fine library, but it may not support all features of normal text. Consider using webfonts, generated by Font Squirrel.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the best way to store thumbnails for a non-image attachment? I'm in the process of extending Document Gallery to support generating and displaying thumbnails for each document.
I've got thumbnail generation under control, but I'm curious as to what best practices for storing both the physical image files for each thumb and the references to these file paths. The research I've done thus far turned up attachment thumbnails (which appear to be different than Post Thumbnails) and these seem like an ideal foundation for creating this new functionality without reinventing the wheel. Documentation on how to hook into this existing framework, specifically, creating new attachment thumbnails, seems to be quite sparse. As much as possible, I'd like to use existing functionality rather than duplicating functionality.
With this in mind, looking at wp_get_attachment_thumb_file (below), it seems like I could simply set the thumb filed in attachment metadata to the name of the thumbnail which would live in the same directory as the attachment file. In doing this, I would also indirectly handle removing the thumbnail file when the attachment is deleted since wp_delete_attachment checks for a thumbnail on deletion and removes it if present.
I believe this solution will work, but I was hoping someone with a working knowledge of all of this could verify not only that it will work but, more importantly, whether it is the "best" way to handle my needs.
function wp_get_attachment_thumb_file( $post_id = 0 ) {
    $post_id = (int) $post_id;
    if ( !$post = get_post( $post_id ) )
        return false;
    if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
        return false;

    $file = get_attached_file( $post->ID );

    if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) )
        return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
    return false;
}


text:
Q: sqlalchemy join two tables together I am wanting to map a class object to a table that is a join between two tables, and all the columns from one table and only one column from the joined table being selected (mapped).
join_table = join(table1, table2, tabl1.c.description==table2.c.description)
model_table_join= select([table1, table2.c.description]).select_from(join_table).alias()

Am I doing this right?

A: If all you want to do is pull in one extra column from a JOIN, I'd not muck about with an arbitrary select mapping. As the documentation points out:

The practice of mapping to arbitrary SELECT statements, especially complex ones as above, is almost never needed; it necessarily tends to produce complex queries which are often less efficient than that which would be produced by direct query construction. The practice is to some degree based on the very early history of SQLAlchemy where the mapper() construct was meant to represent the primary querying interface; in modern usage, the Query object can be used to construct virtually any SELECT statement, including complex composites, and should be favored over the "map-to-selectable" approach.

You'd just either select that extra column in your application:
session.query(Table1Model, Table2Model.description).join(Table2Model)

or you can register a relationship on the Table1Model and an association property that always pulls in the extra column:
class Table1Model(Base):
    # ...

    _table2 = relationship('Table2Model', lazy='join')
    description = association_proxy('_table2', 'description')

The association property manages the Table2Model.description column of the joined row as you interact with it on Table1Model instances.
That said, if you must stick with a join() query as the base, then you could just exclude the extra, duplicated columns from the join, with a exclude_properties mapper argument:
join_table = join(table1, table2, table1.c.description == table2.c.description)

class JoinedTableModel(Base):
    __table__ = join_table
    __mapper_args__ = {
        'exclude_properties' : [table1.c.description]
    }

The new model then uses all the columns from the join to create attributes with the same names, except for those listed in `exclude_properties.
Or you can keep using duplicated column names in the model simply by giving them a new name:
join_table = join(table1, table2, table1.c.description == table2.c.description)

class JoinedTableModel(Base):
    __table__ = join_table

    table1_description = table1.c.description

You can rename any column from the join this way, at which point they will no longer conflict with other columns with the same base name from the other table.


text:
Q: When does a system of linear congruences in multiple variables have a solution. If I'm given a list of m linear congruences in n variables, how can I efficniently (in polynomial time) tell if they have a unique solution, no solution or many solutions?
Example:
$a_{11}.x_{1}+a_{12}.x_{2}+...+a_{1n}x_{n} \equiv b_{1}\ mod\ 2$
$a_{21}.x_{1}+a_{22}.x_{2}+...+a_{2n}x_{n} \equiv b_{2}\ mod\ 2$
.
.
.
$a_{m1}.x_{1}+a_{m2}.x_{2}+...+a_{mn}x_{n} \equiv b_{m}\ mod\ 2$


text:
Q: Execute two Zenity dialogs side by side I want to write a script in bash using zenity for UI. My idea is to have 2 diaglos open side by side: one to interact with user and second to display results. Is it possible to set positions of these dialogs to avoid dialogs overlapping?

A: Combine 2 scripts using zenity. The main for the output and the child for the UI input.


text:
Q: Show that $x^5-x^2-4=0$ has at least one real root Proof
Since $x^5-x^2-4=0$ is a polynomial it is continuous on any interval [a,b] such that a,b are real numbers
say:
$f(a)= x$ such that $x<0$
$f(b)=z$ such that $z>0$
$k=0$
Since k is between $x$ and $z$ by the intermediate value theorem it follows that there is a number $c$ such that $f(c)=c^5-c^2-4=0$

A: Hint: What is $x \to \infty$? What is $x \to -\infty$. What does the intermediate value theroem say? For the limits you can use $f(x)=x^5(1-1/x^3-4/x^5)$

A: Here is maybe an other interesting proof.
If $c$ is a complex root, then $\overline{c}$ is also a complex root. It follows from the fact that $$P(\overline{c}) =\overline{\overline{P}(c)}=\overline{P(c)}=0,$$ since your polynomial $P$ has real coefficients. Hence the number of complex (non real) roots is always even.
Here because the degree of your polynomial is odd, you have at least one real root. (Because you can only have $0,2$ or $4$ complex non real roots, but not $5$.)
This can be easily generalized : if $P$ is a polynomial with odd degree and with coefficients in $\mathbb{R}$, then it has at least one real root.

A: This particular problem
is a special case
of this theorem:
A polynomial
$p(x)
=\sum_{k=0}^d a_k x^k
$
with $a_d > 0$
and
$a_0 < 0
$
has a positive real root.
Proof:
$p(0) = a_0
< 0$
and,
for large enough $x$,
$p(x) > 0$
(because $a_d > 0$).
By the intermediate value theorem,
$p$ has a positive root.


text:
Q: RestKit - postObject skip parameters I am trying to POST an object to server, but it is not working. This is what I am doing. FYI, I am using MagicalRecords for CoreData easy handling.
DBComments *comment = [DBComments MR_createEntity];
comment.body = @"This is body";
comment.subject = @"This is subject";
comment.commentable_id = [NSNumber numberWithInt:291110];
comment.send_email = [NSNumber numberWithBool:YES];

[[RKObjectManager sharedManager] postObject:comment path:URL_COMMENTS
                                     parameters:nil
                                        success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                            KLog(@"success");
                                        } failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                            KLog(@"fail");
                                        }];

But I get following response:
E restkit.network:RKObjectRequestOperation.m:576 Object request failed: Underlying HTTP request operation failed with error: Error Domain=org.restkit.RestKit.ErrorDomain Code=-1011 "Expected status code in (200-299), got 400" UserInfo=0x11b688c0 {NSLocalizedRecoverySuggestion={"error":"body is missing, commentable_id is missing"}, AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest: 0xc632e50> { URL: http://10.28.79.98:3002/comments }, NSErrorFailingURLKey=http://10.28.79.98:3002/comments, NSLocalizedDescription=Expected status code in (200-299), got 400, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xc23cf70> { URL: http://10.28.79.98:3002/comments } { status code: 400, headers {
    "Cache-Control" = "no-cache";
    Connection = "Keep-Alive";
    "Content-Length" = 54;
    "Content-Type" = "application/json";
    Date = "Fri, 28 Mar 2014 07:45:01 GMT";
    Server = "WEBrick/1.3.1 (Ruby/1.9.3/2012-04-20)";
    "X-Request-Id" = c8b765e61a8d44020be26e9b3267096e;
    "X-Runtime" = "0.010554";
    "X-Ua-Compatible" = "IE=Edge";
} }}

As you can see in response, the values are not being POSTed
{"error":"body is missing, commentable_id is missing"}

Here is my mapping config
[objectManager addRequestDescriptorsFromArray:@[
                                                    // Comments
                                                    [RKRequestDescriptor requestDescriptorWithMapping:[self commentsRequestMapping]
                                                                                objectClass:[DBComments class]
                                                                                rootKeyPath:@""
                                                                                method:RKRequestMethodPOST],
                                                    ]];

- (RKObjectMapping *)commentsRequestMapping {
    RKObjectMapping *commentsRequestMapping = [RKObjectMapping requestMapping];
    [commentsRequestMapping addAttributeMappingsFromDictionary:@{
                                                                 @"body" : @"body",
                                                                 @"commentable_id" : @"commentable_id",
                                                                 @"commentable_type" : @"commentable_type",
                                                                 @"created_at" : @"created_at",
                                                                 @"id" : @"id",
                                                                 @"lft" : @"lft",
                                                                 @"parent_id" : @"parent_id",
                                                                 @"rgt" : @"rgt",
                                                                 @"subject" : @"subject",
                                                                 @"title" : @"title",
                                                                 @"updated_at" : @"updated_at",
                                                                 @"user_id" : @"user_id",
                                                                 @"send_email" : @"send_email",
                                                                 }];

    return commentsRequestMapping;
}

I have never been able to use postObject successfully. Am I missing something? Please help.

A: If the server is expecting a flat set of content then the request descriptor should have a nil key path, not an empty string.
It's important that what you send matches what the server expects and you should use a combination of trace logging and Charles (or a similar tool) to verify what your code is actually producing.


text:
Q: Showing that $|A\cap B|/|A \cup B| + |B\cap C|/|B \cup C| - |A\cap C|/|A \cup C| \leq 1$ for finite sets $A,B,C$.
If $A$, $B$ and $C$ are finite sets, prove that
  $$
 \frac{|A\cap B|}{|A \cup B|}
 + \frac{|B\cap C|}{|B \cup C|}
 - \frac{|A\cap C|}{|A \cup C|}
 \leq 1.
$$

It seem's simple, but I tried it for a long time and cannot get it out. Maybe I can use some optimization methods to calculate it, but that's not what I want...

A:
I'm referring to the Venn diagram above. The indicated variables denote the numbers of elements in the particular component, and are integers $\geq0$.
We have to prove that
$$\eqalign{&{z+y_3\over x_1+x_2+y_1+y_2+y_3+z}+{z+y_1\over x_2+x_3+y_1+y_2+y_3+z}\cr
&\qquad\leq1+{z+y_2\over x_1+x_3+y_1+y_2+y_3+z}\ .\cr}\tag{1}$$
During the proof we shall use several times the fact that the function
$$t\mapsto{a+t\over b+t}\qquad(t>0)$$
is monotonically increasing when $0\leq a\leq b$.
As $x_2$ is not appearing on the RHS of $(1)$ we may assume $x_2=0$. Furthermore, the  LHS of $(1)$  decreases when $y_2$ increases, whereas  the mentioned principle  shows that the RHS of $(1)$ is an increasing function of $y_2$. It follows that we may assume $y_2=0$ as well.
Put $y_1+y_3+z=:s$. Then we have to prove
$${s-y_1\over s+x_1}+{s-y_3\over s+x_3}\leq 1+{s-y_1-y_3\over s+x_1+x_3}\ .\tag{2}$$
Here the RHS can be rewitten as
$${s-y_1+x_3\over s+x_1+x_3}+{s-y_3+x_1\over s+x_3+x_1}\ .$$
Now by the aforementioned principle we have
$${s-y_1\over s+x_1}\leq{s-y_1+x_3\over s+x_1+x_3}\ ,$$
and similarly for the second parts. This proves $(2)$, which is the "worst case" of $(1)$.

A: Let $|A|= a,\quad |B|= b,\quad |C|= c \quad$ then
$0 \le |A \cap B|=n_1 \le a$ or $b$ $\quad $ And $\quad $ $a$ or $b \le |A \cup B|=u_1 \le a+b $
$\implies n_1 \le u_1$
$0 \le |B \cap C|=n_2 \le b$ or $c$ $\quad $ And $\quad $ $b$ or $c \le |B \cup C|=u_2 \le b+c$
$\implies n_2 \le u_2$
$0 \le |A \cap C|=n_3 \le a$ or $c$ $\quad $ And $\quad $ $a$ or $c \le |A \cup C|=u_3 \le a+c$
$\implies n_3 \le u_3$
So we have
$\frac{n_1}{u_1} + \frac{n_2}{u_2} - \frac{n_3}{u_3} = \frac{n_1u_2u_3 + u_1n_2u_3 - u_1u_2n_3}{u_1u_2u_3}$
Case-1:  If $n_i = u_i \quad \forall 1 \le i \le 3$, then
$\frac{u_1u_2u_3 + u_1u_2u_3 - u_1u_2u_3}{u_1u_2u_3} = 1$
Case-2: If $n_i < u_i \quad \forall 1 \le i \le 3$, then
$\frac{n_1u_2u_3 + u_1n_2u_3 - u_1u_2n_3}{u_1u_2u_3} < \frac{u_1u_2u_3 + u_1u_2u_3 - u_1u_2u_3}{u_1u_2u_3}$
$\frac{n_1u_2u_3 + u_1n_2u_3 - u_1u_2n_3}{u_1u_2u_3} < 1$


text:
Q: Filtering data to only keep up to 10 duplicates in two variables, with missing data We have survey data for a survey that respondents can take multiple times, and we want to retain only the first 10 entries per respondent.  The respondent must provide either an email address or a phone number, which we want to use to check for duplicates.
Using R, I ordered the data by response date, and used the following code to add counts for the email addresses and phone numbers:
surveydata <- surveydata %>%
  group_by(email) %>%
  mutate(email_count = row_number())
surveydata <- surveydata %>%
  group_by(phone) %>%
  mutate(phone_count = row_number())

I thought that I could just filter out the entries where email_count or phone_count was over 10.  However this process also counted all of the NAs together, so if I filtered out all of the entries with counts over 10, I'd be deleting a lot of entries that we actually want to keep.
I tried the following if statement to try to reset the email_count and phone_count if the email or phone entries were blank, but it didn't work:
# This doesn't work
if (is.na(surveydata$email)) {
surveydata$email_count = 0
}

Even though the code ran without error, none of the entries without emails had email_count set to 0.
I used the following code to create new data tables that list the emails and phone numbers that occur more than 10 times:
dup_emails <- data.frame(table(surveydata$email))
dup_phones <- data.frame(table(surveydata$phone))
dup_emails <- dup_emails[dup_emails$Freq > 10,]
dup_phones <- dup_phones[dup_phones$Freq > 10,]

I would like to create a For loop to check each row in surveydata where, if the email address or phone number match one of the email addresses or phone numbers in dup_emails or dup_phones, and the email_count or phone_count is over 10, then set a new variable "remove" to 1.  After that, I could then filter out any data where "remove" = 1.
I wrote the following code, but it's not working.  All of the values for "remove" remain 0:
# This doesn't work
surveydata$remove <- 0
for (i in length(unique(dup_emails$Var1))) {
  if(surveydata$email == dup_emails[i,1] && thdsweeps$email_count > 10) {
    surveydata$remove <- 1
  }
}

Any help or suggestions would be greatly appreciated!

A: Try this:
surveydata <- surveydata %>%
 group_by(phone) %>%
 mutate(phone_count = row_number()) %>%
 ungroup() %>%
 group_by(email) %>%
 mutate(email_count = row_number()) %>%
 ungroup() %>%
 #keep the records that have missing values for emails and phone numbers
 filter(is.na(email)&is.na(phone))

A: I figured out a solution.
I created a new TRUE/FALSE variable for whether or not the email or phone variables were NAs.
surveydata$email_remove <- is.na(surveydata$email)
surveydata$phone_remove <- is.na(surveydata$phone)

And then filtered out all rows where the email or phone counts were above 10 and the "remove" variables were FALSE.
surveydata_clean <- surveydata[!(surveydata$email_count > 10 & surveydata$email_remove == FALSE),]
surveydata_clean <- surveydata_clean[!(surveydata_clean$phone_count > 10 & surveydata_clean$phone_remove == FALSE),]


text:
Q: MS Access VBA Function Result in Form Text Box Control I've written a custom VBA function and would like the output to print out into a text box. The function is simple but I keep getting #Name in the text box.
What is the proper way to set the Control Source to a custom VBA function in an Access Form Text Box?

A: This is a vague question ...
Control Source : =MyFunction()

You should, of course, check that the function works. The immediate window is useful for such testing. You can also use an event to get the result and set the value of the textbox.


text:
Q: i am not able to delete the one row of react-final-form-array and it reset is not working properly go through this code and add customers and delete it. it gives an error.
https://codesandbox.io/s/array-fields-7x1n3

A: Define like this
<span
    onClick={() => deleteIt(index)}>
     ❌
 </span>

function code
const deleteIt=index=>{
    console.log(index)
  }

A: I managed to make it work by making your remove span tag like this:
<span type="button"
      onClick={() => fields.remove(index)}
      style={{ cursor: "pointer" }}>
❌
</span>

Basically I made the span a button. I think the problem lies in the definition of the validator of final-form-arrays, maybe it's something about the difference between span and button onClick event but I'm not sure..


text:
Q: Graph: Coloring. We consider the following graph $G$ (see picture below). I have to find
a) A matching of maximum size,
b) $\alpha(G)$
c) $\chi(G)$
d) $\chi'(G)$ which is a coloring of the edges.
My answers
a) I found a perfect matching, and thus a maximum matching so it's fine.
b) I don't understand what are the independents sets.
c) It's obvious that it's not one or two colorable. I found a $4-$coloration, but I'm not able to prove that it's not $3-$colorable. Any help would be welcome.
d) I know that $\Delta (G)\leq \chi'(G)\leq \Delta (G)+1$. I found a $6-$coloration of the edges but I'm not able to prove that it's not $5-$colorable. Any help would be welcome.

A: For the inability to $3$-color the graph, we observe the outside triangle must receive $3$ distinct colors.  This implies the following colors:

but then e.g. vertex $9$ cannot be colored without introducing a new color.
An independent set is a set of vertices, no two of which are adjacent.  E.g. $\{1,7,9\}$ is an independent set, because no two of $1$, $7$, or $9$ are adjacent.  We can argue that this is the largest by observing that an independent set cannot have two vertices from the same triangle, so any independent set of size $4$ must have one vertex from each of these triangles:

If it has vertex $10$, then it must have vertex $2$ (otherwise we get a clash), which means it must also have vertex $6$ (otherwise we get a clash), but then we get a clash no matter which vertex in the triangle $\{3,7,8\}$ we add in.
For the edge coloring, we take the one-factor colored orange below:

and rotate it, which assigns the first three colors.  What's left is two $6$-cycles (dotted), which is $2$-edge-colorable.


text:
Q: Spring boot authentication using proprietary cookies as well as HTTP authentication I have a web application which uses a proprietary cookie format. I also have a Spring Boot service which needs to interoperate with this existing application.
The application will send an HTTP request setting a EncryptedLoginToken cookie value. Inside the Spring Boot application it would be easy to write something like
boolean userHasPermission (String permission)
{
    LoginToken token = LoginToken.decrypt(cookies['EncryptedLoginToken']);

    return token.isValid () && token.hasPermission (permission);
}

The Spring Boot application has controllers like
@PostMapping(value="example/request/path")
@PreAuthorize("hasAuthority('example_permission')")
public ResponseEntity<?> exampleRequest ()
{
   // this will only be called if userHasPermission('example_permission') returns true
}

The Spring Boot application currently implements HTTP authentication, and both that method and this method must be supported.
How can I insert userHasPermission into Spring boot for a) authenticating users and b) checking hasAuthority?

A: You can create a new component that implements PermissionEvaluator.
@Component
public class DocumentsPermissionEvaluator
 implements PermissionEvaluator {

 @Override
 public boolean hasPermission(Authentication authentication,
   Object target,
   Object permission) {
     ...
 }
 @Override
 public boolean hasPermission(Authentication authentication,
   Serializable targetId,
   String targetType,
   Object permission) {
     ...
  }
}

If you do not have appropriate info in the authentication object, you can create a custom filter and custom Authentication where you can store info from cookies, if you need it.
 @PreAuthorize("hasPermission(#param, 'someType', 'SOME_PERMISSION')")
 public Result doSomething(String param) {
   return ...;
 }


text:
Q: Pythagoras theorem holds with equality for linear families The Pythagoras theorem for information projections is given by:
$$D(p||q) \geq D(p||p^*) + D(p^*||q)\;\; \forall p,$$ where $p^* = argmin_{r \in {\cal S}} D(r||q)$, or the projection of the distribution $q$ on the set
${\cal S}$. Also, $D(p||q) = \sum_y p(y) \log(\frac{p(y)}{q(y)})$ is the K-L divergence between two distributions $p$ and $q$.
My question is about the proof of the following fact:
$$D(p||q) = D(p||p^*) + D(p^*||q)\;\; \forall p \in {\cal L},$$
ie, the Pythagoras theorem holds with equality for all $p$ in ${\cal L}$,
where the set ${\cal L}$ is a linear family, and $p^*$ is the projection
of $q$ on ${\cal L}$.
In my course notes, they prove the above starting by using the fact that
some distribution $s$ is in ${\cal L}$ for any $\lambda \in \mathbb{R}$,
where,
$$ s = \lambda p + (1- \lambda) p^*,$$ since both $p$ and $p^*$ are in ${\cal L}$ and this is a property of linear families. Then, they prove it by contradiction using a small $\lambda < 0$ but I don't quite understand how they
proceed. Could you please help me out?
Thank you very much for your time!

A: There are a couple of key points:

*

*Support of $p^*$ = Support of $\mathcal{L}$. (This is true for all convex $\mathcal{S}$ in your notation.)

*$s_\lambda := \lambda p + (1-\lambda) p^* \in \mathcal{L}$ whenever $s_\lambda$ is a valid probability distribution.

Now, due to $1.$, there exists $t\in(0,1)$ s.t. if $\lambda \in (-t,t),$ $s_\lambda$ is a distribution (think why). We'll use this fact below. Let
$$f(\lambda) := D(s_\lambda\|q) - D(s_\lambda\|p^*) - D(p^*\|q).$$ Note that $f(\lambda) \ge 0$ whenever $s_\lambda$ is a distribution, and $f(0) = 0$. Since $s_\lambda$ is a distribution for $\lambda \in (-t,t),$ we have $f \ge 0$ on $(-t,t)$. Thus, $0$ is a local minima of $f$, and since $f$ is differentiable, you must have $$\left.\frac{\partial}{\partial \lambda} f(\lambda)\right|_{\lambda = 0} = \sum_{x\in \mathcal{X}} (p_x - p^*_x) \log \frac{p^*_x}{q_x} = 0,$$
where $\mathcal{X}$ is the support of $p^*$. Manipulating the above identity, we get, \begin{align*}
&\sum_{x\in \mathcal{X}} (p_x - p^*_x) \log \frac{p^*_x}{q_x} = 0 \\ \Leftrightarrow &\sum_{\mathcal{X}} p_x \log \frac{p_xp^*_x}{p_xq_x} = \sum_{\mathcal{X}} p^*_x \log \frac{p^*_x}{q_x} \\
\Leftrightarrow &\sum_{\mathcal{X}} p_x \log \frac{p_x}{q_x} - \sum_{\mathcal{X}} p_x \log \frac{p_x}{p^*_x} = D(p^*\|q)
\end{align*}
and we're done. Note that the main deal here was point $1,$ and the rest is just playing with definitions. While it isn't a terriby hard thing to prove, I'm too lazy to write a proof right now, but you can likely find it here.


text:
Q: Dvorak Setting on Mac OS X 10.5.8 for Right Hand or Left Hand only I use Macbook Pro 13", Mac OS X 10.5.8, and I mostly only use the keyboard on my mac. There are only two Dvorak Settings. I only use standard Dvorak so far. How can I enable Dvorak for right hand or left hand only?
Here is my dvorak setting screenshot on my mac:

A: Short answer: Snow Leopard. Here's my screenshot of keyboard layouts in OS X 10.6.2. Otherwise, I found a link that I haven't tried for adding left- and right-handed Dvorak layouts to OS X.


text:
Q: Как вывести массив объектов на страницу списком в JS? Помогите, пожалуйста правильно вывести массив объектов на страницу. В forEach зацикливает, вне не видны li
const flowers = [
  {
    author: "Белі Свім",
    name: "Троянда",
    price: 60
  },
  {
   author: "Джеймс Лоррі",
   name: "Тюльпан"
  }
]

let div = document.createElement('div');
div.id = 'root';

function flowerList(arr) {
    let ul = document.createElement('ul');
    books.forEach(elems => {
        let li = document.createElement('li');
        let list =
            (li.textContent = `author: ${elems.author}; name: ${elems.name}; price: ${elems.price}`);
        //console.log(li);
        ul.append(li);
        console.log(ul);
    });
    return;
}

flowerList(flowers);

document.getElementById('root').append(ul);

A: В вашем коде есть несколько ошибок. Вот исправленный код:

const flowers = [
  {
    author: "Белі Свім",
    name: "Троянда",
    price: 60
  },
  {
   author: "Джеймс Лоррі",
   name: "Тюльпан"
  }
]

let div = document.createElement('div');
div.id = 'root';
document.body.append(div); // добавляем div на страницу

function flowersList(arr) {
  let ul = document.createElement('ul');
  arr.forEach(elems => {
    let li = document.createElement('li');
    li.textContent = `author: ${elems.author}; name: ${elems.name}; price: ${elems.price}`;
    ul.append(li);
  });
  return ul; // возвращаем список
}

let flowersUl = flowersList(flowers); // получаем список цветов
document.getElementById('root').append(flowersUl); // добавляем список на страницу в div с id=root

В этом коде мы сначала создаем элемент div, добавляем его на страницу, потом определяем функцию flowersList, которая принимает массив объектов и возвращает список (ul) со списком цветов. В функции flowersList мы используем метод forEach, чтобы пройти по каждому объекту массива и создать li элемент для каждого цветка. Затем мы добавляем каждый li элемент в ul, а возвращаем ul. В главной функции мы вызываем flowersList, чтобы получить ul, и добавляем его на страницу в div с id=root.


text:
Q: IF 25% match or more, sum up values Is there a way to use a formula to get excel to look at values and determine if they have atleast a 25% match then to add their values. Kind of like a vlookup and IF function combined but I am not sure how to do the 25% part. The reason I ask this is because I have a data set with Company names that are the same company but they are all typed in differently so excel recognizes them as separate companies. For example:
Company:               Value
XYZ Incorperated       25
XYZ Company            40
XYZ                    12
ABC INC.               39
ABC inc.               10
ABC COMPANY            15

I need it to realize that all the companies with "XYZ" are the same and to add all their values. Same goes for "ABC". Again, I am not entirely sure it is possible but I haven't been able to find a way to get excel to sum it up for me.
Side note I could do it manually but the problem is that the data set is always changing so I need a formula that can recognize the similarities in each cell.

A: Try using Sumproduct.  I am assuming that all of your Column A will start with the company name.  (I.e. there won't be 'Company XYZ', only 'XYZ [...]'.  If this isn't always going to be the case, let me know.
Does this work? I assumed Company is Col. A, Value is Col. B - going to row 7.
=SUMPRODUCT(--(LEFT($A$2:$A$7,LEN(E2))=E2),--($B$2:$B$7>=25),$B$2:$B$7)
So, if a cell has "XYZ" as company, and the "Value" for that row is 25 or greater, it'll add together.  The XYZ cell equates to 65, and you can see the ABC correctly calculates 39.

edit: Here's a screenshot, using named ranges to maybe make it easier to see what goes where in the formula:

A: Yes try SUMPRODUCT it is great. Very simply, it look through column B which is the company names to match the left three characters in the name to what ever you type in cell E3 and sums the values in the value column.
=SUMPRODUCT(--(LEFT(B4:B9,3)=E3)*1,C4:C9)


text:
Q: Codeigniter : Fatal error: Call to a member function num_rows() on a non-object I have problem in link of my script by Codeigniter. I have this URL :-
localhost/index.php/admin/orders/
Its get me all order of product, But when i add any character in the end of link like this :
localhost/index.php/admin/orders/ggg
The user see some error message.
Fatal error: Call to a member function num_rows() on a non-object in

How can save my link, And hidden this message.
My Controller :-
function orders()
{
    $data['orders'] = $this->admin_model->getOrderList();
    $data['total']  = $this->admin_model->getOrderCount();
    $this->load->view('admin/orders',$data);
}

My Model:-
 function getOrderList()
{
    $page = $this->uri->segment(3);
    if($page=='')
        $page=1;

    $start = ($page-1)*RECORDS_PER_PAGE;
    $end = RECORDS_PER_PAGE;

    $this->db->select("*");
    $this->db->limit($end,$start);

    $this->db->order_by('order_id','DESC');
    $result = $this->db->get('wg_orders');
    if($result->num_rows()>0)
    return $result->result();
    else
    return 'empty';
}

A: You can use count() function as well.
In Controller
    function orders()
    {
        $data['orders'] = $this->admin_model->getOrderList();
        $data['total']  = $this->admin_model->getOrderCount();
        $this->load->view('admin/orders',$data);
    }

In Model
    function getOrderList()
    {
        $page = $this->uri->segment(3);
        if($page=='')
            $page=1;

        $start = ($page-1)*RECORDS_PER_PAGE;
        $end = RECORDS_PER_PAGE;

        $query = $this->db->query("SELECT * FROM table_name WHERE (your_argument) LIMIT $end, $start ORDER BY order_id DESC ");
        $result = $query->result_array();
        $count = count($result);

        if($count>0)
        {
            return $result;
        }
        else
        {
            return 'empty';
        }
    }


text:
Q: Compare text to template to detect anomalies (reverse template) I'm looking for an algorithm or even an algorithm space that deals with the problem of validating that short text (email) matches known templates.  Coding will probably be python or perl, but that's flexible.
Here's the problem:
Servers with access to production data need to be able to send out email that will reach the Internet:
Dear John Smith,

We received your last payment for $123.45 on 2/4/13. We'd like you to be aware of the following charges:
      $12.34 Spuznitz, LLC on 4/1
      $43.21 1-800-FLOWERS on 4/2
As always, you can view these transactions in our portal.
Thank you for your business!

Obviously some of the email contents will vary - the salutation ("John Smith"), "$123.45 on 2/4/13", and the lines with transactions printed out.  Other parts ("We received  your last payment") are very static.  I want to be able to match the static portions of the text and quantify that the dynamic portions are within certain reasonable limits (I might know that the most transaction lines to be printed is 5, for example).
Because I am concerned about data exfiltration, I want to make sure email that doesn't match this template never goes out - I want to examine email and quarantine anything that doesn't look like what I expect.  So I need to automate this template matching and block any email messages that are far enough away from matching.
So the question is, where do I look for a filtering mechanism?  Bayesian filtering tries to verify a sufficient similarity between a specific message and a non-specific corpus, which is kind of the opposite problem.  Things like Perl's Template module are a tight match - but for output, not for input or comparison.  Simple 'diff' type comparisons won't handle the limited dynamic info very well.
How do I test to see if these outgoing email messages "quack like a duck"?

A: You could use grammars for a tight matching. It is possible to organize regexps in grammars for easier abstraction: http://www.effectiveperlprogramming.com/blog/1479
Or you could use a dedicated grammar engine Marpa.
If you want a more statistic approach, consider n-grams. First, tokenize text and replace variable chunks by meaningful placeholders, like CURRENCY and DATE. Then, build the n-grams. Now you can use Jaccard index to compare two texts.
Here is a Pure-Perl implementation which works on trigrams:
#!/usr/bin/env perl
use strict;
use utf8;
use warnings;

my $ngram1 = ngram(3, tokenize(<<'TEXT1'));
Dear John Smith,

We received your last payment for $123.45 on 2/4/13. We'd like you to be aware of the following charges:
      $12.34 Spuznitz, LLC on 4/1
      $43.21 1-800-FLOWERS on 4/2
As always, you can view these transactions in our portal.
Thank you for your business!
TEXT1

my $ngram2 = ngram(3, tokenize(<<'TEXT2'));
Dear Sally Bates,

We received your last payment for $456.78 on 6/9/12. We'd like you to be aware of the following charges:
      $123,43 Gnomovision on 10/1
As always, you can view these transactions in our portal.
Thank you for your business!
TEXT2

my %intersection =
    map { exists $ngram1->[2]{$_} ? ($_ => 1) : () }
    keys %{$ngram2->[2]};
my %union =
    map { $_ => 1 }
    keys %{$ngram1->[2]}, keys %{$ngram2->[2]};

printf "Jaccard similarity coefficient: %0.3f\n", keys(%intersection) / keys(%union);

sub tokenize {
    my @words = split m{\s+}x, lc shift;

    for (@words) {
        s{\d{1,2}/\d{1,2}(?:/\d{2,4})?}{ DATE }gx;
        s{\d+(?:\,\d{3})*\.\d{1,2}}{ FLOAT }gx;
        s{\d+}{ INTEGER }gx;
        s{\$\s(?:FLOAT|INTEGER)\s}{ CURRENCY }gx;
        s{^\W+|\W+$}{}gx;
    }

    return @words;
}

sub ngram {
    my ($size, @words) = @_;
    --$size;

    my $ngram = [];
    for (my $j = 0; $j <= $#words; $j++) {
        my $k = $j + $size <= $#words ? $j + $size : $#words;
        for (my $l = $j; $l <= $k; $l++) {
            my @buf;
            for my $w (@words[$j..$l]) {
                push @buf, $w;
            }
            ++$ngram->[$#buf]{join(' ', @buf)};
        }
    }

    return $ngram;
}

You can use one text as a template and match it against your emails.
Check String::Trigram for an efficient implementation. Google Ngram Viewer is a nice resource to illustrate the n-gram matching.

A: If you want to match a pre-existing template with e.g. control flow elements like {% for x in y %} against a supposed output from it, you're going to have to parse the template language - which seems like a lot of work.
On the other hand, if you're prepared to write a second template for validation purposes - something like:
Dear {{customer}},

We received your last payment for {{currency}} on {{full-date}}\. We'd like you to be aware of the following charges:
(      {{currency}} {{supplier}} on {{short-date}}
){,5}As always, you can view these transactions in our portal\.

... which is just a simple extension of regex syntax, it's pretty straightforward to hack something together that will validate against that:
import re

FIELDS = {
    "customer": r"[\w\s\.-]{,50}",
    "supplier": r"[\w\s\.,-]{,30}",
    "currency": r"[$€£]\d+\.\d{2}",
    "short-date": r"\d{,2}/\d{,2}",
    "full-date": r"\d{,2}/\d{,2}/\d{2}",
}

def validate(example, template_file):
    with open(template_file) as f:
        template = f.read()
    for tag, pattern in FIELDS.items():
        template = template.replace("{{%s}}" % tag, pattern)
    valid = re.compile(template + "$")
    return (re.match(valid, example) is not None)

The example above isn't the greatest Python code of all time by any means, but it's enough to get the general idea across.

A: I would go for the "longest common subsequence". A standard implementation can be found here:
http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_subsequence
If you need a better algorithm and/or lots of additional ideas for inexact matching of strings, THE standard reference is this book:
http://www.amazon.com/Algorithms-Strings-Trees-Sequences-Computational/dp/0521585198
Don't be fooled by the title. Compuatational biology is mostly about matching of large database of long strings (also known as DNA sequences).


text:
Q: WPF Listview Scrollbar Visibility Trigger I'm trying to set up a trigger that removes the padding on the listview when the scrollbar is hidden.
I put the trigger on the listview style but I'm getting inconsistent results. For example the background property in the trigger is always active no matter what the scrollbar visibility is.
I've taken a look at the MSDN for the ScrollViewer.ComputedVerticalScrollBarVisibility Property  but am not having much luck figuring out what's wrong.
<ListView Grid.Row="1" Grid.Column="1" BorderBrush="{x:Null}" BorderThickness="0" ItemsSource="{Binding Tasks}" Margin="5"
          ScrollViewer.CanContentScroll="False" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListViewItem}">
                        <ContentPresenter />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.ItemTemplate>
        <DataTemplate>
            <!-- SNIP -->
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.Style>
        <Style>
            <Setter Property="ListView.Padding" Value="0,0,5,0"/>
            <Setter Property="ListView.Background" Value="{x:Null}" />
            <Style.Triggers>
                <Trigger Property="ScrollViewer.ComputedVerticalScrollBarVisibility" Value="Hidden">
                    <Setter Property="ListView.Padding" Value="0"/>
                    <Setter Property="ListView.Background" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListView.Style>
</ListView>

A: I write an ListView style example which worked for me. I tried it.
<Style TargetType="ListView">
      <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
      <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
      <Setter Property="Template">
           <Setter.Value>
                  <ControlTemplate TargetType="ListView">
                          <ScrollViewer>
                                 <ScrollViewer.Style>
                                    <Style TargetType="ScrollViewer">
                                       <Style.Triggers>
                                             <Trigger Property="ComputedVerticalScrollBarVisibility" Value="Visible">
                                                <Setter Property="Padding" Value="100"/>
                                              </Trigger>
                                              <Trigger Property="ComputedVerticalScrollBarVisibility" Value="Collapsed">
                                                  <Setter Property="Padding" Value="10"/>
                                              </Trigger>
                                       </Style.Triggers>
                                     </Style>
                                 </ScrollViewer.Style>
                             <ItemsPresenter />
                        </ScrollViewer>
                 </ControlTemplate>
            </Setter.Value>
        </Setter>
 </Style>


text:
Q: Why is my kernel choosing disk swap over 24G of inactive RAM? Output below is meminfo from a Proxmox hypervisor. I noticed today that swap usage was 90%. I logged into the box and checked and and it seems there is actually 24G of inactive RAM. A couple minutes later, I noticed swap usage was at 99%.

Why does the kernel appear to be favoring disk swap when there is so much inactive RAM available (EDIT: added vmstat -s below)?
# cat /proc/meminfo
MemTotal:       131911836 kB
MemFree:        28128112 kB
MemAvailable:   51794976 kB
Buffers:          397876 kB
Cached:         23298352 kB
SwapCached:       509796 kB
Active:         73136224 kB
Inactive:       24833836 kB
Active(anon):   72432368 kB
Inactive(anon):  2030612 kB
Active(file):     703856 kB
Inactive(file): 22803224 kB
Unevictable:       20256 kB
Mlocked:           20260 kB
SwapTotal:       8388604 kB
SwapFree:          76592 kB
Dirty:               216 kB
Writeback:             0 kB
AnonPages:      73881564 kB
Mapped:           196212 kB
Shmem:            182376 kB
Slab:            3837772 kB
SReclaimable:    1413588 kB
SUnreclaim:      2424184 kB
KernelStack:       10608 kB
PageTables:       281164 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:    74344520 kB
Committed_AS:   265844288 kB
VmallocTotal:   34359738367 kB
VmallocUsed:           0 kB
VmallocChunk:          0 kB
HardwareCorrupted:     0 kB
AnonHugePages:   2787328 kB
ShmemHugePages:        0 kB
ShmemPmdMapped:        0 kB
CmaTotal:              0 kB
CmaFree:               0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:     3584964 kB
DirectMap2M:    118982656 kB
DirectMap1G:    13631488 kB

vmstat -s
    131911840 K total memory
     85913712 K used memory
     80380944 K active memory
     24732132 K inactive memory
     20989356 K free memory
       405840 K buffer memory
     24602928 K swap cache
      8388604 K total swap
      8311256 K used swap
        77348 K free swap
     62711183 non-nice user cpu ticks
       711584 nice user cpu ticks
     19418784 system cpu ticks
   2202190185 idle cpu ticks
     12801599 IO-wait cpu ticks
            0 IRQ cpu ticks
       583222 softirq cpu ticks
            0 stolen cpu ticks
  11537252613 pages paged in
   3575771252 pages paged out
      1581238 pages swapped in
      3670384 pages swapped out
   3388189898 interrupts
   3739302263 CPU context switches
   1535799398 boot time
      3674458 forks


text:
Q: Perl Parsing CSV Efficient with Embedded Commas and Adding To Database How do you apply regular expressions to an array. While reading in my csv file I applied this...
        s/, /- /g;
        s/1,000/1000/g;

But after I put the data in my multidimensional array I don't know how to insert the commas back to my fields.

A: Firstly, there are a few CSV modules you can use to achieve this easily, however in some cases I know people do not have access to, or cannot install packages for reasons. Therefore, this should help if that is the case.
If I am getting you correctly, you are trying to write fields from CSV, which has embedded commas.If this is the case, these imbedded comma fields should have parenthesis or quotes around them in order to ensure they are not seen as the CSV's comma delimited fields. We can then just grab all of the data in your CSV. In this case we will have a csv that uses parenthesis, quotes and both to display data that is using embedded commas:
These show the CSV commas:
"Potatoes 1,000", (Tomatoes, 200), "(GemSquash, 1,029.95)"
                ^                ^

These are embedded commas:
"Potatoes 1,000", (Tomatoes, 200), "(GemSquash, 1,029.95)"
           ^               ^                  ^  ^

So the below will search and replace the data using the parenthesis and the double quotes to determine which are csv commas and which are embedded.
use strict;
use warnings;

my $string = '(Potatoes 1,000), "Tomatoes, 200", "(GemSquash, 1,029.95)"';
my $query = qr/(?: "\( ( [^()""]* ) \)" |  \( ( [^()]* ) \) |  " ( [^"]* ) " |  ( [^,]* ) ) , \s* /x;
my @results = grep defined, "$string," =~ /$query/g;
print "$_\n" for @results;

RESULTS
Potatoes 1,000
Tomatoes, 200
GemSquash, 1,029.95

A: For parsing CSV, use a CPAN module like Text::CSV. You can the use the regex on the values returned.


text:
Q: How to avoid string could not be parsed as xml error? My code is parsing xml using SimpleXMLElement class as shown below
  $xml = new SimpleXMLElement($response, LIBXML_ERR_ERROR, false, 'http://awis.amazonaws.com/doc/2005-07-11');

The xml data is provided by one of the AWS services.
Very frequently I encounter "String Could not be parsed as XML" error which causes the script to terminate. How do you get the script to ignore this error and keep running?
As I have said earlier, the xml data is provided by API and I don't have any control over the contents of the xml data. Is there a way to validate the data before I instantiate the class?

A:
I don't have any control over the contents of the xml data

Yes, you do. You have the whole response in a variable as a string, you can process it any way you fancy.
Start with logging responses that trigger the error. Then get one from the logs and run the new SimpleXmlElement part in a separate php file on the input. If it fails, you know that the data is at fault. Remove half of the data and run the parser again. If it passes, restore the deleted part and remove another. If it fails, go on narrowing down the data until you reach to the root of evil.
It often happens on poorly written xml providers that they put html entities in xml files without declaring them, or they don't escape apostrophes when they have to, etc.
If you discover this is the case, you can run a str_replace to fix the xml before parsing.
This is sad reality which goes against all the neatly written w3c standards, but sometimes you have to go a dirty path to make it work. Cheers!

A: Don't refer to it as XML data. Refer to it as non-XML data. That helps to establish the right mindset. When you talk to the supplier of this data, don't let them be under any illusion that they are delivering XML. Your life would be much easier if they did deliver XML, and you need to make sure they know this.
If it isn't XML, and you still want to parse it (rather than simply returning it to sender as unfit for purpose), then you need to know what it actually is. There's no way any program can parse data whose syntax is completely unpredictable. You need to find out in what ways it differs from XML, then you're going to have to find some strategy for repairing it where it's broken, which you can only do if you develop some kind of understanding of the nature of its brokenness. For example if the problem is lack of quotes around attribute values, then your strategy will be quite different from handling unmatched element tags.


text:
Q: Swing: Dynamically change visibility of components When I set the visibility of components (mainly JPanels that have other child components) to false or back to true later, do I have to call .revalidate() and .repaint() on the parent container explicitly or do the LayoutManagers handle this automatically?
When I tried this with a component in BorderLayout-North position for example, everything looked fine without calling revalidate. Just not sure if it will work on all platforms and with all LayoutManagers.

A: when u set the visibility of components like JPanels. JVM automatically call revalidate() and repaint() method when u set the visibility to true. u does not need to call the all these method. and it will work for all layout

A: The following code may solve your problem
      p2_wrkrreg=new JPanel();
      p2_wrkrreg.setBounds(201,0,830,720);
     // p2_wrkrreg.setLayout(null);
      //p2_wrkrreg.setBackground(Color.white);
      p2_wrkrreg.setVisible(false);

In this code,
The JPanel declared and make it invisible, it will be visible on a button click
@Override
public void actionPerformed(ActionEvent e) {

if(e.getSource()==btn_wrkrreg)
    {
        p2_wrkrreg.setVisible(true);
    }

here btn_wrkrreg is a JButton


text:
Q: Changing label position of data point in plot I have plotted some datapoints with plot function together with a Duncan's multiple range test. When i change the limits of the y-axis the grouping label of the first datapoint exceeds the plot and can no longer be seen.
How can i reduce the spacing between the datapoint and label?
My code:
data(FILIPPA)
model<-aov(TA~DATO + GE,data=FILIPPA)
out <- duncan.test(model,"DATO",
               main="Syre i Filippa")
plot(out,variation="IQR", ylim=c(7,9.5), )
duncan.test(model,"DATO",alpha=0.05,console=TRUE)

A: I couldn't find the FILIPPA dataset (apples and titratable acidity?).
But maybe the graphical parameter xpd is what you're looking for?
It doesn't look like plot.group() allows for adjusting the position of the labels.

library(agricolae)
data(mtcars)

model <- aov(mpg ~ wt + cyl, data=mtcars)
out <- duncan.test(model,"cyl", main="Fuel efficiency")

par(xpd=TRUE, mar=c(2, 2, 3, 1))
plot(out, variation="IQR", ylim=c(13, 30))
duncan.test(model, "cyl", alpha=0.05, console=TRUE)


text:
Q: kafka.api.OffsetRequest - unable to retrieve results Am working through the task of determining ConsumerLag and need to retrieve the current Producer Offset as follows:
PartitionOffsetRequestInfo partitionOffsetRequestInfo =
    new PartitionOffsetRequestInfo(OffsetRequest.LatestTime(), 100);

List<TopicAndPartition> partitions = new ArrayList<>();
for(int i = 0; i < partitionMetadataList.size(); i++) {
    TopicAndPartition topicAndPartition = new TopicAndPartition(topic, i);
    partitions.add(topicAndPartition);

    tuple2List.add(new Tuple2<>(topicAndPartition, partitionOffsetRequestInfo));
}

Tuple2<TopicAndPartition, PartitionOffsetRequestInfo>[] tuple2Array =
    tuple2List.parallelStream().toArray(Tuple2[]::new);

WrappedArray<Tuple2<TopicAndPartition, PartitionOffsetRequestInfo>> wrappedArray =
    Predef.wrapRefArray(tuple2Array);

scala.collection.immutable.Map<TopicAndPartition, PartitionOffsetRequestInfo> offsetRequestInfoMap =
    (scala.collection.immutable.Map<TopicAndPartition, PartitionOffsetRequestInfo>)
    scala.Predef$.MODULE$.Map().apply(wrappedArray);

OffsetRequest offsetRequest = new OffsetRequest(offsetRequestInfoMap, (short)0,
    0, OffsetRequest.DefaultClientId(), Request.OrdinaryConsumerId());

Looking at the OffsetResponse am presented with an array of UnknownTopicOrPartitionException offsets. If I pass in (short)1 for the versionId (as I have for calls to OffsetFetchResponse) I get a NetworkReceive.readFromReadableChannel exception when I try to retrieve the results.
Questions:
a. Is there a better way to get current producer offset?
b. Why doesn't the OffsetRequest call work with VersionId = 1?

Edit:
Note that Im able to use this channel to retrieve ConsumerOffset so I know it works.
I can retrieve the values using the cmdline:

kafka-consumer-groups  --bootstrap-server hostname:9092 --describe --new-consumer --group test_consumer

Edit:
Attempted to reuse sample scala (rewritten as Java) code:
KafkaConsumer<String, String> kafkaConsumer = getConsumer();
List<org.apache.kafka.common.TopicPartition>topicAndPartitions = new ArrayList<>();

org.apache.kafka.common.TopicPartition topicAndPartition = new org.apache.kafka.common.TopicPartition("my_topic", 0);
topicAndPartitions.add(topicAndPartition);

kafkaConsumer.assign(topicAndPartitions);

kafkaConsumer.seekToEnd(topicAndPartitions);
long lPos = kafkaConsumer.position(topicAndPartition);

Got the same exception (NetworkReceive.readFromReadableChannel) when it got to the .position() call.

A: Based on the source code, current version for OffsetRequest is 0 not 1. Besides the source code does not return Version-1 response containing timestamp information as doc says. So it might be a doc bug.

A: If you've come to this point here's a working solution:
private void getOffsets(String topic, String group) {
    KafkaConsumer<String, String> kafkaConsumer = getConsumer(topic, group);
    List<PartitionInfo> partitionInfos = kafkaConsumer.partitionsFor(topic);

    List<org.apache.kafka.common.TopicPartition>topicAndPartitions = new ArrayList<>();

    for(int i = 0; i < partitionInfos.size(); i++) {
        org.apache.kafka.common.TopicPartition topicAndPartition = new org.apache.kafka.common.TopicPartition(topic, i);
        topicAndPartitions.add(topicAndPartition);
    }

    List<Long>startList = new ArrayList<>();
    List<Long>endList = new ArrayList<>();

    kafkaConsumer.assign(topicAndPartitions);

    for(int i = 0; i < partitionInfos.size(); i++) {
        OffsetAndMetadata offsetAndMetadata = kafkaConsumer.committed(topicAndPartitions.get(i));
        if(offsetAndMetadata != null) {
            startList.add(offsetAndMetadata.offset());
        }
    }

    // did we find any active partitions?
    if(startList.size() == 0) {
        LOGGER.info("topic:group not found: {}:{}", topic, group);
        return;
    }

    kafkaConsumer.seekToEnd(topicAndPartitions);

    for(int i = 0; i < partitionInfos.size(); i++) {
        endList.add(i, kafkaConsumer.position(topicAndPartitions.get(i)));
    }

    LOGGER.debug("startlist.size: {}  endlist.size: {}  partitions: {}", startList.size(), endList.size(), partitionInfos.size());

    long sumLag = 0;
    for(int i = 0; i < partitionInfos.size(); i++) {
        long lStart = startList.get(i);
        long lEnd = endList.get(i);

        sumLag += (lEnd - lStart);

/*
 *  At this point Im sending the info to data dog.
 *  The 'sum' value is nice to have.
 */
        LOGGER.debug("partition: {}  start: {}   end: {}  lag: {}", i, lStart, lEnd, (lEnd - lStart));
    }

    kafkaConsumer.poll(100);

    topicAndPartitions.clear();
    kafkaConsumer.assign(topicAndPartitions)

}


text:
Q: How to spawn object on mouse position? When I click right click I want to create new sphere. And I don't know why this don't work. It creates a sphere, but definitely not on mouse position!
Vector2 mousePos;
public Transform mousePointer;
float mouseX, mouseY;
Vector3 spawnPoint;

void Start () {

}

void Update () {
    if(Input.GetMouseButtonDown(1)){
        mousePos = Input.mousePosition;
        mouseX = Input.mousePosition.x;
        mouseY = Input.mousePosition.y;
        spawnPoint = new Vector3(mouseX, mouseY, 0);
        Instantiate(mousePointer, spawnPoint, Quaternion.identity);
    }
}

A: Try spawning the object relative to the camera.
For example, use spawnPoint = cameraPosition + new Vector3(mouseX, mouseY, 0); or something similar. Check out the related post: Create a cube relative to camera mouse position.
The object is being spawned in global coordinates.


text:
Q: Google Map's Polygon with hole went wrong when zoom level is bigger than 19 I'm using Android Google Map v2 and MapFragment to display a map. I cover the whole map with a  large polygon with a small hole. It works fine when the zoom level is smaller 19, but after the zoom level goes up to 20, the hole is gone. Is it a Google Map's bug?
LatLng = (0, 0)

LatLng = (25.00, 121.52)

LatLng = (25.00, 121.52) MapType = SATELLITE

Here is my code, please help. Thanks!
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    map.moveCamera(CameraUpdateFactory.zoomTo(18));
    drawPolygonWithHole(map);
}

private void drawPolygonWithHole(GoogleMap map) {
    ArrayList<LatLng> hole = new ArrayList<LatLng>();

    hole.add(new LatLng(-0.0002, -0.0002));
    hole.add(new LatLng(-0.0002, 0.0002));
    hole.add(new LatLng(0.0002, 0.0002));
    hole.add(new LatLng(0.0002, -0.0002));

    map.addPolygon(new PolygonOptions()
        .add(new LatLng(85,90), new LatLng(85,0.1),
             new LatLng(85,-90), new LatLng(85,-179.9),
             new LatLng(0,-179.9), new LatLng(-85,-179.9),
             new LatLng(-85,-90), new LatLng(-85,0.1),
             new LatLng(-85,90), new LatLng(-85,179.9),
             new LatLng(0,179.9), new LatLng(85,179.9))
        .addHole(hole)
        .strokeWidth(0)
        .fillColor(Color.BLACK));
}

A: It sure looks like an issue within Google Maps Android API v2. There are bugs reported on gmaps-api-issues with a possibly same root cause, but there is nothing like this reported AFAIK, so I suggest to go there and post it.


text:
Q: Get an empty list of XPATH expression in python I have watched a video at this link https://www.youtube.com/watch?v=EELySnTPeyw and this is the code ( I have changed the xpath as it seems the website has been changed)
import selenium.webdriver as webdriver

def get_results(search_term):
    url = 'https://www.startpage.com'
    browser = webdriver.Chrome(executable_path="D:\\webdrivers\\chromedriver.exe")
    browser.get(url)
    search_box = browser.find_element_by_id('q')
    search_box.send_keys(search_term)
    try:
        links = browser.find_elements_by_xpath("//a[contains(@class, 'w-gl__result-title')]")
    except:
        links = browser.find_lemets_by_xpath("//h3//a")
    print(links)
    for link in links:
        href = link.get_attribute('href')
        print(href)
        results.append(href)
    browser.close()

get_results('cat')

The code works well as for the part of opening the browser and navigating to the search box and sending keys but as for the links return an empty list although I have manually searched for the xpath in the developer tools and it returns 10 results.

A: You need to add keys.enter to your search. You weren't on the next page.
search_box.send_keys(search_term+Keys.ENTER)

Import
from selenium.webdriver.common.keys import Keys

Outputs
https://en.wikipedia.org/wiki/Cat
https://www.cat.com/en_US.html
https://www.cat.com/
https://www.youtube.com/watch?v=cbP2N1BQdYc
https://icatcare.org/advice/thinking-of-getting-a-cat/
https://www.caterpillar.com/en/brands/cat.html
https://www.petfinder.com/cats/
https://www.catfootwear.com/US/en/home
https://www.aspca.org/pet-care/cat-care/general-cat-care
https://www.britannica.com/animal/cat


text:
Q: Apache: unable to check htaccess file, ensure it is readable - Read/Execture set right My web server is giving Permission 403 Forbidden errors and checking the error_log
[Sun Aug 24 13:06:49 2014] [crit] [client 162.205.68.223] (13)Permission denied: /home/www/www.networkcmo.com/www/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable
I have done the following:

*

*Changed /home (recursive) to chmod 755

*Made sure the .htaccess file exists and is not corrupt (I can 'cat' it from the shell)

*Changed the owner of .htaccess to be 'apache'

None of these fix the issue.
I have looked at these other SO posts:
 here and here and here and they basically all talk about read+execute or ownership which I have tried.
The permissions right now for /home/www are
drwxr-xr-x+ 6 ftp webusers 4096 Aug  2 14:46 www

The permissions for /home/www/www.networkcmo.com/www are
drwxr-xr-x. 4 ftp    webusers 4096 Aug 20 06:50 www

The file permissions for .htaccess is
-rwxr-xr-x.  1 apache apache   1594 Aug 20 05:59 .htaccess

The one thing that stands out is the '+' sign at the end of the home/www which indicates some special folder permission things in that folder/files but I dont know if that will effect this.
The apache user is a part of the webusers group

A: I've done chmod 755 -R /home/username/public_html and it worked for me.


text:
Q: CoordinatorLayout and RecyclerView issue I am using CoordinatorLayout and NestedScrollView for creating an activity looks like this:

My layout structure is like this:
<android.support.design.widget.CoordinatorLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.MovieDetailActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingToolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/imgToolbarImage"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/backdrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.NestedScrollView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <android.support.v7.widget.CardView
                    ... >
                    <ImageView
                       ... />
                </android.support.v7.widget.CardView>

                <TextView
                        ... />

                <TextView
                        ... />

                <ImageView
                        ... />

                <TextView
                    ... />

                <com.aminiam.moviekade.custom_view.ExpandableTextView
                    ... />

                <android.support.v4.view.ViewPager
                   ... />

                <com.aminiam.moviekade.custom_view.DotIndicator
                    ... />

                <View
                    ... />

                <LinearLayout
                     ... >

                    <TextView
                        ... />

                    <android.support.v7.widget.RecyclerView
                        ... />
                </LinearLayout>

                <android.support.v4.view.ViewPager
                    ... />

                <TextView
                    ... />
            </RelativeLayout>

        </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/activity_horizontal_margin"
        app:layout_anchor="@id/appBar"
        app:layout_anchorGravity="bottom|end"
        app:srcCompat="@drawable/ic_favorite_off" />
</android.support.design.widget.CoordinatorLayout>

When I add RecyclerView to the layout, NestedScrollView will goes under the AppBarLayout, like image below:

I tested some ways for fixing this issue like put NestedScrollView into a FrameLayout or add android:layout_gravity="fill_vertical" and android:fillViewport="true" attributes to NestedScrollView but these couldn't fix the issue.

A: Try adding android:descendantFocusability="blocksDescendants" into your RelativeLayout
<RelativeLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:descendantFocusability="blocksDescendants" >

</RelativeLayout>

Note: descendantFocusability Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus. Here we are blocking that.


text:
Q: Calculating sum of prime number below 2 million by using Sieve of Atkin I'm doing project Euler and I got this problem. I run the code in VS 2013 and the program crashes because of overflow.
This is my method:
void problem10()
{
    long long int iter = 2, sum = 0;

    //Sieve of Atkin
    bool isPrime[PRIME_LIMIT+1];

    for (long long int i = 5; i <= PRIME_LIMIT; i++)
    {
        isPrime[i] = false;
    }

    long long int lim = ceil(sqrt(PRIME_LIMIT));

    for (long long int x = 1; x <= lim; x++)
    {
        for (long long int y = 1; y <= lim; y++)
        {
            long long int n = 4 * x*x + y*y;
            if (n <= PRIME_LIMIT && (n % 12 == 1 || n % 12 == 5))
            {
                isPrime[n] = true;
            }

            n = 3 * x*x + y*y;
            if (n <= PRIME_LIMIT && (n % 12 == 7))
            {
                isPrime[n] = true;
            }

            n = 3 * x*x - y*y;
            if (x > y && n < PRIME_LIMIT && n % 12 == 11)
            {
                isPrime[n] = true;
            }
        }
    }

    // eliminate composites by seiving
    for (long long int n = 5; n <= lim; n++)
    {
        if (isPrime[n])
        {
            for (long long int k = n*n; k <= PRIME_LIMIT; k+= k*k)
            {
                isPrime[k] = false;
            }
        }
    }

    for (long long int n = 5; n <= PRIME_LIMIT; n++)
    {
        if (isPrime[n])
        {
            sum += n;
        }
    }
    sum = sum + 2 + 3;
    printf("%lld\n", sum);
    /* //A basic approach -- too slow
    while (iter < PRIME_LIMIT)
    {
        bool isDivisible = false;
        int prime = iter;
        for (int a = 2; a < iter; a++)
        {
            if (prime%a == 0)
            {
                isDivisible = true;
                break;
            }
        }

        if (isDivisible){}
        else
        {
            //printf("prime is: %d\n", prime);
            sum += prime;
        }
        iter++;
    }
    printf("Sum of prime is: %d\n", sum);
    */
}

This method includes 2 approaches to calculate the sum of all prime numbers in ranges PRIME_LIMIT. The second approach take too long to get the result, and probably take whole day. The first approach is using sieve of Atkin, the program crashes!
Is there any mistake in my code?? Please help!

A: So, let's talk about this problem:
Integer Sizes
Much like Java, Integers in C have a limit to the size that they can fit. Here, you chose to use a long long int. Luckily for this problem, the sum will fit in that data type. For other Project Euler problems, you will need to use a BigInt class.
Your Slow Approach
The slow approach is actually fine if you add one addition. We know, that the list of divisors that we need to search, is actually less than all of the numbers from 2 ... n. So we can change one of your loops to this:
int max = ciel(sqrt(iter));
for (int a = 2; a < max; a++)
    if (prime % a == 0)
        isDivisible = true;
        break;

If we do that, your code will finish relatively quickly.
Your Fast Approach
I haven't fully gone through this code, because it doesn't look like the sieve of eratosthenes that I remember, but at the very least, you are going to overflow the stack with your allocations.
#define PRIME_LIMIT 2000000
bool isPrime[PRIME_LIMIT+1];

Let's fix that:
#define PRIME_LIMIT 2000000
static bool isPrime[PRIME_LIMIT+1]

Or:
#define PRIME_LIMIT 2000000
bool *isPrime = calloc(PRIME_LIMIT + 1, sizeof(bool));

Recommendations
I'd really recommend to not start by trying to implement the Sieve of Atkin. If I was to implement this as a learning exercise, I'd do it in this order:

*

*The slow approach that you've done above. In python, similar code takes about 1 minute to solve the problem. I'd suspect C could do it in about 10 seconds (or faster).

*The sieve of eratosthenes is a much simpler sieve to implement. I'd recommend using that next.

*Then try to implement the sieve of atkin. An algorithm of that speed is completely unnecessary for a problem of this size though.


text:
Q: wxComboBox adding hover effect Here is my code in C++ when initialize a frame in wxwidgets:
wxPanel *panel = new wxPanel(this, wxID_ANY);

combo_list = new wxComboBox(panel,ID_COMBOBOX);
combo_list->Append("Guitar");
combo_list->Append("Violin");

Connect(ID_COMBOBOX, wxEVT_COMMAND_COMBOBOX_SELECTED,
        wxCommandEventHandler(ComboBox::OnSelect));

However, there is no default hover effect, which is background color changing when you move mouse on a specific selection.
And I find for an hour on google but still cannot find it. Can anybody told me how  to make the hover effect?
I just want to implement two drop down lists. The content in the first one has been determined before the running the program. In the order one the content will only be determined after I choose a directory.


text:
Q: What is the expected score of this game? Construct a non-increasing sequence of integers between 0 and 9 by doing the following:
1) Draw a random integer between 1 and 9.  Call this $X_1$.  Multiply this number by $10^{-1}$.
2) To the result of the previous step, add a random integer between 0 and $X_1$ inclusive. Call this $X_2$.  If you draw 0, the sequence terminates.  If your draw is not 0, then multiply $X_2$ by $10^{-2}$ and add this to the result of previous step.
3) Repeat until 0 is drawn, all the while multiplying draws by successively smaller powers of 10.
So, for example, I could draw 6 as my first number, 3 as my second number, 3 as my third number, 1 as my fourth number, and 0 as my fifth number.  The result would be 0.6332 (or $\sum_{i = 1} X_i10^{-i}$).
What is the expected value of this sequence?  Can it be computed analytically?  If so, how?
Here is some python code to simulate this:
import numpy as np

def sim():

    last_draw = 0
    while last_draw==0:
        last_draw = np.random.randint(low=0, high=10)

    digits = [last_draw]
    while last_draw!=0:
        last_draw = np.random.randint(low=0, high=last_draw+1)
        digits.append(last_draw)

    digits = np.array(digits)
    tens = 10.0**(-np.arange(1,len(digits)+1))

    return np.dot(digits, tens)

if __name__=='__main__':

    sims = [sim() for j in range(100000)]

    print(np.mean(sims))

A: Let's $\mu_k$ be the expected value after we draw $k$, and $\mu$ be the total expected value of the game. Then, since we draw between 1 and 9 in the beginning:
$$\mu=\frac{1}{90}\sum_{k=1}^9(k+\mu_k)$$
If we have $k$, where $k>0$, at the last draw, we can write the expected value of our next draws as:
$$\mu_k=\frac{1}{10(k+1)}\sum_{i=1}^k(i+\mu_i)\rightarrow\mu_k=\frac{k(k+1)}{2(10k+9)}+\frac{1}{10k+9}\sum_{i=1}^{k-1}\mu_i$$
Via inductive logic and some algebra, you'll see that this recursion has the solution $\mu_k=k/19$ (substitute it), yielding $\mu=10/19\approx 0.526..$.


text:
Q: Django Sending HTML Table to Python Hello Guys
I'm working with Django and I have a big doubt, i have 3 HTML tables and i need save this data in mysql, that table is filled by users and im not sure how can i sending the tables to python.
i tried using Ajax, but, really I'm not sure how to use it.
HTML CODE from one of my 3 tables:
custom.html

FIRST
Second

<button class="btn btn-primary" onclick="ajaxFunction()" id="IDButton">Touch me!</button>

The tbody rows are added with javascript
Ajax code:

When i click the button in the console i can see "works" but in python is not working
Python code:
crm/views.py
def custom(request, op_id):
     if request.method == "GET":
          IF request.is_ajax():
                 message ="Yes"
          else:
                 message="No"
     return render(request, "custom.html")

I don't know why function is_ajax does not works.
I only wanna find a way to do this,
i will be glad !!!!
Thank you!


text:
Q: How to apply custom formatting for a JSON stringify? I have the following code:

const sample = [
  {
    name: "apple",
    points: [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 7, y: 8 } ],
    age: 24
  },
  {
    name: "banana",
    points: [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 7, y: 8 } ],
    age: 45
  }
];

const qwer = JSON.stringify(sample, null, 2);

console.log(qwer);

If you run it, you'll notice it has nice formatting, except for the points array, which is extremely verbose.
I would like everything to be indented like normally (which is why I'm passing in 2 for the final parameter to stringify), but I would like the points array to only take a single line, like how it is declared in the code.
The reason for this is because currently each points array is stretched to like 18 lines, when there will only ever be 3 or 4 items. I would like them to stay on one line.
I tried to use a custom replacer, and while it somewhat worked, it forced the JSON array to be a string. But it's not a string. I want it to stay an array.
Is there any way to do this?

A: For the general solution, a mini parser would be the best approach, but a quick but ugly-looking approach would be to use a replacer to replace arrays with stringified strings with a unique value as a prefix which can be replaced afterwards.

const sample = [
  {
    name: "apple",
    age: 24,
    points: [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 7, y: 8 } ],
  },
  {
    name: "banana",
    age: 45,
    points: [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 7, y: 8 } ],
  }
];

const withNestedStringifiedArrays = JSON.stringify(
  sample,
  (key, value) => key && Array.isArray(value) ? '@@UNIQUE@@' + JSON.stringify(value) : value,
  2
);
const output = withNestedStringifiedArrays.replace(
  /"@@UNIQUE@@(.*?)"(,)?$/gm,
  (_, stringifiedArr, possibleComma = '') => stringifiedArr.replaceAll('\\', '') + possibleComma
);
console.log(output);


text:
Q: Android Google sign in api always call onResume() Today, I am try implement Google Sign in API: https://developers.google.com/identity/sign-in/web/sign-in
And implement interface
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener on MainActivity(AppCompatActivity). However, everything ok in the first time sign in. When I open the new Activity and back again, onConnected() always called. How to avoid onConnected() called when MainAcivity onResume ?

A: *

*After the first time you login OK -> google sign-in return token key for client which you can save to client (use SharedPreference).

You can ref this code:
YOu need edit your code to similar:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .requestIdToken("server_client_id") //to require server return Id token
                .requestServerAuthCode("server_client_id") //to require server return authCode
                .build();

GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
String tokenKey = acct.getServerAuthCode(); //get authenticated code to save in client

*Open activity/app again -> before do sign-in again you have to check token key is exiting (stored or not) -> if is exiting then you do not sign-in again and of cource connected in listener not occour

Cheer!

A: you must be having
google_api_client.connect()

in your onStart() method which will be connecting it again and again. You can fix it by creating a flag for SignInButton click and in onStart() method check for the flag before connecting the google_api_client.


text:
Q: "Illegal type synonym family application in instance" with functional dependency I have a multi-parameter typeclass with a functional dependency:
class Multi a b | a -> b

I also have a simple, non-injective type synonym family:
type family Fam a

I want to write an instance of Multi that uses Fam in the second parameter, like this:
instance Multi (Maybe a) (Fam a)

However, this instance is not accepted. GHC complains with the following error message:
error:
  • Illegal type synonym family application in instance: Fam a
  • In the instance declaration for 'Multi (Maybe a) (Fam a)'

Fortunately, there is a workaround. I can perform a usual trick for moving a type out of the instance head and into an equality constraint:
instance (b ~ Fam a) => Multi (Maybe a) b

This instance is accepted! However, I got to thinking, and I started to wonder why this transformation could not be applied to all instances of Multi. After all, doesn't the functional dependency imply that there can only be one b per a, anyway? In this situation, it seems like there is no reason that GHC should reject my first instance.
I found GHC Trac ticket #3485, which describes a similar situation, but that typeclass did not involve a functional dependency, so the ticket was (rightfully) closed as invalid. In my situation, however, I think the functional dependency avoids the problem described in the ticket. Is there anything I'm overlooking, or is this really an oversight/missing feature in GHC?


text:
Q: WPF and MVVM. Display and hide a label with a timeout in my MVVM application, I wish to create an auto-closing popup to notify some information to the users (for example "data changes saved successfully").
so, I placed a label into the form, bound to a VM property. Then, I wish to set my message and cancel it after a delay (1 second). But it seems not to work. the app just wait some time, and shows the final status (ie: when the user push "save" button, the app "waits" for one second, and then the label is empty).
any ideas to get it? thanks

A: Why can't you use normal popup in WPF
<Popup Margin="10,10,0,13" Name="Popup1" HorizontalAlignment="Left"  VerticalAlignment="Top" Width="194" Height="200" IsOpen="True">
    <StackPanel>
        <TextBlock Name="McTextBlock"
         Background="LightBlue" >
        This is popup text
       </TextBlock>
        <Button Content="This is button on a Pupup" />
    </StackPanel>

public void show()
{
  Popup1.IsOpen = true;
  Thread t = new Thread(hide);
  t.Start();
}

private void hide() {
  Thread.Sleep(5000);
  Popup1.IsOpen = false;
}

call show function when you want to show popup


text:
Q: IWebExplorer2 Navigate fails with Error reading characters of string IWebExplorer2::Navigate(..) (or Navigate2) is failing to navigate some urls. Like while navigating following url: *https://www.facebook.com/dialog/oauth/?api_key=<MyKey>&redirect_uri=<MyUri>&state=NONE* , I am getting the error **Error reading characters of string** in **DISPID_NAVIGATEERROR**.
......
wchar_t ws[MAX_PATH];
TCharToWide(url,ws,MAX_PATH);

VARIANT v; v.vt=VT_I4; v.lVal=0; //v.lVal=navNoHistory;
ibrowser->Navigate(ws,&v,NULL,NULL,NULL);
......

void TCharToWide(const wchar_t *src,wchar_t *dst,int dst_size_in_wchars){wcscpy(dst,src);}

Please could any one tell me what I am missing?
Thanks in advance.

A: Following Navigate2 method URL Type is Variant, and for Navigate method url type is BSTR; If you have ATL support you can use CComVariant with Navigate2, or CComBSTR with Navigate;
NavToURL( L"www.google.com", FALSE);

BOOL NavToURL(const wchar_t* url, BOOL isnewtab){
  CComVariant vEmpty;
  CComVariant vURL(url);
  CComVariant flag=isnewtab ? 0x0800 : vEmpty;
  ibrowser->Navigate2(&vURL, &flag, &vEmpty, &vEmpty, &vEmpty);
  return TRUE;
}


text:
Q: How can I set values for variables that are declared on one line? I have a list of variables that are being created on one line.
Dim strFirstname, strMiddleName, strLastName As String
Is it possible to set the values for all of them at once? I know this doesn't work, but this is what I'm trying to do :
Dim strFirstname, strMiddleName, strLastName As String = ""

A: I liked the examples, but I just needed to set the values so that the compiler would leave me alone. I have another function that sets all the values that I'm passing these strings into. I wanted to set them to pretty much nothing, just so it would leave me alone. I ended up using this:
Dim strFirstname, strMiddleName, strLastName As New String(String.Empty)

A: If you want different values, this should work:
Dim strFirstname As String = "First name", strMiddleName  As String = "middle name", strLastName As String = "last name"

A: If you truely want one line instantiating them all, create an object to hold this data instead, e.g.
...
person.Firstname
person.MiddleName
person.LastName
...

Then populate them in the constructor, e.g.
Dim person As New Person("first","middle","last")

Seems like a cleaner option if your objects are all related to a specific idea/entity.


text:
Q: Grass Gis r.viewshed how i can set max distance in meter or kilometer? I have a problem with the r.viewshed max distance
wiki: "The value entered is in the same units as the cell size of the raster. "
Work: I get one geo file and where I run a viewshed with radius x(measure)
I do not know which projection and therefore which size the cells have. Perhaps one cell is 1m, 1km or 1 mile.
Is there an option for me to setup the unit in meter or kilometer beforehand?


text:
Q: Como resolver o problema de medium trust em asp.net Estou desenvolvendo um site em Asp.Net MVC5.
Ao publicar o site na LocaWeb e tentar logar com meu usuário recebi a mensagem:
Attempt by security transparent method 'Microsoft.AspNet.Identity.ClaimsIdentityFactory`2+<CreateAsync>d__0<TUser,TKey>.MoveNext()' to access security critical method 'System.Security.Claims.ClaimsIdentity.AddClaim(System.Security.Claims.Claim)' failed.

Assembly 'Microsoft.AspNet.Identity.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is partially trusted, which causes the CLR to make it entirely security transparent regardless of any transparency annotations in the assembly itself.  In order to access security critical code, this assembly must be fully trusted.

Eu utilizo Identity e também alguns componentes da DevExpress.
Foi só então que entrei em contato com o suporte que me disse que o problema ocorre porque o servidor deles só roda em medium trust: http://wiki.locaweb.com.br/pt-br/Security_Level_de_servidores_Windows_em_ambiente_compartilhado
No site da microsoft diz que a solução é colocar dentro da tag <System.web> do meu web.config a tag <trust level="medium" originUrl="" />.
Ao fazer isso recebo o seguinte erro do servidor: This configuration section cannot be used at this path.  This happens when the site administrator has locked access to this section using <location allowOverride="false"> from an inherited configuration file.
Ou seja, a locaweb bloqueou essa alteração atrabés de um arquivo de configuração global (pelo menos foi o que eu entendi do erro).
Já tentei colcoar a tag <location allowOverride="false"> mas tambem não resolveu.
O suporte da locaweb só sabe dizer que o erro é de programação, mas não sei como resolver.
Alguém ai sabe como resolver isso?

A: Já tive um problema parecido. Alguns Host não permitem mesmo.
Tente fazer um teste no Windows Azure: http://azure.microsoft.com/pt-br/
Meus últimos projetos tenho utilizado o Azure como host, agora eles tem servidores no Brasil também.


text:
Q: Can I use a RAM disk to speed up my IDE? Duplicate:

RAMDrive for compiling - is there such a thing?

I have an idea how to speed up my IDE.
I want to create a RAM disk and move my solution onto this virtual disk.
I think that this can speed up the IDE because RAM is much faster than a HDD.
Has anyone done this before?
PS: I think, when I have some documents in my program(real world) which are used frequently(for example some document templates) it could be good idea to move these documents onto a RAM disk as well to speed up I/O. Am I wrong?
If power is a problem, a UPS could solve it.

A: Honestly, if you have Vista/Windows Server 2008 x64 and you jam your workstation with 4 to 8 GB of RAM, for most tasks, everything will be in cache or stored by SuperFetch, which will be a lot easier to manage and just about as high performance as a RAM disk.  The RAM disk won't do a thing for you if you're starving your other system RAM to make it work.
BTW, I tried your suggestion a couple of years ago.  While it technically worked, copying the necessary data to the RAM disk on every boot took too long and was a pain.

A: I have a 128GB Samsung flash based hard drive and it is FAST. My whole system, VM and IDE included, load in less than one minute.

A: Given sufficient RAM, this problem's been solved for a long time.  If you have lots of RAM, stuff from the HD gets cached in it anyhow, and the HD is only the bottleneck the first time you're loading something at boot.  As far as the initial boot time, I'd suggest using sleep/suspend mode and simply not rebooting your computer frequently.

A: Personally I'd just buy a SSD disk, you could lose your whole soln at any time if your ram loses power.
Right now I have 4gb of ram and a 150gb 10k rpm velociraptor hard drive for my boot disk, running win xp pro 64bit and everything(VS 2008, sql management studio, and my testing VM's) is very fast.

A: Under Linux /dev/shm is a ramdisk so you might have some quick success using that as your compile destination (easier than rsyncing your source etc, also has the benefit, if you have one, of reducing any wear on an SSD in your machine).

A: I do remember reading about doing this with netbeans a while ago.
This article has quite a good guide on doing it in linux.
NetBeans on speed
Currently can't find an article on how to do it in windows, however I know it's possible.

A: This might not buy you much.  If you use up memory with your RAM disk, you just going to deprive the OS RAM for virtual memory, and that is going to be causing more frequent page faults and thus potential more writing to the hard disk.

You could loose your whole soln at any time if your ram looses power.

Element is absolutely right. Your machine could lock up at at any time for whatever reason.
If you do decide to use RAM disk at least have a batch file on your desktop that copies everything to disk, and run it frequently.

A: I posted an answer to a similar question previously. As a summary: yes it's possible, I used to do it with my browser (there is a link on how to get it running under linux).
As other people have mentioned if you have a tonne of RAM that stuff will be cached for you anyway, but imo having a ram drive is a bit more explicit than just letting the OS try to deal with it.
If you know that you want 200mb of code in memory all the time then you know you can put in a ram drive and acheive that.
I do wonder however if the OS will cache it twice (once on the ram drive, once itself) if it doesn't know it's on a RAM drive...


text:
Q: /dev/ipmi0 does not exist R710 SLES 11 SP2 I have been searching without success to find how to get ipmitool to work. It is dependent on /dev/ipmi0 existing, however in my case it doesn't. Here's some information that I think would be helpful:
# service ipmi status
ipmi_msghandler module loaded.
ipmi_si module loaded.
ipmi_devintf module loaded.
/dev/ipmi0 does not exist.

# ./srvadmin-services.sh status
dell_rbu (module) is running
ipmi driver is stopped
dsm_sa_datamgrd (pid 30636) is running
dsm_sa_eventmgrd (pid 30757) is running
dsm_sa_snmpd (pid 30816) is running
dsm_om_shrsvcd (pid 30894) is running
dsm_om_connsvcd (pid 30919 30918) is running

ipmi message handler version 39.2
May 29 13:36:13 # kernel: [11369545.480521] IPMI System Interface driver.
May 29 13:36:13 # kernel: [11369545.480523] ipmi_si: probing via hardcoded address
May 29 13:36:13 # kernel: [11369545.480524] ipmi_si: Adding hardcoded-specified kcs state machine
May 29 13:36:13 # kernel: [11369545.480526] ipmi_si: Trying hardcoded-specified kcs state machine at i/o address 0xca2, slave address 0x0, irq 0
May 29 13:36:13 # kernel: [11369545.480532] ipmi_si: Interface detection failed

   # service ipmi restart
Stopping all ipmi     drivers:                                                                        done
Starting ipmi drivers:                                                                            done

# zypper se ipmi
Loading repository data...
Reading installed packages...

S | Name             | Summary                           | Type
--+------------------+-----------------------------------+-----------
i | OpenIPMI         | OpenIPMI                          | package
  | OpenIPMI-devel   | OpenIPMI  - Development libraries | package
i | ipmitool         | Utility for IPMI Control          | package
  | ipmitool         | Utility for IPMI Control          | srcpackage
  | libipmi0         | IPMI library for iDRAC update     | package
i | slessp1-ipmitool | Recommended update for ipmitool   | patch
i | slessp2-ipmitool | Recommended update for ipmitool   | patch

# rpm -qa | grep srvadmin
    srvadmin-sysfsutils-7.2.0-4.1.595.sles11
    srvadmin-omacs-7.2.0-4.459.9.sles11
    srvadmin-deng-snmp-7.2.0-4.183.49.sles11
    srvadmin-tomcat-7.2.0-4.459.11.sles11
    srvadmin-webserver-7.2.0-4.9.3.sles11
    srvadmin-racadm4-7.2.0-4.25.868.sles11
    srvadmin-itunnelprovider-7.2.0-4.468.10.sles11
    srvadmin-racadm5-7.2.0-4.3.567.sles11
    srvadmin-racdrsc-7.2.0-4.481.10.sles11
    srvadmin-rac4-7.2.0-4.25.868.sles11
    srvadmin-server-cli-7.2.0-4.9.3.sles11
    srvadmin-idrac-vmcli-7.2.0-4.40.6.sles11
    srvadmin-hapi-7.2.0-4.237.42.sles11
    srvadmin-omilcore-7.2.0-4.822.1.sles11
    srvadmin-deng-7.2.0-4.183.49.sles11
    srvadmin-idracadm-7.2.0-4.481.10.sles11
    srvadmin-rac-components-7.2.0-4.481.10.sles11
    srvadmin-omcommon-7.2.0-4.459.9.sles11
    srvadmin-isvc-snmp-7.2.0-4.325.23.sles11
    srvadmin-idrac-7.2.0-4.481.10.sles11
    srvadmin-base-7.2.0-4.9.3.sles11
    srvadmin-server-snmp-7.2.0-4.9.3.sles11
    srvadmin-storageservices-7.2.0-4.9.3.sles11
    srvadmin-storelib-sysfs-7.2.0-4.1.594.sles11
    srvadmin-realssd-7.2.0-4.531.5.sles11
    srvadmin-argtable2-7.2.0-4.2.598.sles11
    srvadmin-idrac-ivmcli-7.2.0-4.2.7.sles11
    srvadmin-oslog-7.2.0-4.822.1.sles11
    srvadmin-standardAgent-7.2.0-4.9.3.sles11
    srvadmin-rac4-populator-7.2.0-4.25.868.sles11
    srvadmin-ominst-7.2.0-4.459.11.sles11
    srvadmin-smweb-7.2.0-4.528.5.sles11
    srvadmin-omacore-7.2.0-4.459.11.sles11
    srvadmin-storage-cli-7.2.0-4.528.5.sles11
    srvadmin-storageservices-cli-7.2.0-4.9.3.sles11
    srvadmin-xmlsup-7.2.0-4.458.9.sles11
    srvadmin-storelib-7.2.0-4.525.5.sles11
    srvadmin-racsvc-7.2.0-4.25.868.sles11
    srvadmin-idrac-snmp-7.2.0-4.481.10.sles11
    srvadmin-rac5-7.2.0-4.3.567.sles11
    srvadmin-storageservices-snmp-7.2.0-4.9.3.sles11
    srvadmin-smcommon-7.2.0-4.528.5.sles11
    srvadmin-jre-7.2.0-4.460.9.sles11
    srvadmin-isvc-7.2.0-4.325.23.sles11
    srvadmin-storage-7.2.0-4.528.5.sles11
    srvadmin-storage-snmp-7.2.0-4.528.5.sles11
    srvadmin-all-7.2.0-4.9.3.sles11

# lsmod | grep ipmi
ipmi_devintf           17509  0
ipmi_si                53294  0
ipmi_msghandler        49895  2 ipmi_devintf,ipmi_si

Why doesn't /dev/ipmi0 exist and how can I make it exist?

A: Maybe there's a hardware problem with your BMC. Does it show up in dmidecode's output? You should see something matching "ipmi" or "kcs" or "BMC".