text:
Q: How can I accomplish multiple threads to join multiple times into a process? (pthread_mutex_lock) I want to write a program, what counts to 100. I want to accomplish this with 10 threads, using pthread lock. When the program steps into a thread it generates a number between 0-2, this value will be added to it's index of array and also to the global variable sum. When the sum value reaches 100, every thread should print it's own value of array (the amount of the entire array should be equal with the sum variable).
My problem is the following: Always the first thread locks the mutex variable, but I want to distribute the tasks between all threads (arr[1] = 100, every other = 0, but I want for example arr[1] = 14, arr[2] = 8, etc. up to 100). Where am I wrong?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>

pthread_mutex_t mutex;
int arr[10];
int sum = 0;

void *add (void* input) {

    int *id = (int*) input, x, s;
    int ind = *id;

    while (sum < 100) {
        while (1) {
            if (pthread_mutex_trylock(&mutex) != EBUSY)
                break;
        }

        if (sum < 100) {
            x = rand() % 3;
            arr[ind] = arr[ind] + x;
            sum += x;
        }

        pthread_mutex_unlock(&mutex);
        sleep(0.1);
    }

    printf("The %d. thread got %d points!\n", ind, arr[ind]);
    return NULL;
}

int main (void) {

    int i;
    pthread_t threads[10];
    pthread_mutex_init(&mutex, NULL);
    srand(time(NULL));

    for (i = 0; i < 10; i++) {
        if (pthread_create(&threads[i], NULL, add, &i)){
            perror("pthread_create");
            exit(1);
        }
    }

    for (i = 0; i < 10; i++) {
        if (pthread_join (threads[i], NULL)){
            perror("pthread_join");
        }
    }
    pthread_mutex_destroy(&mutex);
    return 0;
}

The output:
The 1. thread got 100 points!
The 2. thread got 0 points!
The 3. thread got 0 points!
The 4. thread got 0 points!
The 5. thread got 0 points!
The 6. thread got 0 points!
The 7. thread got 0 points!
The 8. thread got 0 points!
The 9. thread got 0 points!
The 0. thread got 0 points!

A: You have several problems in your code, with varying degrees of relevance to the specific issue you asked about.  Before we go further, one output I get from running your code as written may be illustrative:

The 2. thread got 100 points!
The 8. thread got 0 points!
The 9. thread got 0 points!
The 5. thread got 0 points!
The 5. thread got 0 points!
The 6. thread got 0 points!
The 7. thread got 0 points!
The 2. thread got 100 points!
The 4. thread got 0 points!
The 1. thread got 0 points!

Note that some threads got the same counter index.  This can happen because you have a data race between the main thread and each child thread: the main thread passes a pointer to its local variable i, and then proceeds to modify the value of that variable.  Meanwhile the child thread reads the value of the variable via the pointer.  These actions are not synchronized, so the behavior is undefined.
This particular problem has several solutions.  The simplest is probably to cast i to void * and pass the result (by value).  This is in fact pretty common where you just want to pass an integer:
        if (pthread_create(&threads[i], NULL, add, (void *)i)) {
            // ...

Of course, the thread function needs to convert it back:
void *add (void* input) {
    int /*no need for 'id' */ x, s;
    int ind = (int) input;
    // ...

Next, observe that you have another data race among all your child threads where you read the value of sum in the condition of the while loop.  That one does not seem to be biting you at the moment, but it could do at any time.  Since the threads, as a group, both read and modify sum, you must ensure that all such accesses are synchronized -- for example, by performing them only while holding the mutex locked.
Skipping a bit (we'll come back), you have a problem with your sleep() call.  That function's parameter is of type int, so your actual argument, the double 0.1, is converted to int, yielding 0.  The compiler might optimize that out altogether, and if it doesn't, then it might effectively be a no-op.  Even more importantly, however.  sleep() is simply the wrong tool for this job, or for pretty much any job related to inter-thread synchronization and timing.
Recognizing now that there is no sleeping, you should see that your outer while loop is quite tight, in that a thread that has just unlocked the mutex will immediately try to lock it again.  It is quite common for such a re-locking attempt to succeed on the first try, because default mutex behavior makes no promises about thread scheduling fairness.
Additionally, you gain no particular benefit from the peculiar busy loop around pthread_mutex_trylock().  Just use pthread_mutex_lock() if otherwise all you're going to do when the mutex is busy is re-try.  This will save you CPU time and does not have appreciably different semantics.
Overall, though, you have a strategy problem.  Mutexes do not generally provide any guarantees around fair scheduling.  Usually for a tight multithread interaction such as this one, you need to perform some kind of scheduling management manually, and that typically benefits greatly from adding a condition variable to the mix.
It looks like you don't want to force the threads to take turns, but perhaps it would be sufficient to ensure that the thread that just ran does not immediately get selected again.  In that case, you could add a shared variable that records the index of the thread that just ran, and use that to prevent it from being selected again as the next thread.  Schematically, the thread function might then look something like this

*

*loop indefinitely:

*

*lock the mutex

*loop indefinitely:

*

*compare the last thread index to my index

*if it is different, break from the (inner) loop

*else wait on the condition variable

*set my index as the last thread index

*(still holding the mutex locked) broadcast to or signal the CV

*if sum is less than 100

*

*update sum

*unlock the mutex

*otherwise (sum is >= 100)

*

*unlock the mutex

*break from the (outer) loop

A: I found two problems.
When I tried this on Windows with MSys2 my output was
The 1. thread got 101 points!
The 1. thread got 101 points!
The 2. thread got 0 points!
The 3. thread got 0 points!
The 5. thread got 0 points!
The 6. thread got 0 points!
The 6. thread got 0 points!
The 8. thread got 0 points!
The 9. thread got 0 points!
The 0. thread got 0 points!

You pass the address of your loop counter i to the threads. This variable is not constant, that's why the threads may read a value that has already changed. To fix thisI created an array int ids[10] and passed every thread its own ID array element.
Function sleep uses an unsigned int argument, so you effectively call sleep(0). With sleep(1) the program runs slower but works as expected. You can use usleep if you want to sleep for fractions of a second.
Modified program:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>

pthread_mutex_t mutex;
int arr[10];
int sum = 0;

void *add (void* input){

    int *id = (int*) input, x, s;
    int ind = *id;
    while (sum < 100){
        while (1){
            if (pthread_mutex_trylock(&mutex) != EBUSY)
                break;
        }
        if (sum < 100){
            x = rand() % 3;
            arr[ind] = arr[ind] + x;
            sum += x;
        }
        pthread_mutex_unlock(&mutex);
        usleep(100000);
    }
    printf("The %d. thread got %d points!\n", ind, arr[ind]);
    return NULL;
}

int main (void){

    int i;
    pthread_t threads[10];
    int ids[10];
    pthread_mutex_init(&mutex, NULL);
    srand(time(NULL));
    for (i = 0; i < 10; i++){
        ids[i] = i;
        if (pthread_create(&threads[i], NULL, add, &ids[i])){
            perror("pthread_create");
            exit(1);
        }
    }
    for (i = 0; i < 10; i++){
        if (pthread_join (threads[i], NULL)){
            perror("pthread_join");
        }
    }
    pthread_mutex_destroy(&mutex);
    return 0;
}


text:
Q: WPF control for tokenizing I didn't found any wpf library that contains control for tokenizing (tagging) text input. Perhaps I can't find the library, because I incorrectly call this component. How it is called or where there is such a library?

A: The DevExpress WPF library contains several data editing controls that provide the option to work in token mode, which is your required functionality. Here is the overview page for this: https://documentation.devexpress.com/WPF/17861/Controls-and-Libraries/Data-Editors/Editor-Types/Token-Editors
Note: This is a paid product. They offer a free trial if you would like to try out their ecosystem.
Another option is to create your own. This can be done fairly quickly (with minimum functionality, but probably enough fro your needs) using a RichTextBox and custom InlineUIContainers. There is a blog post here that fleshes out the idea and provides a sample implementation: https://blog.pixelingene.com/2010/10/tokenizing-control-convert-text-to-tokens

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mapping JavaObject to Javabeans in declarative way Edit1
I am not sure if the title is best for the problem so if any have some more orinted title please suggest
i am trying my hands on camel where i have to fetch some csv file from a file system and needs to convert it to xml format and place it on some other system
i am using camel for this and here is my sample POC code
import org.apache.camel.CamelContext;

import org.apache.camel.Exchange;

import org.apache.camel.Message;

import org.apache.camel.Processor;

import org.apache.camel.builder.RouteBuilder;

import org.apache.camel.impl.DefaultCamelContext;
import com.poc.convertor.CSVConverterBean;

  public class TestPOC {

           public static void main(String args[]) throws Exception {
           CamelContext context = new DefaultCamelContext();
           context.addRoutes(new RouteBuilder() {

                  public void configure() {
                          from("file:data/csv?noop=true").unmarshal().csv().bean(new CSVConverterBean(),"processCSVInvoice").to("file:data/csvoutput?fileName=test.xml").marshal("jaxb");

                  }

              });
               context.start();
               Thread.sleep(1000);
               context.stop();
          }

}

In this approach camel csv unmarshaller will covert the csv file in to java list List<List<String>>
i have written a java converter CSVConverterBean which will iterate the list and set the values in the respective java objects being generated by jaxb 2.x , final object is being marshaled in to xml and file is being saved.
Everything is being working properly with only one issue , if in future there arises any request to change mapping we need to do the modification in CSVConverterBean and than this java file needs to be recompiled and need to be redistributed which we want to avoid.
my question is, Is there any way by which we can map the values from the java List being given by Camel to the respective java classes being generated by the JaxB so that the need to recompile java code can be avooided.

A: You can provide a "from-to" kind of configuration file to map the columns of your CSV data with your Bean properties, and code an algorithm to read that file and process the convertion.
You could do with a .properties file:
# mapping.properties
column0=propertyOne
column1=propertyTwo

For each column in your CSV, you get the value from the property file and find which property you should set the value on.
int columnIndex = 0;
for(String column : csvColumns) {
    String property = findProperty(columnIndex);
    reflectionUtil.setValue(object, property, column);
    columnIndex++;
}

This may give you some hint.
Whenever your data changes, you will only need to change the property file, not the class.

A: Use Bruno's idea, but read the property names from the header row in the csv file.

A: I have solved this problem using dom4j.camel gave me back csv as list> and firstly i read the headers and than made these headers and the XML tags and the values as there respected values on run time.


text:
Q: Logic of Java Operators && and || Hello dear Programmers,
I have a String String input = "30.09.1993";
Then i want to save all numbers in this string in an array(Only numbers!). The "." are at index 2 and 5 so i want to skip these parts of my string in my loop with an if-statement.
I fixed my problem and everything works fine but I'm confused with the logic of the && and || operators.
This is my working code:
String input = "30.09.1993";
int[] eachNumbers = new int[8];

int x = 0;
for(int i = 0; i <= 9; i++){
    if(i != 2 && i != 5){
       eachNumbers[x] = Integer.parseInt(input.substring(i, i+1));
       x++;
    }
}

And this is the code which doesnt work:
String input = "30.09.1993";
int[] eachNumbers = new int[8];

int x = 0;
for(int i = 0; i <= 9; i++){
    if(i != 2 || i != 5){
       eachNumbers[x] = Integer.parseInt(input.substring(i, i+1));
       x++;
    }
}

The only difference between these two code snippets are the operators in the if-clause.
I thought that the results for these operators are:
&& operator:
false + false = false
true  + false = false
false + true  = false
true  + true  = true

|| operator:
false + false = false
true  + false = true
false + true  = true
true  + true  = true

So in my opinion the second code snippet should work and the first should throw a NumberFormatException. But thats not the case.
I'm sure there are some better solutions for what im doing but my question is only about the logic in my if-statement. Can someone explain me the logic behind this? I'm totally confused and thankful for every helping answer.
Greetings
Lukas Warsitz

A: In the second snippet, the if-clause will always be true, because i will always be not 2 or not 5 (because it cannot be 2 and 5 at the same time)
For what you want to do your first snippet is fine, it does exactly what you want: If your are not at the third element and neither at the 6th element, you want to parse, else you are at one of the points in the date.

A: Key point is here : In && if first case is false, second case won't check.
true && false // Evaluates false because the second is false
false && true // Evaluates false because the first is false
true && true // Evaluates true because both are true
false && false // Evaluates false because the first is false

and
In || if first case is true , second case won't check.
true || false // Evaluates true because the first is true
false || true // Evaluates true because the second is true
true || true // Evaluates true because the first is true
false || false // Evaluates false because both are false

A: Although not necessarily your issue which LionC notes.
the 4 and and or logic operators follow the following logic:
& is as you describe && above.
false + false = false
true  + false = false
false + true  = false
true  + true  = true

| is as you describe || above
false + false = false
true  + false = true
false + true  = true
true  + true  = true

&& and || are shortcut operators that don't test the second value if it would make no difference to the result.
&&
false + untested = false
true  + false = false
false + untested = false
true  + true  = true

||
false + false = false
true  + untested = true
false + true  = true
true  + untested  = true

A: Your second snippet is not working because it should be
if(i != 2 && i != 5)

and your first snippet is not throwing error because of same reason that you have used && there.

A: Pick a number, any number. It is either not equal 2, or not equal 5.
Therefore the expression (i != 2 || i != 5) can be statically (by the compiler) transformed into just true and the whole if control structure eliminated.
The obvious result is a NumberFormatException if any of the characters is not a digit.

A: I'm not giving answer for your question but suggesting better code.
public class splitToArray {
    public static void main(String[] args) {
        String input = "30.09.1993";
        input = input.replace(".", " ");
        String array[] = input.split(" ");
        for(String value : array){
            System.out.println(value);
        }
    }
}

Output:
30
09
1993

Now use Integer.parseInt to get integer value. This will also work when you have String input = "30.9.1993"; [0 removed from 09]

A: i can only have one value at a time.
So any of the following conditions are valid:
if(i != 2 && i != 5) //means `i` is not any 2 AND i is not 5

or
if(i == 2 || i == 5) //means `i` is either 2 OR 5

Note: (i != 2 || i != 5) is always true because at any time

*

*If i = 2, LHS i is not equal to 2 is FALSE and RHS i is not equal to 5 is TRUE

*If i = 5, LHS i is not equal to 2 is TRUE and RHS i is not equal to 5 is FALSE

*For all other value of i: Both LHS and RHS are true.


text:
Q: Split multidimensional array with array_chunk based on another array I am trying to split a multi dimensional array based on another array of values
Something like array_chunk($multi_array, array(1,3,7)). Managed to find something related to this over here array_chunk_multi. Just that it doesn't work for multi dimensional array. Currently it splits them up correctly just that I get NULL to all values.
PHP
function array_chunk_array(array $values, array $sizes)
{
    $results = [];
    foreach ($sizes as $size) {
        $current = [];
        while (count($values) > 0 && count($current) < $size) {
            $current[] = array_unshift($values);
        }
        $results[] = $current;
    }
    return $results;
}

$input_sub_arr = range('1', '6');
$input_sub_array = array();
foreach ($input_sub_arr as $answer) {
  $input_sub_array[] = 'answer-'.$answer;
}
$input_sub_answers = array();
foreach ($input_sub_array as $input_sub_answer) {
  $input_sub_answers[$input_sub_answer] = array('attributes' => array('correct'));
}
//var_dump($input_sub_answers);
$new_answer = array_chunk_array($input_sub_answers, array(4,2));
var_dump($new_answer);

CURRENT ARRAY
array(6) {
  [0]=>
  array(3) {
    ["@attributes"]=>
    array(2) {

    }
  }
  [1]=>
  array(2) {
    ["@attributes"]=>
    array(2) {

    }
    ["answerText"]=>
    array(1) {

    }
  }
  [2]=>
  array(3) {
    ["@attributes"]=>
    array(2) {

    }
    ["answerText"]=>
    array(2) {

    }
  }
  [3]=>
  array(3) {
    ["@attributes"]=>
    array(2) {

    }
    ["answerText"]=>
    array(2) {

    }
  }
  [4]=>
  array(3) {
    ["@attributes"]=>
    array(2) {

    }
    ["answerText"]=>
    array(2) {

    }
  }
  [5]=>
  array(3) {
    ["@attributes"]=>
    array(2) {

    }
    ["answerText"]=>
    array(2) {

    }
  }
}

EXPECTED OUTPUT
array(4) {
  [0]=>
  array(3) {
    ["@attributes"]=>
    array(2) {

    }
  }
  [1]=>
  array(2) {
    ["@attributes"]=>
    array(2) {

    }
    ["answerText"]=>
    array(1) {

    }
  }
  [2]=>
  array(3) {
    ["@attributes"]=>
    array(2) {

    }
    ["answerText"]=>
    array(2) {

    }
  }
  [3]=>
  array(3) {
    ["@attributes"]=>
    array(2) {

    }
    ["answerText"]=>
    array(2) {

    }
  }
}
array(2) {
  [1]=>
  array(3) {
    ["@attributes"]=>
    array(2) {

    }
    ["answerText"]=>
    array(2) {
      ["@attributes"]=>
      array(1) {

      }
    }
  }
  [2]=>
  array(3) {
    ["@attributes"]=>
    array(2) {

    }
    ["answerText"]=>
    array(2) {

    }
  }
}

CURRENT OUTPUT
array(2) {
  [0]=>
  array(4) {
    [0]=>
    NULL
    [1]=>
    NULL
    [2]=>
    NULL
    [3]=>
    NULL
  }
  [1]=>
  array(2) {
    [0]=>
    NULL
    [1]=>
    NULL
  }
}

A: What really should be used here is array_splice:
$vl = [1,1,1,1,2,2,3,3,3];
$sz = [4, 2, 3];
function array_chunk_array(array $values, array $sizes)
{
    $result = [];

    foreach ($sizes as $s) {
        $result[] = array_splice($values, 0, $s);
    }

    return $result;
}

echo'<pre>',print_r(array_chunk_array($vl, $sz)),'</pre>';


text:
Q: Excel Pivot Table Manipulations I work for a Helpdesk and I am trying to create a pivot table that shows the resolution rate of our analysts. This is the pivot table I currently have shows each analysts name on the left and the data in the table is the number of tickets that we created. On the top of the pivot table, the only field I have is split into two columns, Dispatched and Resolved.
What I am trying to do is add another field that basically shows their resolution rate or Resolved/Grand Total. If someone could point me in the right direction it would be greatly appreciated.

A: If I understand you correctly, your pivot table has:

*

*Name as a row label

*The state of the ticket (Dispatched or Resolved) as a column label

*The Count of the ticket number as the Value

Then you can:

*

*Change the field settings of the Count of ticket number to Show values as % of row. That will change the totals to percentages for the data; or

*If you want to show both counts and percentages, then you'd need to add Count of the ticket number as a Value a second time; you can then set one as just the count and the second as a percentage. This looks a little messy but you can play around with the formatting (showing/hiding totals, etc.) to make it a bit nicer

*If you just want a %age at the end (Dispatched/Resolved or something like that) it may be simpler just to add a formula to the right of your pivot table and calculate it outside of the pivot table. You'll end up with something like =GETPIVOTDATA("Count of Ticket No",$F$2,"Name",F5,"State","Dispatched")/(GETPIVOTDATA("Count of Ticket No",$F$2,"Name",F5,"State","Dispatched")+GETPIVOTDATA("Count of Ticket No",$F$2,"Name",F5,"State","Resolved")), which is really just pivot table code for =Dispatched/(Resolved+Dispatched). When you add a cell in a pivot table into a formula, it gets entered as GETPIVOTDATA("Count of Ticket No",$F$2,"Name","bob","State","Dispatched"), which means 'Get the value of "Count of Ticket No" column from the pivot table at $F$2 where Name=Bob and State = Dispatched'. I often change these to replace the hard coded bob and Dispatched values with the cell references, so that I can drag the formulas and also so they update if the pivot table resizes. e.g. GETPIVOTDATA("Count of Ticket No",$F$2,"Name",F6,"State",G$3)

A: You could add an auto calculating field to the pivot which would do that in the actual pivot table. On iPhone at moment but wrote an example as answer to another question here:
How do I show the average by month in a pivot table?
This has the advantage of not getting overwritten or missing data when the pivot gets resized (eg when new staff are added etc.)


text:
Q: If/else Statement not evaluating issues I have something weird going on with my code. I have a Data Extension name "DEXT Seeds". I am checking the DataSourceName_ to see if this list is picked by a user. I have an if/else statement that says if DataSourceName_ contains Seed, then the variable Seedsource equals "columnSeed" from the local Data Extension. Otherwise lookup Columnsource that matches the subscriberkey from a shared Data Extension.
My issue is that the DEXT Seeds works if I pick a seeded list. But if I pick something outside of the seeded list, I get an error that says it is looking for "columnSeed". But I don't want it to pull in ColumnSeed, I want it to lookup Columnsource. Why is it still trying to evaluate columnSeed when it should ignore this code and evaluate the Lookup. Please see the code below.
SET @DEXT = _DataSourceName

SET @SubscriberKey = [Customer ID]

IF Indexof(@DEXT, "Seed") > 0 THEN

SET @Seedsource = [columnSeed]

ELSE

SET @Seedsource = Lookup('ENT.Shared_DE','Column1','SubscriberKey', @SubscriberKey)

ENDIF

A: I think your issue may be that the IndexOf() will pick up anything that has Seed in it. Including "Conciseedition" or similar.
I would define this a bit more defensively with something like:
SET @DEXT = AttributeValue("_DataSourceName")
SET @SubscriberKey = AttributeValue("Customer ID")
SET @Seed = AttributeValue("columnSeed")

IF NOT EMPTY(@Seed) AND @Seed != "" THEN

  SET @Seedsource = AttributeValue("columnSeed")

ELSE

  SET @Seedsource = Lookup('ENT.Shared_DE','Column1','SubscriberKey', @SubscriberKey)

ENDIF

I always utilize AttributeValue() for all personalization string references as it is better at handling null and Empty values - reducing the amount of unnecessary errors.
In this case, we are using the AttributeValue() function to check and see if that field exists. If the value comes up empty, then we know that it either does not exist in the sendable DE, or that the value inside of the column is empty.


text:
Q: Designing Data storage for a E-commerce website I am trying to understand how E-commerce sites handle huge amount of inventory and the transactions associated with it. With respect to this, i have some basic questions.
Consider a E-commerce website running on multiple servers
and the inventory associated with it is small and can fit inside a single server.
Where should this inventory be kept? In a centralized server or should it be replicated in each server where the web app is running?
Consider two users whose request being handled by different servers, contest for the same product.
If the inventory is replicated in each server, then the transactions can't be synchronized. Or is there any synchronization mechanism which works across multiple servers?
And if the inventory is kept in a centralized server and if all web apps have to query this centralized server, then the issue is it takes more time for the transaction.
How do websites resolve above problem?
Suppose if the inventory is huge, is a distributed database way to go?
With respect to distributed databases:

*

*Do distributed databases inherently have mechanisms to handle above issue(contesting for the same product)? And How did E-commerce sites handle this issue when there were no distributed databases?

*Can a relational database be distributed?

*Can a typical inventory be modeled as a non-relational database?
I understand that these are some basic questions, i am just starting to learn about E-commerce and building scalable web applications, so any resources or learning materials to get answers to the questions i mentioned above is appreciated.

A: I am working as a developer for a big e-commerce system. We are using one database (oracle) and 1..n nodes of an backend and frontend. Each node has own cache, we are using events to invalidate it within a cluster.

Consider two users whose request being handled by different servers, contest for the same product.

In solution as my company is using, regular transactions are enough to handle such scenario.

How do websites resolve above problem?

I think there is many approaches to handle this issue, which also depends of the technology you would like to use. You can go as we did with one database or you could go for microservices approach or somehow mix it. Each solution has is pluses and minuses.


text:
Q: Django not recognizing files deleted/added I have the following function that gives me the list of files(complete path) in a given list of directories:
from os import walk
from os.path import join

# Returns a list of all the files in the list of directories passed
def get_files(directories = get_template_directories()):
    files = []
    for directory in directories:
        for dir, dirnames, filenames in walk(directory):
            for filename in filenames:
                file_name = join(dir, filename)
                files.append(file_name)
    return files

I'am adding some files to the template directories in Django. But this function always return the same list of files even though some are added/deleted in the run time. These changes are reflected only when I do a server restart. Is that because of some caching that os.walk() performs or is it required that we need to restart the server after adding/removing some files ?

A: It is not django problem, your behaviour is result of python interpreter specific:

Default arguments may be provided as plain values or as the result of a function call, but this latter technique need a very big warning. Default values evaluated once at start application and never else.

I' m sure this code will solve your problem:
def get_files(directories = None):
    if not directories:
        directories = get_template_directories()
    files = []
    for directory in directories:
        for dir, dirnames, filenames in walk(directory):
            for filename in filenames:
                file_name = join(dir, filename)
                files.append(file_name)
    return files

You can find same questions on Stackoverflow Default Values for function parameters in Python


text:
Q: C++ : How to specialize a member function for a template Array-like class A to deal with A >? I'm writing a template <class T> array-like class A, and I want to specialize a few member functions to deal with arrays of arrays A<A<T>>.
Here is an working example that is close to what I want:
#include "stdio.h"

//primary template class
template <class T> class A {
public: void f() {printf("A<T>::f\n");}
};

//1st solution : specialization (?) of A for A<A<T>>
template <class T> class A< A<T> > {
public: void f() {printf("A<A<T>>::f\n");}
};

//2nd solution : specialization of A::f for A<A<int>>
template<> void A< A<int> >::f() {
    printf("A<A<int>>::f\n");
}

int main(void) {

    A<int> A_int;
    A< A<int> > A_A_int;
    A< A<double> > A_A_double;

    A_int.f();        // ok : prints A<T>::f
    A_A_int.f();      // ok : prints A<A<int>>::f
    A_A_double.f();   // ok : prints A<A<T>>::f

    return 0;
}

The problem with 1st solution is that I have to duplicate a lot of member functions from the primary template class
I tried to derive from the primary class but
template <class T> class A< A<T> > : public A< A<T> >

makes no sense
The problem with 2nd solution is that I have to duplicate the specialization for every possible types, and that defeats the purpose of template classes.
Since it is possible to define template<> void A< A<int> >::f(), it seems one should be able to "templatize" this specialization for any type. I tried :
template <class T> template<> void A< A<T> >::f()
template <template <class T> > void A< A<T> >::f()
template <template <> class T> void A< A<T> >::f()

and other absurd syntaxes...
So... Can I templatize the specialization template<> void A< A<int> >::f() not just for int but for any type T ?
Thanks in advance,
Best regards,

A: One possible way:
#include <cstdio>

// forward declaration
template<typename>
class A;

template<typename>
class A_Base {
    // general case
    public: void f() { printf("A<T>::f\n"); }
};

// partial specialization for any A
template<typename T>
class A_Base< A<T> > {
    // special stuff
    public: void f() { printf("A<A<T>>::f\n"); }
};

template<typename T>
class A : private A_Base<T> { // private inheritance, we're not modeling IS-A
public:
    using A_Base<T>::f;  // make f accesible

    // all the other stuff that doesn't need to change
};

int main()
{
    A<int> a1;
    A<A<int>> a2;
    a1.f();       // A<T>::f
    a2.f();       // A<A<T>>::f
}

This way you put only the functions that need to behave differently in the base class. You can of course make it vice-versa - you put common code in the base class and specialize a derived class where you also define f.


text:
Q: Local density of a deformed lattice to lowest order in displacement I am trying to understand the derivation from appendix A in the paper https://arxiv.org/abs/cond-mat/9501087. The idea is to calculate the local density of a deformed lattice of a particle as a function of displacement field $\vec{u}$. If the lattice were perfect, then the particle density would be
$$\rho\left(\vec{r}\right)=\sum_{i}\boldsymbol{\delta}\left(\vec{r}-\vec{R_{i}}^{0}\right),$$
where $\vec{R_{i}}^{0}$ the position vectors of the underlying lattice. Now assume that particle changes positions the new position are given by
$$\vec{R}_{i}=\vec{R}_{i}^{0}+\vec{u}_{i}\left(\vec{R_{i}}^{0}\right),$$ where $\vec{u}_{i}\left(\vec{R_{i}}^{0}\right)$ is the displacement of the atom which was sitting in the lattice site labelled by $\vec{R_{i}}^{0}$. So the new density would be
$$\rho\left(\vec{r}\right)=\sum_{i}\boldsymbol{\delta}\left(\vec{r}-\vec{R_{i}}\right).$$ The result of appendix A in the above mentioned paper is that this density can be expanded as following
$$\rho\left(\vec{r}\right)\approx\rho_{0}-\rho_{0}\nabla.\vec{u}+\rho_{0}\sum_{\vec{K}\neq0}\exp\left(\dot{\iota}\vec{K}.\left(\vec{r}-\vec{u}\right)\right),$$
where $\rho_{0}$ is the average density, and $\vec{K}$ are the Brillouin zone (BZ) vectors of the undeformed lattice.
They arrive at this result by defining a continuous field  $\vec{\phi}\left(\vec{r}\right)\equiv\vec{r}-\vec{u}\left(\vec{\phi}\right)$, and following some elastic approximations. But I believe the derivation is not transparent (for e.g. A5 should be an approximation, not an exact result).
I was wondering whether there is an easier way to arrive at this result without defining this spurious field $\vec{\phi}$. If not, I will very much appreciate it if there is a clear way to think through this derivarion.


text:
Q: Material UI treating iPad (768px width and 1024px height) as a small screen The layout between medium and small screens on my app is quite different, and I am taking advantage of Material UI's breakpoints to decide the proper layout.
From what I can tell in the documentation, small screens are to 600px and under. However, even with these breakpoints, on the iPad components are still being rendered as if it was a small screen, even though it has a width of 768px.
For example:
const MyComponent = () => (
    <div>
        <Box display={{ xs: 'none', sm: 'none', md: 'block', lg: 'block' }}>
            Display only on MEDIUM screens and up! So, should be displayed on the iPad!
        </Box>
        <Box display={{ md: 'none', lg: 'none' }}>
            Display only on SMALL screens. Should NOT be displayed on the iPad!
        </Box>
    </div>
)

These two blocks have been pretty smooth overall, except on the iPad which displays the small one. All the theme breakpoint settings are left in Material UI's default.
What is going on? Is there a specific setting relating to tablets that I have missed? How can I fix this and always treat anything above 600px as a medium screen?

A: Material-ui breakpoints are defined thus:
xs, extra-small: 0px sm, small: 600px md, medium: 960px lg, large:    1280px xl, extra-large: 1920px
A breakpoint goes from its value as above (inclusive) up to the next breakpoint (exclusive).
Therefore a breakpoint of sm will include the iPad 768px. Small screens are NOT 600px and under, that is xs. They are 600px and over (up to but not including 960px).
See documentation at: https://material-ui.com/customization/breakpoints/


text:
Q: react-native-chart-kit different Shadow color so I want to draw two lines on my chart, I gave each line a different color using color. I want to give each line a different shadow as well. However by changing withShadow, it will either true for both or false for both, cannot each for each. I wish I could use the shadow for one dataset and not the other or have it of different color for each.
<LineChart
  data={{
    labels: dataDayOfWeek,
    datasets: [
      {
        data: dataValueNew,
        color: `rgba(25, 255, 12, 1)`,
      },
      {
        data: dataValueOld,
        color: `rgba(25, 255, 12, 0)`,
        withShadow: false, //this did not work
      },
    ],
  }}
/>;

A: There's a pretty simple feature for it. It took me also, an hour to figure out it.
The chartConfig has a field called, useShadowColorFromDataSet -> Boolean
Here's the documentation -
https://github.com/indiespirit/react-native-chart-kit

Just declare that in the chartConfig and then use the Color field in datasets and you'll be done.
Here's a sample code snippet ->
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import {
  LineChart,
  BarChart,
  PieChart,
  ProgressChart,
  ContributionGraph,
  StackedBarChart,
} from 'react-native-chart-kit';
import { Dimensions } from 'react-native';
const screenWidth = Dimensions.get('window').width;
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default function App() {
  return (
    <View>
      <Text>Bezier Line Chart</Text>
      <LineChart
        data={{
          labels: ['January', 'February', 'March', 'April', 'May', 'June'],
          datasets: [
            {
                data: [9, 7, 6, 4, 2, 5],
                strokeWidth: 2,
                color: (opacity = 1) => purple,
                 // optional
              },
              {
                data: [9, 4, 6, 8, 8, 2],
                strokeWidth: 2,
                color: (opacity = 1) => black,
                colors: 'purple' // optional
              },
              {
                data: [9, 4, 7, 8, 2, 4],
                strokeWidth: 3,
                color: (opacity = 1) => blue, // optional
              },
          ],
        }}
        width={Dimensions.get('window').width} // from react-native
        height={220}
        yAxisLabel="$"
        yAxisSuffix="k"
        yAxisInterval={1} // optional, defaults to 1
        chartConfig={{
          backgroundColor: 'grey',
          backgroundGradientFrom: 'grey',
          backgroundGradientTo: 'grey',
          decimalPlaces: 2, // optional, defaults to 2dp
          color: (opacity = 1) => rgba(255, 255, 255, ${opacity}),
          labelColor: (opacity = 1) => rgba(255, 255, 255, ${opacity}),
          style: {
            borderRadius: 16,
          },
          propsForDots: {
            r: '',
          },
          propsForBackgroundLines: {
            color: 'black',
            stroke: 'black',
            strokeDasharray:[],
          },
          useShadowColorFromDataset: true
        }}
        bezier
        style={{
          marginVertical: 8,
          borderRadius: 16,
        }}
      />
    </View>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ECF0F1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Well, it was always present in the docs. Which teaches, that always read the docs properly. It took me an hour to figure it out.


text:
Q: Trying to purposely corrupt data in a photo to get the effect I'm trying to purposely corrupt the data in a photo and recover it to get the cool effect it leaves behind.  I don't want to recreate it in Photoshop, i'd like to do it organically if that make sense. I'm looking for any information on corruption and recovery. what makes this crazy effect happen.
I've attached a image of what im looking for..again if anyone has articles or any information on this subject i'd like to be indulged! Thanks in advance!


text:
Q: Dual monitor setup issue - Both monitors detected but 2nd screen Is black I recently upgraded my computer from using onboard graphics to a GTX 960 (GV-N960OC-4GD).
I previously had a dual monitor setup, with my primary monitor (SyncMaster2233sw) using a DVI cable and the secondary monitor (Syncmaster 173v) using a VGA cable. I purchased a DVI to VGA adapter to connect the secondary monitor, and while it detects the monitor the screen remains black as if it is in standby mode.

I can even move windows and my mouse onto the second monitor, however it obviously just disappears from sight. I've also tried switching the cables to see if it was a faulty port, however my primary monitor works in both, just the secondary that remains black.
Any help would be much appreciated!
NVIDIA Control Panel:

GPU drivers:

UPDATE: The problem was just a faulty VGA-to-DVI adapter. That's what I get for buying it off eBay I guess.
UPDATE 2: It turns out that I needed a DVI-I adapter as my secondary screen apparently only accepts analogue output whereas I was using a DVI-D (digital) adapter.

A: Assuming that you are using a Windows machine, try the following:

*

*See if the connections are correct.

*Press Windows key + P.

*Select duplicate or extend options.

*Even now if the screen does not appear then check if you have powered on the 2nd monitor.

A: I fixed mine by turning off monitor, plugging the hdmi cable out of the laptop. Then turned off the main power switch for the monitor and waited for about 20 sec. Turned back on the power switch. Turned back on the monitor and insert the hdmi cable back into the laptop. Andddd it suddenly appeared on the other monitor too.

A: It's weird, that the second monitor is not listed in the device manager.
Check if the current screen settings for your second monitor are actually supported by it (screen resolution, refresh rate).
Then try to swap monitors (change their order of 1 and 2 internally in Windows only) and see, if the second one is actually responding.
If that doesn't help, change their connections on your PC - maybe the second DVI-out out is somehow ... "broken".
If the second monitor still stays black - get a new one ;-)
Sometimes my second monitor isn't available too and flickrs (?) all around. Then i just turn it off and on again and then it is recognized by Windows.
But there might also be a wrong setting that prevents outputting video information on the second DVI-out. You might double check your setting within nVidia Control Panel and the (usually) built-in Intel Graphics Control panel or whatever.

A: There exist "video range extender" solutions which connect signals directly to a different cable style, without changing the signal format.  This is useful if, for example, you have long VGA cables permanently installed inside the walls of your room, because you can use the existing cable to carry DVI or HDMI data.  But you must use the corresponding adapter to change the signal back to its original connector type, that matches the signal encoding.  You can't expect to connect directly to a device supporting the new connector format, since it also expects a different signal encoding.
While a DVI-I to VGA connector is also passive (no re-encoding), use of the analog pins in the DVI-I connector signal to the video source to generate VGA (analog) signalling instead of DVI, so that the monitor receives a real VGA signal as it expects.
Another thing to try if whether your second monitor has an "input" or "source" button.  If your monitor is displaying from DVI in but you've hooked up its VGA cable, then you would not get any picture.

A: I just encountered the same problem. Found the solution which is to right click on the 2nd monitor -> Properties -> Under the Adapter tab -> List All Modes and change it to 16 bit.

A: Wow, all I did was press the monitor menu buttons on the physical monitor and it magically starting displaying and no longer blank.
I was about to try and reset to factory defaults as I read elsewhere on the web might work, but now... I don't need to.
Hope this helps someone :).

A: In the monitor menu, I changed the input port version from HDMI 2 to HDMI 1.4 and it worked


text:
Q: Modification of a const reference via an interrupt Is it safe to have a variable passed by const reference modified externally (via an interrupt)?
std::atomic_bool g(true);

void sig_handler(int num) {
   switch(num) {
      case SIGHUP:
        g = false;
        break;
   }
}

void method(const std::atomic_bool &flag) {

   while(flag) {
      ...
   }
}

method(g);  // blocks

Here we have a const reference that is modified externally via an interrupt. I get the fact that the callee (method) can't modify flag, but can the caller modify g? Because in g space std::atomic_bool is not const.

A: If this is an external process / OS that's changing the flag, then you just need atomic, that's all, no volatile needed. This is the case for SIGHUP.
If this is an actual hardware interrupt that changes the value: this is one of the very few valid use cases of volatile keyword. (Very) loosely speaking, volatile informs the compiler that it cannot assume that the value written to an address last will be the value read from the address, or that the value doesn't change without writing into it. In this case, you have a const volatile std::atomic_bool& - in this case, declare g itself as both volatile and atomic.

A: I don't agree with @lorro here. You don't really need volatile modifier.
std::atomic<T>::operator<T> :

Atomically loads and returns the current value of the atomic variable.
  Equivalent to load().

It means that each time your evaluate flag in loop condition you atomically obtain actual value of flag variable. And you don't have to flag this variable as volatile.
Difference between volatile and std::atomic types is perfectly explained in  Scott Meyers Effective Modern C++, chapter Item 40: Use std::atomic for concurrency, volatile for special memory.


text:
Q: No match to std::vector when specifying vector size in constructor class Foo {
    vector<Bar> bars;
  public:
    Foo(int barcount) : { bars(barcount, 0); };
};

I'm trying to turn the bars vector into a vector holding barcount Bars. However I get 2 errors when doing this:
Foo.cpp:8: error: expected identifier before '{' token
Foo(int barcount) : { bars(barcount, 0); };
                           ^
Foo.cpp:8: error: no match for call to '(std::vector<Bar>) (int&, int)'
Foo(int barcount) : { bars(barcount, 0); };

Any help on what might be going wrong would be much appreciated.
EDIT: This is my code now (Foo/Bar replaced):
class Machine {
    vector<Rotor> rotors;
  public:
    Machine(int rotorcount) : rotors(rotorcount, 0) {}
};

And I get a pretty long error message:
/usr/include/c++/4.8/bits/stl_vector.h: In instantiation of 'void std::vector<_Tp, _Alloc>::_M_initialize_dispatch(_Integer, _Integer, std::__true_type) [with _Integer = int; _Tp = Rotor; _Alloc = std::allocator<Rotor>]':
/usr/include/c++/4.8/bits/stl_vector.h:404:55:   required from 'std::vector<_Tp, _Alloc>::vector(_InputIterator, _InputIterator, const allocator_type&) [with _InputIterator = int; _Tp = Rotor; _Alloc = std::allocator<Rotor>; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<Rotor>]'
Machine.cpp:8:51:   required from here
/usr/include/c++/4.8/bits/stl_vector.h:1166:59: error: no matching function for call to 'std::vector<Rotor>::_M_fill_initialize(std::vector<Rotor>::size_type, int&)'
    _M_fill_initialize(static_cast<size_type>(__n), __value);
                                                           ^
/usr/include/c++/4.8/bits/stl_vector.h:1166:59: note: candidate is:
/usr/include/c++/4.8/bits/stl_vector.h:1212:7: note: void std::vector<_Tp, _Alloc>::_M_fill_initialize(std::vector<_Tp, _Alloc>::size_type, const value_type&) [with _Tp = Rotor; _Alloc = std::allocator<Rotor>; std::vector<_Tp, _Alloc>::size_type = long unsigned int; std::vector<_Tp, _Alloc>::value_type = Rotor]
       _M_fill_initialize(size_type __n, const value_type& __value)
       ^
/usr/include/c++/4.8/bits/stl_vector.h:1212:7: note:   no known conversion for argument 2 from 'int' to 'const value_type& {aka const Rotor&}'

A: The initializer list goes after the comma, but before the constructor body, and is not followed by a semicolon:
Foo(int barcount) : bars(barcount, 0) {};

A: no known conversion for argument 2 from 'int' to 'const value_type& {aka const Rotor&}'

Sounds like you don't have a constructor that takes int as a single parameter.


text:
Q: Google Maps not rendering completely on page? I have a google maps on my page with a search pane I built myself which can be displayed and hidden at will. It covers like lets say 200 pixels of the map on a side. The thing is that when I resize my map or so the area where the pane overlaps is unrendered i.e the map doesn't render there for some reason.
Check out this link
In the Box type in lets say OMDB which is an icao code for an airport and press enter.
The results are shown and you see the pane. Now click on the full screen link and then click on the airports tab to make the panel go away - you see now that part of the map hasn't rendered at all...I have to drag the map around and that only partially renders that area. How can I fix it?
FYI I've run it on Google Chrome, Firefox and IE8 on Windows XP. Is there a way to like force complete rendering of a map or so? This is quite an erratic problem and could it be concerne with my code or is it a host issue? Or does Google just don't like me? :(
EDIT: See the big ugly patch on the side. Its unrendered area where the map should have been rendered as well. No amount of zooming in and panning is helping clear this :(

A: In Google Maps V3, the little bit of magic you need is documented here:
https://developers.google.com/maps/documentation/javascript/reference#Map
under events

Developers should trigger this event on the map when the div changes
  size: google.maps.event.trigger(map, 'resize')

The trick is knowing when to call this which will be situational depending on your code. If you're using Bootstrap 3 Modals, this works beautifully.
$("#modal-map")
    .modal()
    .on("shown.bs.modal", function() {
        google.maps.event.trigger(gmap, 'resize');
    });

Where gmap is the google.maps.Map object you created.

A: I faced same issue when i tried to load google map in dialog. It was like google map was not rendered properly. so i find out below solution which may be solve your problem.
I have triggered google map resize event after initialize dialog please check below snipped code.
google.maps.event.trigger(map, 'resize', function () {
    // your callback content
});

Example:
I have loaded map by ajax call then initialized dialog and at last triggered google map resize event.
$.ajax({
    url:"map.php",
    type:"POST",
    success:function(data){
        $("#inlineEditForm").html(data);

        $('#inlineEditPopUp').dialog('open');
        google.maps.event.trigger(map, 'resize', function () {
            // your callback content
        });
    }
});

A: If you are using the jQuery plugin goMap, then you should use:
google.maps.event.trigger($.goMap.map, 'resize');

Although you should wrap this in an event so that it runs when the map is shown.
This how i do it in my code :
$(document).on('click', '#mapClicker', 'initmap', function() {
   setTimeout(function() {
         google.maps.event.trigger($.goMap.map, 'resize');
      $.goMap.fitBounds();
   }, 100)
});

A: I'm not able to reproduce the issue you are having, but it looks similar to another issue I've seen with google maps.
It looks like you might be running afoul of the way google maps determines which tiles are in view.  It calculates this only once, when the map is loaded into the div the first time, and if the div grows, then not enough map will be drawn.  Fortunately, this is easy to deal with.  any time the container may have resized, use the checkResize() method on the map instance, and the clipping area will be recomputed from the container's current size.

A: Yes, you MUST supply a real pixel height and width of the container DIV. This is in fact detailed in the Google API.
By using something like this:

instead of

you'll be home free !

A: As far as I can see it works fine on OS X 10.6.2 in Google Chrome.
http://i33.tinypic.com/sfe3ah.png
Only problem is that Copenhagen Airport is nowhere near the location your application implies. And LAX is in the middle of the ocean ;-)
Edit:
I see your screenshot, and it would appear to me that somehow Google Maps does not render the part of the map that was covered by the search and search results pane, and afterwards the rendering is not triggered correctly upon hiding the search pane.
I haven't been able to find a decent render triggerer in the Google Maps API, but I think you should try something like programatically zooming in and out or moving the center of the map somewhere else and back, in order to maybe force the re-rendering of the map.
Alternatively you could try manually triggering some of the events that you think might set off a rerendering of the map, for example google.maps.event.trigger(map, 'resize').
I know these suggestions feel like a terrible hacking way of making it work, and I am highly unsure whether it would work, but it is my best shot ;-)

A: I know this question is a bit old, but I just came across a similar problem. However, in my case, I was setting the map to be loaded from the body (for a full screen effect) within an iframe.
Like Jay mentioned on his answer a width and height must be specified which I had not done then.
I changed:

to:

and now it loads perfectly on Chrome, Firefox and Internet Explorer 10.
Hopefully this helps anyone out there who also came across this problem. You must specify width and height for it to work across different clients.
Regards

A: I had the same problem and solved it simply by changing the width of the containing div to "px" instead of "%" (e.g width="700px" instead of "80%"). I guess that google can do better size calculation that way... I don't guarantee for this but it helped me

A: I had this issue and I found the only solution (in my instance) was to trigger the resize inline after the element.  I can't say why but I found a thread where somebody also had this solution. (sorry no ref.) My setup was a tad different; it was from a jQueryMobile injected page so the late instantiation may have something to do with my issue. Hopefully this helps someone.

A: In my case, same issues for Mac devices on:
Safari 5.1.7 (Os Windows 10[Sorry])
Safari 5.1 (Ipad 1 [Old Sorry])
Safari 10 (Iphone 6 Plus)
Here my solution work for me:
1) capture Browser width detect.min.js
2) change attr style width parameter
3) resize map

/* Of course insert detect.min.js and Jquery in your HTML ;)*/
var user = detect.parse(navigator.userAgent);
var browserFamily=user.browser.family;
var browserVersion=user.browser.version;
if ( browserFamille=="Mobile Safari" || browserVersion.substr(0,3)=="5.1") {
    canvasWidth = $(window).width(),
    $(".macarte").attr("style","width:"+canvasWidth+"px")
    google.maps.event.trigger(map, 'resize');
}
/* browserFamily returns "Mobile Safari" for tablet and mobile devices; "Safari" for desktop devices */

A: I faced the same issue when setting the map centre manually. I solved it by the below code:
google.maps.event.trigger(map, "center_changed");

A: function initialize(lon,lat) {
var largeLatlng = new google.maps.LatLng(lon,lat);
var largeOptions = {zoom: 18, center: largeLatlng,mapTypeId:     google.maps.MapTypeId.ROADMAP};
var largeMap = new google.maps.Map(document.getElementById("map"), largeOptions);
var largeMarker = new google.maps.Marker({position: largeLatlng, map:largeMap, title:"Cherrytrees"});

google.maps.event.addListenerOnce(largeMap, 'idle', function(){
    google.maps.event.trigger(largeMap, 'resize');
    largeMap.setCenter(largeLatlng);
});
largeMarker.setMap(largeMap);

}


text:
Q: How to find $E[X^2\mid X+Y]$? Suppose $X$ and $Y$ are independent Poisson random variables with rates $\lambda_1, \lambda_2$ respectively, then how would we go about calculating:
$
E[X^2\mid X+Y] \text{ ?}
$$

A: Since $X+Y\sim\mathrm{Poisson}(\lambda_1+\lambda_2)$, for any positive integer $n$ we have
$$
\begin{align*}
\mathbb P(X=k|X+Y=n) &= \frac{\mathbb P(X=k, X+Y=n)}{\mathbb P(X+Y=n)}\\
&= \frac{\mathbb P(X=k)\mathbb P(Y=n-k)}{\mathbb P(X+Y=n)}\\
&= \left(\frac{e^{-\lambda_1}\lambda_1^k}{k!}\right)\left(\frac{e^{-\lambda_2}\lambda_2^{n-k}}{(n-k)!}\right)\left({\frac{e^{-(\lambda_1+\lambda_2)}(\lambda_1+\lambda_2)^n}{n!}}\right)^{-1}\\
&= \frac{\lambda_1^k\lambda_2^{n-k} n!}{(\lambda_1+\lambda_2)^n k!(n-k)!}\\
&= \binom nk \left(\frac{\lambda_1}{\lambda_1+\lambda_2}\right)^k\left(\frac{\lambda_2}{\lambda_1+\lambda_2}\right)^{n-k}
\end{align*}
$$
so that $$X|X+Y=n\sim\mathrm{Bin}\left(n,\frac{\lambda_1}{\lambda_1+\lambda_2}\right).$$ It follows from linearity of conditional expectation that
$$
\begin{align*}
\mathbb E[X^2|X+Y=n] &= \mathbb E[X(X-1)|X+Y=n] + \mathbb E[X|X+Y=n]\\ &= n(n-1)\left(\frac{\lambda_1}{\lambda_1+\lambda_2}\right)^2  + \frac{n\lambda_1}{\lambda_1+\lambda_2}\\ &= \frac{n\lambda_1(n\lambda_1+\lambda_2)}{(\lambda_1+\lambda_2)^2}.
\end{align*}$$


text:
Q: Formatting Numbers in Swift 3 I want to format number to this: 123.234.234.234 from 123234234234 depends on what the user types into the text field.
I don't want to manage currency, it's not about currency, it is about the user has to type in a number and this number should be formatted correctly to be easier to read.
Not with a comma, with a dot.
I found only currency stuff in the whole research

A: You can do it with NumberFormatter:
let yourNumber = 123234234234
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
numberFormatter.groupingSeparator = "."
let formattedNumber = numberFormatter.string(from: NSNumber(value:yourNumber))

A: Details

*

*Xcode 9.2, Swift 4

*Xcode 10.2 (10E125), Swift 5

Solution
import Foundation

extension String { var toLocale: Locale { return Locale(identifier: self) } }

extension NumberFormatter {
    convenience init(numberStyle: NumberFormatter.Style, groupingSeparator: String?, decimalSeparator: String?) {
        self.init()
        set(numberStyle: numberStyle, groupingSeparator: groupingSeparator, decimalSeparator: decimalSeparator)
    }

    convenience init(numberStyle: NumberFormatter.Style, locale: Locale) {
        self.init()
        set(numberStyle: numberStyle, locale: locale)
    }

    func set(numberStyle: NumberFormatter.Style, groupingSeparator: String?, decimalSeparator: String?) {
        self.locale = nil
        self.numberStyle = numberStyle
        self.groupingSeparator = groupingSeparator
        self.decimalSeparator = decimalSeparator
    }

    func set(numberStyle: NumberFormatter.Style, locale: Locale?) {
        self.numberStyle = numberStyle
        self.locale = locale
    }
}

extension Numeric {
    func format(formatter: NumberFormatter) -> String? {
        if let num = self as? NSNumber { return formatter.string(from: num) }
        return nil
    }
}

Usage
let formatter = NumberFormatter(numberStyle: .decimal, locale: "fr_FR".toLocale)
print(value.format(formatter: formatter))

formatter.set(numberStyle: .decimal, groupingSeparator: " ", decimalSeparator: ".")
print(value.format(formatter: formatter))

Full sample

Do not forget to add the solution code here

func test<T: Numeric>(value: T) {
    print("=========================================================")
    print("\(T.self), value = \(value)")

    let formatter = NumberFormatter(numberStyle: .decimal, locale: "fr_FR".toLocale)
    print(value.format(formatter: formatter) ?? "nil")
    formatter.set(numberStyle: .currency, locale: "de_DE".toLocale)
    print(value.format(formatter: formatter)  ?? "nil")
    formatter.set(numberStyle: .decimal, groupingSeparator: " ", decimalSeparator: ".")
    print(value.format(formatter: formatter)  ?? "nil")
}

func print(title: String, value: String?) {
    if let value = value { print("\(title) \(value)") }
}

test(value: Int(10000))
test(value: Double(10000.231))
test(value: Float(10000.231))

Result
=========================================================
Int, value = 10000
10 000
10.000,00 €
10 000
=========================================================
Double, value = 10000.231
10 000,231
10.000,23 €
10 000.231
=========================================================
Float, value = 10000.231
10 000,231
10.000,23 €
10 000.231

A: swift 4
extension Int {
    func formatnumber() -> String {
        let formater = NumberFormatter()
        formater.groupingSeparator = "."
        formater.numberStyle = .decimal
        return formater.string(from: NSNumber(value: self))!
    }
}

A: For leading zeros (Swift 5.2)
String(format: "%02d", intNumber) // 6 -> "06"
String(format: "%03d", intNumber) // 66 -> "066"
String(format: "%04d", intNumber) // 666 -> "0666"

from: https://stackoverflow.com/a/25566860/1064316

A: What you are looking for is probably groupingSeparator of NumberFormatter
let formater = NumberFormatter()
formater.groupingSeparator = "."
formater.numberStyle = .decimal
let formattedNumber = formater.string(from: number)

A: There's actually much easier solution (there is no need to create NumberFormatter instance) and it takes into account the user's language:
let result = String(format: "%ld %@", locale: Locale.current, viewCount, "views")

Result for value 1000000 with English:

1,000,000

Russian:

1 000 000

p.s. in Android it's exactly the same String.format(Locale.getDefault(), "%,d %s", viewCount, "views")

A: For swift 4, I implemented an extension where I can choose the formatting or use default one if none is selected.
extension Int {
    func formatnumber(groupingSeparator: String?) -> String {
        let formater = NumberFormatter()
        formater.groupingSeparator = (groupingSeparator != nil) ? groupingSeparator! : ","
        formater.numberStyle = .decimal
        return formater.string(from: NSNumber(value: self))!
    }
}

A: My script as an example:
1) Add extension to project
extension String {

    public func subString(startIndex: String.Index, endIndex: String.Index) -> String {
        return String(self[startIndex...endIndex])
    }

    public func subString(_ from: Int, _ to: Int) -> String {
          let startIndex = self.index(self.startIndex, offsetBy: from)
          let endIndex = self.index(self.startIndex, offsetBy: to)
        return String(self[startIndex...endIndex])
    }
}

2) Create file Utilites.swift and add my method
public func  priceNumFormat(_ number: String)->String{

    var formattedNumber = number
    var print = number
    var prefix = ""

    if number.range(of:"-") != nil {
        let index = number.index(of:"-")
        formattedNumber.remove(at: index ?? formattedNumber.endIndex)
        prefix = "-"
    }

    if formattedNumber.range(of:".") != nil {
        let index = formattedNumber.index(of:".")
        formattedNumber =  formattedNumber.subString(startIndex: formattedNumber.startIndex, endIndex: index ?? formattedNumber.endIndex)
        formattedNumber.remove(at: index ?? formattedNumber.endIndex)
    }

    if formattedNumber.count == 8 //10 000 000
    {
       let num0 = formattedNumber.subString(0, 1)
       let num1 = formattedNumber.subString(2, 4)
       let num2 = formattedNumber.subString(5, 7)
       print =  "\(num0) \(num1) \(num2)"
    }

    if formattedNumber.count == 7 //1 000 000
    {
        let num0 = formattedNumber.subString(0, 0)
        let num1 = formattedNumber.subString(1, 3)
        let num2 = formattedNumber.subString(4, 6)
        print =  "\(num0) \(num1) \(num2)"
    }

    if formattedNumber.count == 6 //100 000
    {
        let num0 = formattedNumber.subString(0, 2)
        let num1 = formattedNumber.subString(3, 5)
        print =  "\(num0) \(num1)"
    }

    if formattedNumber.count == 5 //10 000
    {
        let num0 = formattedNumber.subString(0, 1)
        let num1 = formattedNumber.subString(2, 4)
        print =  "\(num0) \(num1)"
    }

    if formattedNumber.count == 4 //1 000
    {
        let num0 = formattedNumber.subString(0, 0)
        let num1 = formattedNumber.subString(1, 3)
        print =  "\(num0) \(num1)"
    }

    if formattedNumber.count == 3 //100
    {
        print =  formattedNumber
    }

    if prefix.count > 0
    {
        print = "- \(print)"
    }

    return print;
}

3) Add code in your UIController
 let utils = Utilites()
            private func test(){
                var price =  self.utils.priceNumFormat("-12345678.000")
                print("\(price)") //-12 345 678
                price =  self.utils.priceNumFormat("-1234567.000")
                print("\(price)") //-1 234 567
                price =  self.utils.priceNumFormat("-123456.000")
                print("\(price)") //-123 456
                price =  self.utils.priceNumFormat("-12345.000")
                print("\(price)") //-12 345
                price =  self.utils.priceNumFormat("-1234.000")
                print("\(price)") //-1 234
                price =  self.utils.priceNumFormat("-123.000")
                print("\(price)") //-123

            }


text:
Q: Overleaf API - How to programmatically upload an image? I use overleaf to edit latex documents. The overleaf platform has a feature to upload an image file, which can then be referenced and included in the latex document.
I'm able to manually upload images into the overleaf platform, and use/reference them successfully from my latex document, but I was wondering if there is a way to do the uploading programmatically via an API.
I think I might need to use https://github.com/overleaf/filestore but I'm not sure how to get started.
FYI: My main use case is to do this from Python, specifically a Google Colab notebook.

A: Unfortunately, the Overleaf API does not currently allow programmatic upload to existing projects. It's sole purpose is to provide links that can be used to start new projects by users who manually click specially crafted links. Instead, you probably want to look at one of Overleaf's sync options. Currently they offer Git/GitHub and Dropbox options. Once the sync is set up, you could add the files to those sources to allow Overleaf to pull them in.

A: While Overleaf doesn't have its own upload API, Dropbox does. To use it to get files into Overleaf,

*

*Set up Dropbox synchronization. You'll need a paid account for this.

*Make yourself a Dropbox app with 'Full Dropbox Access'.

*Add the 'files.content' permissions to your app.

*Use that web console to get an OAuth2 token, which you'll pass in below.

Now you can upload files! The HTTP API is well documented, but Python at least has a nice SDK. So for me, programmatic uploading worked out to
pip install dropbox

import dropbox
from pathlib import Path
from io import BytesIO
import matplotlib.pyplot as plt

def upload(ax, project, path):
    bs = BytesIO()
    format = path.split('.')[-1]
    ax.figure.savefig(bs, bbox_inches='tight', format=format)

    token = Path('token.txt').read_text()
    dbx = dropbox.Dropbox(token)

    # Will throw an UploadError if it fails
    dbx.files_upload(
        f=bs.getvalue(),
        path=f'/Apps/Overleaf/{project}/{path}',
        mode=dropbox.files.WriteMode.overwrite)

if __name__ == '__main__':
    fig, ax = plt.subplots()

    upload(ax, 'project_name', 'images/test.png')


text:
Q: Capturing picture is not working in Android ( Samsung, Lenovo, Lava etc...) This is the code i am using to open the camera app(Pre-installed camera application )
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, BTN1_IMAGE_REQUEST);

In OnActivityResult method
Bitmap image = (Bitmap) data.getExtras().get("data");
                picUri = getImageUri(this, image);
                if (picUri != null) {
                    View view = ((LinearLayout) btn.getParent())
                            .findViewById(1);
                    ByteArrayOutputStream bao = new ByteArrayOutputStream();
                    image.compress(Bitmap.CompressFormat.PNG, 100, bao);
                    byte[] ba = bao.toByteArray();
                    btnImg1 = Base64.encodeToString(ba, Base64.DEFAULT);
                    BitmapDrawable bdrawable2 = new BitmapDrawable(image);
                    view.setBackgroundDrawable(bdrawable2);

Is this having any issues please let me know any kind of suggestions are also welcomed thanks in advance....
If this method is wrong please let me know what i need to do to capture the image in every kind of mobile with out any issue....
(THANKS IN ADVANCE)


text: Q: How to Display Multiple Y-Axis in PANDASGUI? everyone. I have a DataFrame in Python that comes from an Excel file. I want to display it as a visual chart. But one problem I'm having is that I can't display multiple Y-axes. I can only display one Y axes with one X axis. I want to compare multiple Data in y-axes.


text:
Q: how to display all the users in table users to my subjects table in add.ctp view Here is my subjects add.ctp view
<?= $this->Form->create($subject) ?>
<fieldset>
    <legend><?= __('Add Subject') ?></legend>
    <?php
        echo $this->Form->input('math');
        echo $this->Form->input('english');
        echo $this->Form->input('history');
        echo $this->Form->input('science');

       ******this field will display all the users in drop down************* from users table
    ?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>

****UsersController.php ****
public function index()
{

     $user=  $this->set('users', $this->paginate());

    $this->set('user', $user);
    $this->set('_serialize', ['user']);

}

How to achieve this one please help me...

A: If you want user select box(Dropdown) in the subject add.ctp then you should send all the list of user from add() of SubjectsController.
In subjects add method
public function add()
{
    //Your previous logics

    $this->loadModel('Users');
    $users=  $this->Users->find('list');

    $this->set('users', $users);
    $this->set('_serialize', ['users']);
    //Your previous logics
}

In your subject add.ctp
<?= $this->Form->create($subject) ?>
<fieldset>
    <legend><?= __('Add Subject') ?></legend>
    <?php
        echo $this->Form->input('math');
        echo $this->Form->input('english');
        echo $this->Form->input('history');
        echo $this->Form->input('science');
        echo $this->Form->input('user_id', ['options' => $users]);
    ?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>

In your UsersTable(Users Model), add/edit your initialize() as follow
$this->displayField('username');
$this->primaryKey('id');

A: *

*at your Controller
$allUser = $this->Users->find(); // this will be get all user from user table
$this->set('allUser', $allUser);

*at your View
/**@var array $allUser */// already type of array
    <?= $this->Form->select('all_user', [
        'multiple' => true,
        'value' => $allUser
    ]); ?>

A: Use $this->Form->select() or $this->Form->input('users', ['options' => array()]);
if you do not want to do foreach loop.
try:
<?= $this->Form->select('users', $users); ?>


text:
Q: Why are you late to class? Yesterday I was in my class. Five students came late to class. I asked them " why are you late ? "
  Their responses are given below

*

*I have watched the cricket match.

*I have been watching the cricket match.

*I watched the cricket match.

*I have just watched the cricket match.

*I just watched the cricket match.

I feel a native English speaking student says  "I have been watching the cricket match"
We may expect the answers " I have Just watched the cricket match or I have watched the cricket match"
from non native English speaking students
I am of the opinilon that I have watched or I have been watching the cricket match is correct.
I am not sure of the other sentences. I think they are wrong
I would like to know whether the sentences 3,4, and 5 are also possible
I would be most grateful to you if you could answer my question

A: As a native speaker, my answer would be

I was watching the cricket match.

Past perfect continuous tense means the action began at a time in the past and continued at the point in time being described or was somehow incomplete then. In the context of your question, I (the student) am late for class now because I watched the cricket match that took place close to or perhaps overlapping class time. This implies of course that the student stopped watching but presumably not soon enough to make it to class on time.
Of the answer choices given, the most appropriate would be

I have been watching the cricket match.

Have been … indicates that the speaker was elsewhere but since returned, as opposed to have gone … to mean the person is presently in a different place. This is the present perfect continuous or present perfect progressive tense.
With respect to the other possibilities in your question:

*

*I have watched the cricket match.
This is the present perfect tense, which indicates something started in the past and continues in the present. The students are no longer watching the match, so present perfect may confuse the listener.

*I have been watching the cricket match.
Explained above

*I watched the cricket match.
Simple past tense is a bit robotic in this context. It is a true statement and accurate but only vaguely suggests a connection to being late. One might argue for a difference in precision over whether the student watched the cricket match to completion, in which case simple past would be more appropriate, or whether the match was still ongoing when the student left, in which case past continuous would be slightly better.

*I have just watched the cricket match.
Present perfect again. Using just implies that it took place in the recent past, but the whole construction is wordy and awkward. Good English style is careful about use of just, only, and very. Also, statements perceived as being overly wordy may cause the listener to be suspicious.

*I just watched the cricket match.
Just is mildly ambiguous here. Does the speaker mean just as in recently completed or just as in was watching the match and nothing more?

A: "I have been watching a cricket match" is wrong because there is no time frame, so we can not use present perfect continuous tense


text:
Q: Use Django model IntegerField validator values on the form I am able to set the minimum value validator on the model:
class MyModel(Model):
    my_field = models.fields.IntegerField(default=250, validators=[MinValueValidator(30)])

Then I create a form using the previous model:
class MyForm(ModelForm):
    class Meta:
        model = MyModel
        fields = ('my_field',)

The form gets validated, the correct error message is displayed (when entered value is <30), but even when entered wrong value, it gets saved on the instance!
I was able to make it work by specifying (again) the min value on the form:
class MyForm(ModelForm):
    my_field = form.IntegerField(min_value=30)

    class Meta:
        model = MyModel
        fields = ('my_field',)

But this way the code is not dry - I need to specify the value and field type twice.
Is there any way I could avoid this? Or at least get the min_value from the model validator?

A: Validators don't have anything to do with saving the model - other than the fact they should be checked before saving.
docs

Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.

Either ensure that you are strict with how you allow objects to be created or you may need to override save or provide a pre_save signal

A: I think all the problem you have is this .fields you added, and you didn't call models.Model properly. Every other thing seem to be in order.
my_field = models**.fields**.IntegerField(default=250, validators=[MinValueValidator(30)])
Try this:
class MyModel(models.Model):
    my_field = models.IntegerField(default = '250', validators = MinValueValidator(30)])


text:
Q: How to get updated copy state of azure blob when using blob StartCopyAsync I have some c# code to copy a blob from one storage account to another.  I noticed that when I make the call to CloudBlob.StartCopyAsync, the target blob's CopyState.Status is set to CopyStatus.Pending.  Is there any way that I can get an updated status on the copy operation?
I have tried adding a await Task.Delay(TimeSpan.FromSeconds(10)); after the call, but when the delay finishes, the state still shows pending.  If I then try to re-obtain the blob from the storage container, I get CopyStatus == null.

A:
Polling for Copy Blob properties: we now provide the following additional properties that allow users to track the progress of the copy, using Get Blob Properties, Get Blob, or List Blobs:
x-ms-copy-status (or CopyStatus): The current status of the copy operation. It can be one of the following:
  pending: Copy operation is pending.
  success: Copy operation completed successfully.
  aborted: Copy operation was aborted by a client.
  failed: Copy operation failed to complete due to an error.
x-ms-copy-id (CopyId): The id returned by the copy operation which can be used to monitor the progress or abort a copy.
x-ms-copy-status-description (CopyStatusDescription): Additional error information that can be used for diagnostics.
x-ms-copy-progress (CopyProgress): The amount of the blob copied so far. This has the format X/Y where X=number of bytes copied and Y is the total number of bytes.
x-ms-copy-completion-time (CopyCompletionTime): The completion time of the last copy.
These properties can be monitored to track the progress of a copy operation that returns "pending" status. However, it is important to note that except for Put Page, Put Block and Lease Blob operations, any other write operation (i.e., Put Blob, Put Block List, Set Blob Metadata, Set Blob Properties) on the destination blob will remove the properties pertaining to the copy operation.

https://blogs.msdn.microsoft.com/windowsazurestorage/2012/06/12/introducing-asynchronous-cross-account-copy-blob/
Please note that you need to periodically poll the copy state from Azure Storage server side, await Task.Delay(TimeSpan.FromSeconds(10)); does nothing actually.
public static void MonitorCopy(CloudBlobContainer destContainer)
{
    bool pendingCopy = true;

    while (pendingCopy)
    {
        pendingCopy = false;
        var destBlobList = destContainer.ListBlobs(
            true, BlobListingDetails.Copy);

        foreach (var dest in destBlobList)
        {
            var destBlob = dest as CloudBlob;

            if (destBlob.CopyState.Status == CopyStatus.Aborted ||
                destBlob.CopyState.Status == CopyStatus.Failed)
            {
                // Log the copy status description for diagnostics
                // and restart copy
                Log(destBlob.CopyState);
                pendingCopy = true;
                destBlob.StartCopyFromBlob(destBlob.CopyState.Source);
            }
            else if (destBlob.CopyState.Status == CopyStatus.Pending)
            {
                // We need to continue waiting for this pending copy
                // However, let us log copy state for diagnostics
                Log(destBlob.CopyState);

                pendingCopy = true;
            }
            // else we completed this pending copy
        }

        Thread.Sleep(waitTime);
    };
}


text:
Q: How do I create a new column in r that is a binomial variable based on a string variable? I'm currently trying to create a new column in my data frame based on another column using mutate().
I want to make the new column a binomial variable (1 or 0) based on whether the column its based on says "Active" or not. I'm currently trying to do it by saying:
violations$outcome = if (violations$RESULT == "Active") { 1 } else { 0 }

This currently produces the "Warning message:
In if (violations$RESULT == "Active Rat Signs") { :
  the condition has length > 1 and only the first element will be used" and I look at my new data frame and every violations$outcome is 0.
Does anyone have any idea how to do this and why my original answer isn't working? This is very frustrating and I would appreciate any comments, advice, or help you have to offer. Thank you.

A: R has a handy function called ifelse
Try violations$outcome = ifelse(violations$RESULT == 'Active', 1, 0). The first argument is the condition you're testing, the second argument is what to return if it is TRUE and the third agrument is what to return if it's FALSE.


text:
Q: How to prevent Thymeleaf Template Engine read path URL Get Mapping as a template engine name in Spring Boot I have a controller get mapping which read path variable to return object from repository, and return template engine name using Thymeleaf to show it, and it works well in localhost with postman and browser:
@Controller
public class InvoiceFormController {

  @Autowired
  InvoiceDetailRepository invoiceDetailRepository;

  @Autowired
  InvoiceService invoiceService;

  @GetMapping("/supermarket/invoice/{id}")
  public String getInvoiceView(@PathVariable("id") UUID id, Model model) {
    InvoiceDetail invoiceDetail = invoiceDetailRepository.getInvoiceDetailById(id);
    if(invoiceDetail == null) {
      return invoiceService.showError(model);
    }
    return invoiceService.showDetail(invoiceDetail, model);
  }
}

this is the service:
@Service
public class InvoiceService {

    public Spring showDetail(InvoiceDetail invoiceDetail, Model model) {
      model.addAttribute("invoiceDetail", invoiceDetail);
      return "invoicePage";
    }

    public Spring showError(Model model) {
      model.addAttribute("error", "not found");
      return "errorPage";
    }
}

But, when I creating the unit test, it always became error, because the path url get mapping always read by Spring Boot as template engine name:
ERROR org.thymeleaf.TemplateEngine -[THYMELEAF][main] Exception processing template "supermarket/invoice/d5afd278-db7c-4482-b992-c7440b522067": Error resolving template [supermarket/invoice/d5afd278-db7c-4482-b992-c7440b522067], template might not exist or might not be accessible by any of the configured Template Resolvers
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [supermarket/invoice/d5afd278-db7c-4482-b992-c7440b522067], template might not exist or might not be accessible by any of the configured Template Resolvers

the unit test is looks like this:
@WebMvcTest(InvoiceFormController.class)
class InvoiceFormControllerTest {

  @Autowired
  private MockMvc mockMvc;
  @MockBean
  InvoiceDetailRepository invoiceDetailRepository;
  @MockBean
  InvoiceService invoiceService;
  @Mock
  Model model;

  @Test
  void testViewSuccess() throws Exception {

    InvoiceDetail invoiceDetail = InvoiceDetail.builder().id(UUID.fromString("d5afd278-db7c-4482-b992-c7440b522068").build();

    UUID id = UUID.fromString("d5afd278-db7c-4482-b992-c7440b522068");

    Mockito.when(invoiceDetailRepository.getInvoiceDetailById(id))
            .thenReturn(invoiceDetail);

    Mockito.when(invoiceService.showDetail(invoiceDetail, model))
            .thenReturn("invoicePage");

    mockMvc.perform(MockMvcRequestBuilders.get("/supermarket/invoice/"+"d5afd278-db7c-4482-b992-c7440b522068"))
            .andExpect(MockMvcResultMatchers.status().isOk());
            .andExpect(MockMvcResultMatchers.view().name("invoicePage"));
}


text:
Q: Remove namespace declarations from web service response I have a web service that returns a simple object:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.4927")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(Namespace="urn:CHAMADO")]
public partial class STRUCCHAMADOOUT : object, System.ComponentModel.INotifyPropertyChanged {

    private string cODField;

    private string mSGField;

    /// <remarks/>
    public string COD {
        get {
            return this.cODField;
        }
        set {
            this.cODField = value;
            this.RaisePropertyChanged("COD");
        }
    }

    /// <remarks/>
    public string MSG {
        get {
            return this.mSGField;
        }
        set {
            this.mSGField = value;
            this.RaisePropertyChanged("MSG");
        }
    }

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName) {
        System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
        if ((propertyChanged != null)) {
            propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }
    }
}

this class was generated by wsdl.exe, based on a wsdl file provided by the client. This is the web method:
[WebMethod(MessageName="CHAMADORequest")]
[SoapRpcMethod(
 Action = "urn:CHAMADO#CHAMADO",
 RequestNamespace = "urn:CHAMADO",
 RequestElementName = "CHAMADO",
 ResponseNamespace = "",
 ResponseElementName = "return",
 Use = SoapBindingUse.Literal
)]
[return: XmlElement("return")]
public STRUCCHAMADOOUT CHAMADO(STRUCCHAMADOIN ENTRADA)
{
    STRUCCHAMADOOUT result = new STRUCCHAMADOOUT();
    try {
        string str = Util.GetRequestXML();
        persist(getResult<Entidades.Chamado>(str, "ENTRADA", string.Empty));

        result.COD = "1";
        result.MSG = "Operação realizada com sucesso";
    } catch (Exception ex) {
        result.COD = "0";
        result.MSG = ex.Message + Environment.NewLine + ex.StackTrace;
    }

    return result;
}

The client is saying that his system is raising an error because the service response has namespaces declaration, just like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CHAMADOResponse xmlns="urn:CHAMADO" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <return xmlns="">
        <COD xmlns="urn:CHAMADO">1</COD>
        <MSG xmlns="urn:CHAMADO">Operação realizada com sucesso</MSG>
    </return>
</CHAMADOResponse>

Now, I managed to remove the namespaces from COD and MSG by applying the attriute WebServiceBinding(ConformsTo = WsiProfiles.None) to the service's class and setting ResponseNamespace to an empty string. But CHAMADOResponse still have the namespaces declaration.
I'm pretty sure that it should not be done like that. In fact, I don't believe that the namespaces are the problem at all. This project has been hard since the begining, as we had to create services that matched legacy wsdl.
My question is: is there a way that I could remove all that namespaces declaration from the web service response?
Edit
I've logged the server's response and got this:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <CHAMADOResponse>
            <return>
                <COD>1</COD>
                <MSG>Operação realizada com sucesso</MSG>
            </return>
        </CHAMADOResponse>
    </soap:Body>
</soap:Envelope>

There's no namespace declaration in the message's body. But the client says that he received this:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!-- Request Message Mapping -->
<CHAMADOResponse xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
    <return>
        <COD>1</COD>
        <MSG>Operação realizada com sucesso</MSG>
    </return>
</CHAMADOResponse>

Am I missing something here?

A: Fernando,
I have run into a similar situtation with one our legacy systems (UniVerse) in which it does not have a true XML parser but a homegrown system that works via raw string matching.  The solution we found to work is to implement IXmlSerializable in the classes that will be transmitted to the system and when writing out to the XmlWriter we can control what namespaces get added.  An example of one of these implementations is below.
/// <summary>
/// Serialize the state to XML
/// </summary>
/// <param name="writer">The writer to write the state</param>
public void WriteXml(XmlWriter writer)
{
    writer.WriteElementString("TERMINATION_STATUS", Status);
    writer.WriteElementString("TRANS_SEQ_NUM", Sequence.ToString());
    writer.WriteElementString("INTRN_SEQ_NUM", Id.ToString());
    writer.WriteElementString("CMRCL_FLAG", IsCommercialCard.ToString());
    writer.WriteElementString("AUTH_CODE", Authorization);
    writer.WriteElementString("CMRCL_TYPE", CommericalFlag.ToString());
    writer.WriteElementString("RESULT_CODE", ResultCode.ToString());
    writer.WriteElementString("TROUTD", RoutingId.ToString());
    writer.WriteElementString("RESPONSE_TEXT", Message);
    writer.WriteElementString("REFERENCE", ProcessorReferenceCode);
    writer.WriteElementString("PAYMENT_MEDIA", PaymentMedia);
    writer.WriteElementString("RESULT", Result.ToString().ToUpper());
    if (Error != null)
    {
        writer.WriteStartElement("ERROR");
        writer.WriteElementString("ERROR_CODE", Error.Code);
        writer.WriteElementString("ERROR_DESCRIPTION", Error.Description);
        writer.WriteEndElement();
    }
}

Again since it is a custom situtation it my not help but it is easy enough to try.


text:
Q: magento custom dashboard tabbed contents I would like to create my own "grids" similar to magento's dashboard grids (bestsellers, most viewed products..).
I have tried copying the entire app/code/core/adminhtml folder to my local folder in the hopes of replicating the dashboard page, but magento can't find the page.
There's a better approach to this and I am hoping anyone could provide me the solution.

A: You need to rewrite this method Mage_Adminhtml_Block_Dashboard_Grids::_prepareLayout.
Here is a small and useful tutorial on how to do it.
You can add a new tab similar to the ones that already exist
$this->addTab('reviewed_products', array(//tab name...mut be unique.
    'label'     => $this->__('Most Viewed Products'), //tab label
    'url'       => $this->getUrl('*/*/productsViewed', array('_current'=>true)),//url for ajax call
    'class'     => 'ajax'
));

And you can see how the grid is shown in this method Mage_Adminhtml_DashboardController::productsViewedAction()
You can also see how the layout looks in app/design/adminhtml/default/default/layout/main.xml :
<adminhtml_dashboard_productsviewed>
    <block type="core/text_list" name="root" output="toHtml">
        <block type="adminhtml/dashboard_tab_products_viewed" name="adminhtml.dashboard.tab.products.viewed"/>
    </block>
</adminhtml_dashboard_productsviewed>


text:
Q: Is there a difference between hi and hi!, like hi Visual guibg=#FFEC8B and hi! Visual guibg=#FFEC8B This is a simple question, and I'm only asking it here because I couldn't find the answer in Vim's help, under :h :hi.
I have seen some people use hi and others use hi!, like hi Visual guibg=#FFEC8B vs hi! Visual guibg=#FFEC8B OR hi link CursorLineNr Visual vs hi! link CursorLineNr Visual. Is there a difference between them? From what I know, the bang ! symbol toggles a setting. But when I run them, I get the same results, whether I use hi or hi!.

A: In the form :hi! Group ctermbg=black, the ! nullifies the whole command, which makes it rather pointless.
In the form :hi! link FromGroup ToGroup, the ! forces the link to be made even if FromGroup already has some attributes set.
See :help :hi-link.

A: Block-level HTML elements have a few restrictions:
They must be separated from surrounding text by blank lines.
The begin and end tags of the outermost block element must not be indented.
Markdown


text:
Q: Is $\infty$ undefined? I am confused at $\infty$ in a lot of ways. First, we sometimes say that ${1\over 0}=\infty$. That gives us these confusing calculations.$${1\over0}=\infty$$
$$1=0*\infty$$
$$2=(0*2)*\infty$$
$$2=0*\infty$$
$$1=2$$
But certainly, this is not true. $1\ne 2$. What is happening?
Another confusion: let's say $x=x+1$. This is never true. But with $x=\infty$, it works.
Third confusion: let's say $2x=x$. Subtracting both sides by $x$ gives $x=0$. But what about $\infty$?
Fourth confusion: $x-x=0$ is always true, but not for $\infty$. $\infty-\infty$ is undefined.
What is actually happening??! Any help will be very appreciated.

A: You may calculate with $\infty$, in a certain sense.  For that purpose let $\infty$ be an object which is not a real number, e.g., $\infty:=\{\mathbb R_+\}$. (You may define $-\infty$ as $\{\mathbb R_-\}$.)  Declare for any real number $r$ the set $N_r(\infty\}:=\{x\in\mathbb R\mid x>r\}$ as a neighbourhood of $\infty$.
Apply the usual definition of a limit to define if as sequence has $\infty$ as limit: in each neighbourhood of $\infty$ there are almost all elements of the sequence.
Now prove that for the limit of sequences some of the usual rules are valid, for example $\infty\cdot\infty=\infty$, which means the product of two sequences which limit is $\infty$ has limit $\infty$ as well.  Also $\infty+\infty=\infty$ as well as $\infty\pm a=\infty$ for any sequence with limit $a\in\mathbb R$ and $|a|\cdot\infty=\infty$ for $a\neq0$.  $a/\infty=0$ is another one for non-negative $a$.
On the other hand there are so called "indetermined expressions" as $0\cdot\infty$ or $\infty-\infty$, which can be any number (including $\infty$).

A: Infinity does not exist in the typical real number line: it is a construct that is contained in the extended real number line, which is used in certain fields of mathematics, especially limit calculus. However, the extended real number line does not share all of the same properties of the normal real number line, which means that the apparent contradiction of 1=2 that you have produced does not hold, as certain operations which you performed to reach that point are not valid in the extended real number line. Whenever we manipulate infinity, we must enter the extended real number line, with different properties.


text:
Q: Best Algorithm to randomly generate a number that is divisible by N Is there a better agorithm to do the following?
I am trying to generate 50 random numbers that are divisible by 7. I then select one of those 50 at random & return that number.
Is there a more efficient/better way to randomly generate numbers that are divisible by 7? Is there a better way I could code/do this?
    unsigned int generateRandomNumberDivisibleByN( unsigned int n, unsigned int num=10 )
    {
        // Post: Generate many different random numbers that are divisible by n, then randomly select one of
        //       of those numbers to return.

        unsigned int potentialNums[num];

        for (int i=0, j=2; i<num; i++, j=rand()%INT_MAX)
        {
            potentialNums[i] = j*n;
        }

        return potentialNums[ rand()%num ]; // should this be rand()%(num-1) so it never returns an invalid array index?
    }

A: The most efficient way to randomly generate a number divisible by 7 is to generate a random number and then multiply it by 7.
return ( rand() % ( INT_MAX / 7 ) ) * 7

A: Why can't you just do this?
return (rand() % MAX) * 7;

It does almost the same thing.
Where MAX is small enough to avoid overflow during the multiplication by 7. Which you can define as:
const MAX = INT_MAX / 7;

Or if you want it to be fast, you can do something like:
return (rand() & 0xff) * 7;

A: Why generate a bunch of random numbers, then choose one of them at random?  You have the core idea already:  generate a random number and multiply it by 7.  The potentialNums array doesn't add any value.

A: To make this much faster first use the fast random generation function found here this should make the actual process of creating randoms much faster,
Next, you can multiply the random by 7 and it will always be a multiple of 7, however, if this multiplication causes an overflow of the int (which with randoms is likely) you can always take a mask of the first few bits and multiply them.
e.g.
randomNumber = (generatedRandom & 0x00FFFFFF) * 7


text:
Q: google sign-in post redirected back to login I added the google sign in button and try to post the token back to the server. Created a Filter and a controller for the post and also in the WebSecurityConfigurerAdapter defined it as  .antMatchers("/google-sign-in/**").permitAll().
but my post is redirected back to the login page...
.antMatchers("/google-sign-in/**").permitAll()
.and()
.formLogin()
.loginPage(LOGIN_PAGE_URL)

function onSignIn(googleUser) {
    var profile = googleUser.getBasicProfile();
    console.log('ID: ' + profile.getId());
    console.log('Name: ' + profile.getName());
    var id_token = googleUser.getAuthResponse().id_token;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/google-sign-in?idtoken=' + id_token);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        console.log('Signed in as: ' + xhr.responseText);
    };
    xhr.send('idtoken=' + id_token);
}

what am I doing wrong?