Q:

Evolution of the (phenotypic) facial features of the indigenous people of (west/central) Africa

I am not even remotely an expert in this field; I just got curious, so help me.
First of all, let us remove all human sentimental attributes from this question (such as connotations of scientific racism or emotional reactions thereof) and ask it from a purely scientific point of view. The typical facial feature of a West/Central African person (the so-called broad African type) exhibits a wide nose, a lack of nasal bridge projection (similar to many Asian noses) and a prognathous skull shape that resembles more closely to our ancestor Homo Heidelbergensis than many other indigenous phenotypes from other parts of the world do.
I agree that this claim sounds anecdotal, and is certainly not true of all Africans (for example, Ethiopians), but one cannot dismiss it simply on grounds of ethical policing. I cannot help but notice that many of my African friends remind me of our shared ancestry (with no disrespect meant whatsoever), as is clear from the photographs below, one of a supposed Homo Heidelbergensis and one of a random African Homo Sapiens of today.

My question is the following. What is the reason behind this seeming resemblance? Is this appearance an illusion and possibly a construct of a prejudiced mind, or does this have a valid scientific answer? For example, are most Africans closer to our ancestors than the rest of humanity is? How does evolution answer this question?
Thank you for your help.

A:

Note that I had never heard of the expression "broad african type" and could not find much reference to this term when googling. But anyway, I'm happy to use it to refer to a particular set of typical facial features.

What is the reason behind this seeming resemblance?

Note that the Homo Heidelbergensis image is not a picture (obviously) and much of what is being depicted was open to artistic interpretation. It is possible that some of the feature you are thinking of are not real. Have a look at the post In reconstructions, how are various shapes of facial features determined from skull only?.
You list several phenotypic traits and it would be too broad of a question if you were expecting an explanation about the evolution of each of these traits. I will just pick one classic trait; the nose.
One of the role of the nose is too even up the temperature of the air that we're inhaling. As such, the shape of the nose is under differential selection pressures depending on the environment. So if the nose of Homo Heidelbergensis looked alike (assuming it really looked like on the facial reconstruction) today's "broad African type", it is probably because of shared environment. Note however that nose shape vary a lot among african lineages and also among non-african lineages. You might want to have a look at this popular article.
A big point of ressemblance is the skin color that you don't talk about. Have a look at the posts Why do we assume that the first humans were dark-skinned? and How did some humans evolve to be white? to learn more about skin color

Is this appearance an illusion and possibly a construct of a prejudiced mind, or does this have a valid scientific answer?

First, see my above point about facial reconstruction.
H. Heidelbergensis lived in Africa and in this resepct shared an environment that is like the environment that modern african are encountering that what modern Han Chinese are encountering. In this respect, we could expect some ressemblance.

For example, are most Africans closer to our ancestors than the rest of humanity is?

No, they're not and they cannot be. The MRCA of all humans today is more recent than the MRCA between any human and H. Heidelbergensis. You should have a look at this intro to phylogeny to understand a little bit better how different lineages relate evolutionarily speaking.


Q:

Optimisation using scipy

In the following script:
import numpy as np
from scipy.optimize import minimise

a=np.array(range(4))
b=np.array(range(4,8))

def sm(x,a,b):
      sm=np.zeros(1)
      a=a*np.exp(x)
      sm += sum(b-a)
      return sm

 x0=np.zeros(4)
 print sm(x0,a,b) #checking my function

 opt = minimize(sm,x0,args=(a,b),method='nelder-mead',
 options={'xtol': 1e-8,     'disp': True})

I am trying to optimise for x but I am having the following message:

Warning: Maximum number of function evaluations has been exceeded.

And the result is:

array([-524.92769674,  276.6657959 ,  185.98604937,  729.5822923 ])

Which is not the optimal.
My question is am I having this message and result because my starting points are not correct?

A:

Your function sm appears to be unbounded. As you increase x, sm will get ever more negative, hence the fact that it is going to -inf.
Re: comment - if you want to make sm() as close to zero as possible, modify the last line in your function definition to read return abs(sm).
This minimised the absolute value of the function, bringing it close to zero.
Result for your example:
>>> opt = minimize(sm,x0,args=(a,b),method='nelder-mead', options={'xtol': 1e-8,     'disp': True})
Optimization terminated successfully.
         Current function value: 0.000000
         Iterations: 153
         Function evaluations: 272
>>> opt
  status: 0
    nfev: 272
 success: True
     fun: 2.8573836630130245e-09
       x: array([-1.24676625,  0.65786454,  0.44383101,  1.73177358])
 message: 'Optimization terminated successfully.'
     nit: 153


Q:

Solve the linear system by Gaussian elimination

$\begin{cases}-2b+3c=1 \\ 3a+6b-3c=-2 \\ 6a+6b+3c=5\end{cases}$
I got an inconsistent linear system with the third row being 0 0 0 6.
May someone please verify if I am right? I looked it over.

A:

Your calculations are correct, since you end up with the last line of the matrix being 0 0 0 6 the last equation in the reduced matrix has no solution so the whole system has no solution


Q:

After issuing partial refund via PayPal RefundTransaction NVP API, IPN listener only shows payment status as "Refunded," not "Partially_Refunded"

When I issue a partial refund on my site using the RefundTransaction API operation, the refund is processed successfully. However, my IPN listener continually receives a payment status of just Refunded for this transaction. I am not sure why it isn't Partially_Refunded.
I have tested partial refunds with PayPal's IPN Simulator and my IPN listener returns Partially_Refunded every time during these tests.
Here's the beginning of my IPN listener file:
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
    $keyval = explode ('=', $keyval);
    if (count($keyval) == 2)
        $myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
   $get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
   if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
        $value = urlencode(stripslashes($value));
   } else {
        $value = urlencode($value);
   }
   $req .= "&$key=$value";
}

// STEP 2: POST IPN data back to PayPal to validate

$ch = curl_init($paypal_url);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));

// In wamp-like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set
// the directory path of the certificate as shown below:
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
    //mscampMail($my_email, 'MSCamp curl error', "Got " . curl_error($ch) . " when processing IPN data");
    curl_close($ch);
    exit;
}
curl_close($ch);

// STEP 3: Inspect IPN validation result and act accordingly

if (strcmp ($res, "VERIFIED") == 0) {
    // The IPN is verified, process it:
    // check whether the payment_status is Completed
    // check that txn_id has not been previously processed
    // check that receiver_email is your Primary PayPal email
    // check that payment_amount/payment_currency are correct
    // process the notification

    require_once ('includes/mysql_connect.php');

    // Get payment status & parent_txn_id if refund
    $payment_status = escape_data($_POST['payment_status']);

    // Cart Items
    $num_cart_items = isset($_POST['num_cart_items']) ? $_POST['num_cart_items'] : '';

    $txn_id = escape_data($_POST['txn_id']);
    $user_id = escape_data($_POST['custom']);
    $order_total = escape_data($_POST['mc_gross']);
    $shipping_fee = escape_data($_POST['mc_handling']);
    $first_name = escape_data($_POST['first_name']);
    $last_name = escape_data($_POST['last_name']);

    // For guest orders, need name & address info for shipping
    $guest = $user_id == 0 ? 'guest' : '';
    $address_street = escape_data($_POST['address_street']);
    $address_city = escape_data($_POST['address_city']);
    $address_state = escape_data($_POST['address_state']);
    $address_zip = escape_data($_POST['address_zip']);

And the function that posts partial refund data to PayPal:
function PPHttpPost($methodName_, $nvpStr_, $env) {
 global $live;
 // Set up your API credentials, PayPal end point, and API version.

 if("sandbox" === $env)
    $API_Endpoint = "https://api-3t.$env.paypal.com/nvp";
 else
    $API_Endpoint = "https://api-3t.paypal.com/nvp";

 $version = urlencode('122');

 // Set the curl parameters.
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
 curl_setopt($ch, CURLOPT_VERBOSE, 1);

 // Turn off the server and peer verification (TrustManager Concept).
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_POST, 1);

 // Set the API operation, version, and API signature in the request.
 $nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";

 // Set the request as a POST FIELD for curl.
 curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

 // Get response from the server.
 $httpResponse = curl_exec($ch);

 if(!$httpResponse) {
    exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
 }

 // Extract the response details.
 $httpResponseAr = explode("&", $httpResponse);

 $httpParsedResponseAr = array();
 foreach ($httpResponseAr as $i => $value) {
     $tmpAr = explode("=", $value);
     if(sizeof($tmpAr) > 1) {
        $httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
     }
 }

 if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
    exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
 }

 return $httpParsedResponseAr;
}

And finally, code from the page that calls the function above when a user initiates the partial refund:
if ($live === false) $env = "sandbox";

// Set request-specific fields.
$item = urlencode($refund_detail['item']);
$amount = urlencode($refund_detail['cost']);
$inventory_num = urlencode($order_detail_id_for_refund);
$transactionID = urlencode($refund_detail['paypal_txn_id']);
$refundType = urlencode('Partial');     // or 'Partial'
$memo = urlencode("Refund of ".$refund_detail['item']);     // required if Partial.
$currencyID = urlencode('USD');         // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')

// Add request-specific fields to the request string.
$nvpStr = "&L_INVOICEITEMNAME0=$item&L_SKU0=$inventory_num&TRANSACTIONID=$transactionID&REFUNDTYPE=$refundType&CURRENCYCODE=$currencyID";

if(isset($memo)) {
    $nvpStr .= "&NOTE=$memo";
}

if(strcasecmp($refundType, 'Partial') == 0) {
    if(!isset($amount)) {
        exit('Partial Refund Amount is not specified.');
    } else {
        $nvpStr = $nvpStr."&AMT=$amount";
    }

    if(!isset($memo)) {
        exit('Partial Refund Memo is not specified.');
    }
}

Any advice or nudge in the right direction would be greatly appreciated as my client needs to be able to process partial refunds on the site. I've scoured Stackoverflow and Google for more information to no avail. Thanks.

A:

Mike,
The payment_status = Refunded txn will have a parent_txn_id field with the value of the transaction that was "partially" refunded.
Assuming you have stored that original payment in your database, the IPN listener can look up the original transaction and compare mc_gross from that record with the same field in the current IPN txn.  If different, it is "partial" refund.


Q:

passing argument by using CallNonvirtualVoidMethod

I have a JNI function calling an instance method within an Android activity. I am using CallNonvirtualVoidMethod. Like this:
jarray buffer = (*env)->NewByteArray(env, len);
void* pBuffer = (*env)->GetPrimitiveArrayCritical(env, buffer, NULL);
// ... load data to buffer via pBuffer
(*env)->ReleasePrimitiveArrayCritical(env, buffer, pBuffer, 0);
(*env)->CallNonvirtualVoidMethod(env, o, c, m); // associate m with java method name 'mMethod' somewhere
(*env)->DeleteLocalRef(env, buffer);

If no argument passed (like above nothing after 'm'), everything works. But if with argument (even only one single integer like: (*env)->CallNonvirtualVoidMethod(env, o, c, m, msg);), the activity seems not receiving them properly (but I am sure it is called). Like this:
public void mMethod(int msg) {
    Log.i("aaa", "I am here"); <----------------successfully printed in logcat
    Log.i("aaa", "I hate: " + msg);<------------not got printed
}

I am using ndk-r8-crystax. Anyone can help me out? Thanks.

A:

Problem is gone when I call another class rather than any activity. Guess the reason is an activity cannot be communicated with primitives/references as arguments.


Q:

Возможна ли прямая работа по FTP в PhpStorm

Возможно ли на PhpStorm редактировать проекты прямо на стороне сервера, не закачивая их на локальный сервер?
Хочу перейти на какую-то толковую IDE, где можно это делать.

A:

Так делать нельзя.
Нельзя ни при каких условиях залезать грязными ручонками на рабочий сервер.
Даже если надо подправить одну строчку.
Даже если один символ.
НЕЛЬЗЯ.
PHPStorm так не умеет. Пока. Возможно, потому что это толковая IDE.
Но если вам очень хочется — курите WebStorm 10 EAP. Навыпрашивались.

A:

Это стало возможно в новом PhpStorm 9

Удаленная разработка
В версии 9 добавлена одна из самых востребованных функций в истории
PhpStorm — удаленное редактирование (Remote Edit). Открывайте
одиночные файлы напрямую с удаленного сервера (FTP, SFTP, FTPS и т.
д.) и редактируйте их в IDE без сохранения/загрузки в локальный
проект.
Чтобы начать редактирование файла с удаленного сервера, просто
выберите Edit Remote File в контекстном меню или дважды щелкните файл.

Кроме все прочего появилась возможность сравнивать текущую версию файла с последней загруженной.
Есть еще видео "Что нового в PHPStorm 9?" на английском языке, демонстрирующее использование новой возможности.
p.s. всегда делайте бэкапы, не надейтесь на "авось".


Q:

Is there any difference between these two JVM settings in Eclipse?

1) Click Window->Preferences->Java->Installed JREs->JDK1.8->Edit->Default VM options
and
2) Click Run->Run Configurations->Java Application->VM options.
If I set -Xmx=6G. Is there any difference between these two options in setting the RAM to be used by my application?

A:

-the first 1 makes all the new Java projects using the selected Jre ect.. and iit affect the running settings if they are per default.
-but if you use directly the second method ,it will only affect the running not the creation of the next projects.
and if you've noticed , when u do (2nd methode):
Run->Run Configurations->Java Application->VM options

you can choose the default environnement selected by the first method.


Q:

Print the relative path

Description
Given a source path and a destination path, output the relative path to the destination with respect to the source.
Rules

The input can come from stdin or as arguments to the program/function.
Both Windows and Unix style paths must be supported.
The output path can use / and/or \ for the path separator (your choice and combination of both is OK).
You can assume a relative path is possible.
The use of external programs, built-in or library functions made for computing relative paths is prohibited (e.g. Python's os.path.relpath)
This is code-golf
Edit: New rule from comments.
The relative path must be the shortest relative path possible.
Assume the destination path is different from the source path.

Example 1
# In
/usr/share/geany/colorschemes
/usr/share/vim/vim73/ftplugin

# Out
../../vim/vim73/ftplugin

Example 2
# In
C:\Windows\System32\drivers
C:\Windows\System32\WindowsPowerShell\v1.0

# Out
..\WindowsPowerShell\v1.0

A:

CJam, 46 bytes
ll]{'\/'/f/:~}/W{)__3$=4$@==}g@,1$-"../"*o>'/*

Try it online.
Examples
$ echo '/usr/share/geany/colorschemes
> /usr/share/vim/vim73/ftplugin' | cjam path.cjam; echo
../../vim/vim73/ftplugin
$ echo 'C:\Windows\System32\drivers
> C:\Windows\System32\WindowsPowerShell\v1.0' | cjam path.cjam; echo
../WindowsPowerShell/v1.0

How it works
ll]         " Read two lines from STDIN and wrap them in an array.                       ";
{           " For each line:                                                             ";
  '\/       " Split by “\”.                                                              ";
  '/f/      " Split each chunk by “/”.                                                   ";
  :~        " Flatten the array of chunks.                                               ";
}/          "                                                                            ";
W           " Push -1 (accumulator).                                                     ";
{           "                                                                            ";
  )__       " Increment and duplicate twice.                                             ";
  3$=       " Extract the corresponding chunk from the first line.                       ";
  4$@=      " Extract the corresponding chunk from the second line.                      ";
  =         " If the are equal,                                                          ";
}g          " repeat the loop.                                                           ";
@,          " Rotate the array of chunks of the first line on top and get its length.    ";
1$-         " Subtract the value of the accumulator.                                     ";
"../"*o     " Print the string “../” repeated that many times.                           ";
>           " Remove all chunks with index less than the accumulator of the second line. ";
'/*         " Join the chunks with “/”.                                                  ";


Q:

Right-skewd or power law distribution

Is a power law distribution right skewed?
Is there any relation between concepts of right skewness and power law distribution?

A:

No, the student-t distribution is a power law distribution and it is always symmetric. The same goes for the Cauchy distribution.


Q:

Implementing "includes" when parsing in Attoparsec

I am writing a DSL for fun. I decided to use attoparsec because I was familiar with it.
I want to implement parsing of includes with relative filenames like this:
include /some/dir/file.ext

or URLs:
include http://blah.com/my/file.ext

So when I'm parsing I expect to read the referenced resource and parse the entire thing, appending its contents to the "outer" parsing state.
The problem is that although the parsing of these statements is easy, I can't run IO (as I understand it) within my Attoparsec parsers.
How do I use Attoparsec to achieve this? Do I chop the initial input up using some string filtering and then parse each "block" into parse and feed accordingly? Essentially a two-pass parse approach?

A:

Attoparsec is pure (Data.Attoparsec.Internal.Types.Parser is not a transformer and doesn’t include IO) so you’re right that you can’t expand includes from within a parser directly.
Splitting the parser into two passes seems like the right approach: one pass acts like the C preprocessor, accepting a file with include statements interleaved with other stuff. The “other stuff” only needs to be basically lexically valid, not your full parser—just like the C preprocessor only cares about tokens and matching parentheses, not matching other brackets or anything semantic. You then replace the includes, producing a fully expanded file that you can give to your existing parser.
If an included file must be syntactically “standalone” in some sense†, then you can parse a whole file first, interleaved with includes, then replace them. For instance:
-- Whatever items you’re parsing.
data Item

-- A reference to an included path.
data Include = Include FilePath

parse :: Parser [Either Include Item]

-- Substitute includes; also calls ‘parse’
-- recursively until no includes remain.
substituteIncludes :: [Either Include Item] -> IO [Item]

† Say, if you’re just using attoparsec for lexing tokens that can’t cross file boundaries anyway, or you’re doing full parsing but want to disallow an include file that contains e.g. unmatched brackets.

The other option is to embed IO in your parser directly by using a different parsing library such as megaparsec, which provides a ParsecT transformer that you can wrap around IO to do IO directly in your parser. I would probably do this for a prototype, but it seems tidier to separate the concerns of parsing and expansion as much as possible.


Q:

How to simplify an expression?

I have two similar expressions. The first expression can be simplified
$3125\ 2^{\frac{1}{2} \left(\sqrt{29}+5\right)} \left(7-\sqrt{29}\right)^{\frac{1}{2} \left(\sqrt{29}-7\right)} \left(\sqrt{29}-5\right)^{\frac{5}{2}-\frac{\sqrt{29}}{2}} \left(\sqrt{29}+3\right)^{-\frac{\sqrt{29}}{2}-\frac{3}{2}}$
FullSimplify[3125 * 2^((1/2) * (5 + Sqrt[29])) * (7 - Sqrt[29])^((1/2)*(-7 + Sqrt[29])) * (-5 + Sqrt[29])^(5/2 - Sqrt[29]/2) * (3 + Sqrt[29])^(-(3/2) - Sqrt[29]/2)]

(* 131 - 22 Sqrt[29] *)

but the second expression not
$27\ 2^{\frac{1}{2} \left(\sqrt{13}+3\right)} \left(5-\sqrt{13}\right)^{\frac{1}{2} \left(\sqrt{13}-5\right)} \left(\sqrt{13}+1\right)^{\frac{1}{2} \left(-\sqrt{13}-1\right)} \left(\sqrt{13}-3\right)^{\frac{3}{2}-\frac{\sqrt{13}}{2}}$
FullSimplify[27 2^(1/2 (3 + Sqrt[13])) (5 - Sqrt[13])^(1/2 (-5 + Sqrt[13])) (1 + Sqrt[13])^(1/2 (-1 - Sqrt[13])) (-3 + Sqrt[13])^(3/2 - Sqrt[13]/2)]

(* 27 2^(1/2 (3 + Sqrt[13])) (5 - Sqrt[13])^(1/2 (-5 + Sqrt[13])) (-3 + Sqrt[13])^(3/2 - Sqrt[13]/2) (1 + Sqrt[13])^(1/2 (-1 - Sqrt[13])) *)

Why ?
The requested result is
(* 1/2 (11 + Sqrt[13]) *)

The numerical check is OK:
N[ 27 2^(1/2 (3 + Sqrt[13])) (5 - Sqrt[13])^(1/2 (-5 + Sqrt[13])) (1 + Sqrt[13])^(1/2 (-1 - Sqrt[13])) (-3 + Sqrt[13])^(3/2 - Sqrt[13]/2), 50]
N[1/2 (11 + Sqrt[13]), 50]

(* 7.3027756377319946465596106337352479731256482869226 *)
(* 7.3027756377319946465596106337352479731256482869226 *)

A:

expr = 27 2^(1/2 (3 + Sqrt[13])) (5 -
      Sqrt[13])^(1/2 (-5 + Sqrt[13])) (1 +
      Sqrt[13])^(1/2 (-1 - Sqrt[13])) (-3 + Sqrt[13])^(3/2 -
      Sqrt[13]/2);

Use ExpToTrig
expr2 = expr // ExpToTrig // FullSimplify

(* (1/2)*(11 + Sqrt[13]) *)

expr == expr2 // FullSimplify

(* True *)


Q:

Can I program my Pi to keep track of its own power usage?

I'm doing a university project using a raspberry pi 3 using , and I'm essentially making a time lapse camera. I have the camera module, and I've managed to take some pictures, but it would be good for my project if I could also get an idea of how much energy my project was using for my report. Does anyone know if the Pi has the hardware necessary to do that or a library I could reference?
When I tried to look it up myself, I saw mainly projects of using the Pi to track some other device's power usage. I could totally design a circuit that would allow me to measure voltage and current draw, but I'd rather not if the Pi is capable of doing so on its own. I know that most laptops do have a utility for it buried somewhere in the OS, and I'd rather not reinvent the wheel if I can avoid it. Thanks!

A:

While the Pi can't do this on its own, a number of sensors can.
The INA219 claims to be able to record Amps. You could modify your PI PSU with this device, and then wire the data back to the pi. It should be then trivial to read the current useage with a bash script.
Unfortunatly, I don't have an exact build for you to follow, but there will be examples on how to use this.


Q:

UML for multithreading dataflow

I want to paint a diagram where you can see the dataflow of a java program, and if there are one or multiple threads handling the data.
Sequence charts don't show multithreading and get very confusion when you have more than 5 different entities.
Class diagrams are good for showing the relations but the dataflow is missing.
I would like to paint boxes (like class/package diagram) and connect them. Maybe having a box doubled and ... in between to show that there can be more than one thread.
What diagram does UML have for this kind of dataflow diagram?
What editor is good for that diagram? If possible freeware or open source.

A:

I would look at athe UML activity diagram for showing multiple threads and their parallel execution.  On communication diagrams, you also sometimes see thread letters (e.g. A,B,C) to try and denote concurrent threads, but I almost always find this confusing.  There are fragments in UML 2 which may help show concurrency in sequence diagrams, but I always find this cumbersome and the diagrams hard to refactor (which means they quickly go out of date).
If the threads are executing the same tasks, but running in parallel, you could just add a Note to your diagram to explain this.  This way you could concentrate on modelling a single thread accurately and cleanly.
With regard to which tool to use most IDEs will have some degree of UML modelling tool included e.g. I am happy to use the EMF based tools which ship with Eclipse.

A:

Sequence diagrams do have notation for both parallel operations and asynchronous calls and would be an appropriate means of showing your dataflow.

A:

Depends on the problem, but I'd probably go with an activity diagram to describe the sequence of events:
http://www.agilemodeling.com/style/activityDiagram.htm
Then maybe a set of sequence diagrams to capture the class-level interactions for each of those steps.
Alternatively, you could look at describing the sequence serially (think iterating an array in a loop) and just note that the iteration should be parallelised in implementation.


Q:

matplotlib barplot spacing does not work properly

I am using matplotlib and pandas DataFrame to draw a barplot as follows:
pdata = pd.DataFrame([[11.14285714,  6.33333333,  2.52380952],
       [10.47619048,  6.61904762,  2.9047619 ],
       [10.80952381,  6.19047619,  3.        ],
       [11.0952381 ,  6.66666667,  2.23809524],
       [10.14285714,  4.9047619 ,  4.95238095],
       [ 9.61904762,  5.71428571,  4.66666667],
       [10.0952381 ,  5.14285714,  4.76190476],
       [ 9.47619048,  5.14285714,  5.38095238],
       [10.66666667,  4.38095238,  4.95238095],
       [ 9.66666667,  5.04761905,  5.28571429],
       [10.33333333,  4.95238095,  4.71428571],
       [10.85714286,  4.9047619 ,  4.23809524],
       [ 9.71428571,  4.9047619 ,  5.38095238],
       [10.71428571,  4.52380952,  4.76190476],
       [ 9.57142857,  3.71428571,  6.71428571],
       [11.61904762,  5.47619048,  2.9047619 ],
       [12.23809524,  5.23809524,  2.52380952],
       [11.28571429,  7.28571429,  1.42857143],
       [10.52380952,  6.52380952,  2.95238095],
       [10.80952381,  6.38095238,  2.80952381],
       [10.95238095,  7.71428571,  1.33333333],
       [11.0952381 ,  7.42857143,  1.47619048],
       [10.0952381 ,  8.71428571,  1.19047619],
       [10.42857143,  8.42857143,  1.14285714],
       [10.57142857,  7.95238095,  1.47619048],
       [10.14285714,  8.66666667,  1.19047619],
       [ 9.38095238,  9.38095238,  1.23809524],
       [ 8.9047619 ,  9.80952381,  1.28571429],
       [10.66666667,  8.04761905,  1.28571429],
       [ 9.19047619,  9.19047619,  1.61904762]])
pdata.index = np.arange(30)+1

fig,axes = plt.subplots(1,2,figsize=(6,3),sharey=True)
ax = axes[0]
pdata[pdata.index<=15].plot(
    ax=ax,kind='bar',stacked=True,width=.95, color=colors,alpha=.7, rot=0)

ax = axes[1]
pdata[pdata.index>15].plot(
    ax=ax,kind='bar',stacked=True, color=colors,width=.95,alpha=.7, rot=0)
ax.get_legend().remove()
ax.set_ylim([0,20])
fig.tight_layout()

However, the resulting figure looks like the following, with different spacings between bars:

Is there a way to correct the spacings? Also, is it possible to further reduce the distance between the two plots?

A:

What you are seeing is a combination of two effects, the width attribute being set to 0.95 and the dpi being too low to resolve every whitespace between bars. If you want some whitespace but between every bar you can simply increase the dpi of the figure, as suggested by the comments and as in this answer,
fig,axes = plt.subplots(1,2,figsize=(6,3),sharey=True, dpi=300)

will set the dpi of the figure to 300 and produce something like

Where the inter-bar whitespace is created by width=0.95, if you want no space at all between bars simply set width=1.0 to produce

Note that in both cases I used plt.subplots_adjust(wspace=0.05) instead of fig.tight_layout() but this is a matter of preference. Furthermore, note that if you use width=1.0 you need not adjust the dpi attribute, as the display will be correct:

 Complete example
import pandas as pd
import matplotlib.pyplot as plt
pdata = pd.DataFrame([[11.14285714,  6.33333333,  2.52380952],
       [10.47619048,  6.61904762,  2.9047619 ],
       [10.80952381,  6.19047619,  3.        ],
       [11.0952381 ,  6.66666667,  2.23809524],
       [10.14285714,  4.9047619 ,  4.95238095],
       [ 9.61904762,  5.71428571,  4.66666667],
       [10.0952381 ,  5.14285714,  4.76190476],
       [ 9.47619048,  5.14285714,  5.38095238],
       [10.66666667,  4.38095238,  4.95238095],
       [ 9.66666667,  5.04761905,  5.28571429],
       [10.33333333,  4.95238095,  4.71428571],
       [10.85714286,  4.9047619 ,  4.23809524],
       [ 9.71428571,  4.9047619 ,  5.38095238],
       [10.71428571,  4.52380952,  4.76190476],
       [ 9.57142857,  3.71428571,  6.71428571],
       [11.61904762,  5.47619048,  2.9047619 ],
       [12.23809524,  5.23809524,  2.52380952],
       [11.28571429,  7.28571429,  1.42857143],
       [10.52380952,  6.52380952,  2.95238095],
       [10.80952381,  6.38095238,  2.80952381],
       [10.95238095,  7.71428571,  1.33333333],
       [11.0952381 ,  7.42857143,  1.47619048],
       [10.0952381 ,  8.71428571,  1.19047619],
       [10.42857143,  8.42857143,  1.14285714],
       [10.57142857,  7.95238095,  1.47619048],
       [10.14285714,  8.66666667,  1.19047619],
       [ 9.38095238,  9.38095238,  1.23809524],
       [ 8.9047619 ,  9.80952381,  1.28571429],
       [10.66666667,  8.04761905,  1.28571429],
       [ 9.19047619,  9.19047619,  1.61904762]])
pdata.index = np.arange(30)+1

# With spacing between bars
fig,axes = plt.subplots(1,2,figsize=(6,3),sharey=True, dpi=300)
plt.subplots_adjust(wspace=0.05)
ax = axes[0]
colors = list()
pdata[pdata.index<=15].plot(
    ax=ax,kind='bar',stacked=True,width=0.95 ,alpha=.7, rot=0)

ax = axes[1]
pdata[pdata.index>15].plot(
    ax=ax,kind='bar',stacked=True, width=0.95,alpha=.7, rot=0)
ax.get_legend().remove()
ax.set_ylim([0,20])
plt.show()

# Without any spacing between bars
fig,axes = plt.subplots(1,2,figsize=(6,3),sharey=True, dpi=300)
plt.subplots_adjust(wspace=0.05)
ax = axes[0]
colors = list()
pdata[pdata.index<=15].plot(
    ax=ax,kind='bar',stacked=True,width=1 ,alpha=.7, rot=0)

ax = axes[1]
pdata[pdata.index>15].plot(
    ax=ax,kind='bar',stacked=True, width=1,alpha=.7, rot=0)
ax.get_legend().remove()
ax.set_ylim([0,20])
plt.show()


Q:

NHibernate's ISQLQuery returns instances that are of an unexpected type

I'm using NHibernate 2.1.2.400, and I'm having an issue with a an ISQLQuery query.
The reason why I use an ISQLQuery here, is that this query uses a table for which I have no entity mapped in NHibernate.
The query looks like this:
ISQLQuery query = session.CreateSQLQuery (
    "select p.*, price.* " +
    "from prestation p left outer join prestationprice price on p.PrestationId = price.PrestationId " +
    "where p.Id IN ( select id from prestationregistry where ...");

'Prestationregistry' is the table that is not known by NHibernate (unmapped, so therefore the native SQL Query).
my code continues like this:
query.AddEntity ("p", typeof(Prestation));
query.AddJoin ("price", typeof(PrestationPrice));

query.SetResultTransformer (Transformers.DistinctRootEntity);

var result = query.List();

So far so good.
I expect that I'm given a list of 'Prestation' instances as a result of this query, since I declared 'Prestation' as being the root-object that has to be returned by the AddEntity method.
I also expect that the PrestationPrices for each Prestation are eagerly loaded by this query (hence the AddJoin method).
To my surprise, the List() method returns a collection of PrestationPrice instances instead of Prestation instances.
How come ?  Am I doing something wrong ?  And if so, could you be so kind to tell me what I'm doing wrong ?
Edit: Additional Info:
When I debug, and put a watch on the 'query' instance, I can see that the queryReturns member of the query contains 2 items:
- one NativeSqlQueryRootReturn instance who'se ReturnEntityName is 'Prestation'
- one NativeSqlQueryJoinReturn
When I do not specify the 'DistinctRootEntity' result transformer, the query returns instances of 'Prestation' instead of PrestationPrice.  However, it contains multiple copies of the same instance.

A:

I'm not sure this is the real cause of your problem, but you must enclose SQL aliases in braces, e.g.
select {p.*}, {price.*}
from prestation p
left outer join prestationprice price on p.PrestationId = price.PrestationId
where p.Id IN ( select id from prestationregistry where ...


Q:

Java Beginner Assignment

I am new to Java, and I am trying to make a program for the user to enter a certain number of integers and then retrieve those integers and print them back.
This works only if you input 1 integer. Otherwise, it terminates.
import java.util.Scanner;
public class Assignment4 {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the Number of Numbers");
        int totalNumbers = scan.nextInt();
        int[] numbers = new int[totalNumbers];
        for(int i = 0;i == (totalNumbers-1); i++){
            System.out.println("Enter the Next Number");
            numbers[i] = scan.nextInt();
        }

        for(int i = 0;i == (totalNumbers-1); i++){
            System.out.println(numbers[i]);
        }

    }
}

A:

Your loop condition is your problem. It will only accept one input. The condition:
for(int i = 0; i == (totalNumbers-1); i++){

Will terminate when i != (totalNumbers - 1). Your for loop should be read like the following:

Initialize a new variable i to zero, then while i is equal to
  "totalNumbers - 1", do the following block of code, then increment i
  by 1

You probably want:
for(int i = 0; i <= (totalNumbers-1); i++){

Which can be read as:

Initialize a new variable i to zero, then while i is LESS THAN or equal to
  "totalNumbers - 1", do the following block of code, then increment i
  by 1


Q:

JavaScript performance of || operator to instantiate a variable

Just a quick question that I can't seem to find a reliable source for. I always use the || operator for shorthand undefined checks, like
myVar = myVar || {};

But I'm wondering if this means it will reassign myVar if it exists? And hence if it would be better, from a performance point of view, to expand this to an if statement as such:
if(!myVar) myVar = {};

Many thanks in advance for clearing this up!

A:

I cannot imagine that you would run this more than a few times at runtime. It will never be a problem.
If this is in hot function then you are screwed anyway because implicit/optional stuff is intuitively very bad. I cannot imagine you have a hot function that needs to do this. You are probably establishing classes or modules - you could run a loop for 100000 times additionally and not notice anything.


Q:

How to validate a Text with Jface Dialog?

i created a Dialog with two input fields with the following Code.
 public class CCIDDialog extends TitleAreaDialog {

 private Text ccidText;
 private Text descriptionText;
 private String CCID;
 private String description;

 public CCIDDialog(Shell parentShell) {
  super(parentShell);
 }

public void create() {
    super.create();
    setTitle(_title);
    setMessage("Bitte geben Sie die CCID "+firstchar+"xxxxxxx und eine Beschreibung ein (max. 7-stellig): ", IMessageProvider.INFORMATION);   }

 @Override
  protected Control createDialogArea(Composite parent) {
    Composite area = (Composite) super.createDialogArea(parent);
    Composite container = new Composite(area, SWT.NONE);
    container.setLayoutData(new GridData(GridData.FILL_BOTH));
    GridLayout layout = new GridLayout(2, false);
    container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    container.setLayout(layout);

    createCCID(container);
    createDescription(container);

    return area;
  }

  private void createCCID(Composite container) {
    Label lbtFirstName = new Label(container, SWT.NONE);
    lbtFirstName.setText("CCID (ohne "+firstchar+"): ");

    GridData dataCCID = new GridData();
    dataCCID.grabExcessHorizontalSpace = true;
    dataCCID.horizontalAlignment = GridData.FILL;

    ccidText = new Text(container, SWT.BORDER);

    ccidText.setLayoutData(dataCCID);
  }

  private void createDescription(Composite container) {
    Label lbtLastName = new Label(container, SWT.NONE);
    lbtLastName.setText("Beschreibung: ");

    GridData dataDescription = new GridData();
    dataDescription.grabExcessHorizontalSpace = true;
    dataDescription.horizontalAlignment = GridData.FILL;
    descriptionText = new Text(container, SWT.BORDER);
    descriptionText.setLayoutData(dataDescription);
  }

  @Override
  protected boolean isResizable() {
    return true;
  }

  // save content of the Text fields because they get disposed
  // as soon as the Dialog closes
  private void saveInput() {
      CCID = ccidText.getText();
      description = descriptionText.getText();

  }

  @Override
  protected void okPressed() {
    saveInput();
    super.okPressed();
  }

  public String getCCID() {
    return CCID;
  }

  public String getDescription() {
    return description;
  }
}

Is there a way to validate the ccidtext?
If the user type more then 7 chars, he must get a notification and should not be able to continue the dialog. I read so lot at the internet but can`t find a solution for this problem.
Thank u so much for your help.
JonasInt

A:

You can use Text.addModifyListener to add a ModifyListener which will be called each time the text is changed. You can also use Text.addVerifyListener to add VerifyListener which can actually prevent text being entered.
For TitleAreaDialog you can call setMessage or setErrorMessage to display a message in the title area.
You can disable the OK button on the dialog using:
getButton(IDialogConstants.OK_ID).setEnabled(false);

Note: getButton(xxx) can return null if you call it too early in the dialog construction. Buttons are created during the createContents method after the createDialogArea method has been called.
So you can access the buttons by overriding createContents like this:
@Override
protected Control createContents(final Composite parent)
{
  Control control = super.createContents(parent);

  // TODO access buttons here

  return control;
}


Q:

How to execute script during image build in Docker

I have the following at the end of my Dockerfile:
ENTRYPOINT bash -C '/usr/local/bin/setup_php_settings';'bash'

If I am not wrong that /usr/local/bin/setup_php_settings will be executed each time the container is started. If so then I have a few installation stuff (like this ZRay for example) inside that script that I would like to move to another script that would be executed just once on image build process let's say.
The content of the setup_php_settings (whithout the ZRay part) is the following:
#!/bin/bash -x
set -e

PHP_ERROR_REPORTING=${PHP_ERROR_REPORTING:-"E_ALL & ~E_DEPRECATED & ~E_NOTICE"}
sed -ri 's/^display_errors\s*=\s*Off/display_errors = On/g' /etc/php5/apache2/php.ini
sed -ri 's/^display_errors\s*=\s*Off/display_errors = On/g' /etc/php5/cli/php.ini
sed -ri "s/^error_reporting\s*=.*$//g" /etc/php5/apache2/php.ini
sed -ri "s/^error_reporting\s*=.*$//g" /etc/php5/cli/php.ini
echo "error_reporting = $PHP_ERROR_REPORTING" >> /etc/php5/apache2/php.ini
echo "error_reporting = $PHP_ERROR_REPORTING" >> /etc/php5/cli/php.ini

mkdir -p /data/tmp/php/uploads
mkdir -p /data/tmp/php/sessions
mkdir -p /data/tmp/php/xdebug
chown -R www-data:www-data /data/tmp/php*

ln -sf /etc/php5/mods-available/zz-php.ini /etc/php5/apache2/conf.d/zz-php.ini
ln -sf /etc/php5/mods-available/zz-php-directories.ini /etc/php5/apache2/conf.d/zz-php-directories.ini
ln -sf /usr/share/php/libzend-framework-php/Zend/ /usr/share/php/Zend
a2enmod rewrite
php5enmod mcrypt

# Apache gets grumpy about PID pre-existing files
: "${APACHE_PID_FILE:=${APACHE_RUN_DIR:=/var/run/apache2}/apache2.pid}"
rm -f "$APACHE_PID_FILE"

source /etc/apache2/envvars && exec /usr/sbin/apache2 -DFOREGROUND "$@"

The question is, how do I execute such new script during image build? Using CMD? Any other workaround?

A:

The correct directive for this is RUN. This would run the script on image build. in your case -
RUN /usr/local/bin/setup_php_settings
CMD bash


Q:

Thread order execution?

I have this simple code  : (which i run in linqpad)
void Main()
{
    for ( int  i=0;i<10;i++)
     {
      int  tmp=i;
      new Thread (() =>doWork(tmp)).Start();
     }
}

 public void doWork( int h)
 {
 h.Dump();
 }

the int  tmp=i; line is for capture variable  - so each iteration will have its own value.
2 problems :
1) the numbers are not sequential , while thread execution is !
2) sometimes i get less than 10 numbers !
here are some executions outputs:

questions :
1) why case 1 is happening and how can i solve it ?
2) why case 2 is happening and how can i solve it ?

A:

It should not be expected that they are sequential. Each thread gets priority as the kernel chooses. It might happen that they look sequential, purely by the nature of when each is started, but that is pure chance.
For ensuring that they all complete - mark each new thread as IsBackground = false, so that it keeps the executable alive. For example:
new Thread(() => doWork(tmp)) { IsBackground = false }.Start();


Q:

Simple route not working laravel

Hello people here is my code below for laravel routes.php
            Route::get('/', function()
    {
        return View::make('index');
    });

    Route::get('bid', function()
    {
      return View::make('bid');
    });

this works fine for http://localhost/supadmin/public/ but does not work for http://localhost/supadmin/public/bid ,, what could be the problem?? Iam getting an error The requested URL /supadmin/public/bid was not found on this server. i have also configured .htaccess to
Options +FollowSymLinks
        RewriteEngine On

        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.php [L]

It works fine like this http://localhost/supadmin/public/index.php/bid but iam expecting it to work http://localhost/supadmin/public/bid
php artisan routes shows
+--------+--------------------------+-------------+---------+----------------+---------------+
| Domain | URI                      | Name        | Action  | Before Filters | After Filters |
+--------+--------------------------+-------------+---------+----------------+---------------+
|        | GET|HEAD /               |             | Closure |                |               |
|        | GET|HEAD bid             |             | Closure |                |               |
|        | GET|HEAD bid_history     | bid_history | Closure |                |

A:

You need to put /bid
Route::get('/bid', function()
    {
      return View::make('bid');
});

Please make sure routes are registered by using php artisan routes
and try it serving through php artisan serve
Edit
You should also try checking your apache setting
add the following code to /etc/apache2/sites-available/default
AllowOverride All

Restart apache


Q:

Formatting a text file and exporting a text file

I have a Range of data in text file like 102201906000-102201911999-23451 around thousands. i want to create a new text file to create the range into numbers like.
102201906000 23451
102201906001 23451
102201906002 23451

till
102201911999 23451

Keeping the last digit as fixed.
I have made following code.
Private Sub CommandButton21_Click()
    Application.ScreenUpdating = False
    Dim LastRow As Long
    LastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    Dim lCol As Long
    Dim rngEnd As String
    Dim rng1 As String
    Dim rng2 As String
    Dim x As Long
    Dim Num As Range
    For Each Num In Range("A1:A" & LastRow)
        lCol = ActiveSheet.UsedRange.Columns.Count
        rngEnd = Split(Num, "-")(2)
        rng1 = Split(Num, "-")(0) - 1
        rng2 = Split(Num, "-")(1)
        For x = 1 To rng2 - rng1
            Cells(x, lCol + 1) = rng1 + x & " " & rngEnd
        Next x
    Next Num
    Application.ScreenUpdating = True
End Sub

But as i have huge data i am unable to use it properly.
Can i get some help on to create a text file itself when i run a macro without using the spreadsheet.
Waiting for expert advises.

A:

Assuming that you have a text file and want to create another textfile where each line like 102201906000-102201911999-23451 is replaced by a number of lines like  102201906000 23451 it is more natural to use VBScript than straight VBA. You can bypass the need to pull the data into Excel (but -- it is written as an Excel macro so you need to call it from Excel. With minor modification you can remove Excel from the loop completely and use pure VBScript).
To use it you have to include a reference to Microsoft Scripting Runtime to your projects (Tools/References in the VBA editor).
Sub ExpandData(inName As String, outName As String)
    Dim FSO As New FileSystemObject
    Dim tsIn As TextStream
    Dim tsOut As TextStream
    Dim startNum, endNum, i, line 'variants

    On Error GoTo err_handler

    Set tsIn = FSO.OpenTextFile(inName, ForReading)
    Set tsOut = FSO.OpenTextFile(outName, ForWriting, True)

    Do While tsIn.AtEndOfStream = False
        line = Split(tsIn.ReadLine, "-")
        If UBound(line) = 2 Then
            startNum = CDec(line(0))
            endNum = CDec(line(1))
            For i = startNum To endNum
                tsOut.WriteLine i & " " & line(2)
            Next i
        End If
    Loop
    tsIn.Close
    tsOut.Close
    Exit Sub
err_handler:
    Debug.Print "I'm confused!"
End Sub

Used like thus (inName must be different from outName):
Sub test()
    ExpandData "C:\Programs\test.txt", "C:\Programs\testout.txt"
End Sub


Q:

How does a mutex lock and unlock functions prevents CPU reordering?

As far as I know, a function call acts as a compiler barrier, but not as a CPU barrier.
This tutorial says the following:

acquiring a lock implies acquire semantics, while releasing a lock
  implies release semantics! All the memory operations in between are
  contained inside a nice little barrier sandwich, preventing any
  undesireable memory reordering across the boundaries.

I assume that the above quote is talking about CPU reordering and not about compiler reordering.
But I don't understand how does a mutex lock and unlock causes the CPU to give these functions acquire and release semantics.
For example, if we have the following C code:
pthread_mutex_lock(&lock);
i = 10;
j = 20;
pthread_mutex_unlock(&lock);

The above C code is translated into the following (pseudo) assembly instructions:
push the address of lock into the stack
call pthread_mutex_lock()
mov 10 into i
mov 20 into j
push the address of lock into the stack
call pthread_mutex_unlock()

Now what prevents the CPU from reordering mov 10 into i and mov 20 into j  to above call pthread_mutex_lock() or to below call pthread_mutex_unlock()?
If it is the call instruction that prevents the CPU from doing the reordering, then why is the tutorial I quoted makes it seem like it is the mutex lock and unlock functions that prevents the CPU reordering, why the tutorial I quoted didn't say that any function call will prevent the CPU reordering?
My question is about the x86 architecture.

A:

If i and j are local variables, nothing.  The compiler can keep them in registers across the function call if it can prove that nothing outside the current function have their address.
But any global variables, or locals whose address might be stored in a global, do have to be "in sync" in memory for a non-inline function call.  The compiler has to assume that any function call it can't inline modifies any / every variable it can possibly have a reference to.
So for example, if int i; is a local variable, after sscanf("0", "%d", &i); its address will have escaped the function and the compiler will then have to spill/reload it around function calls instead of keeping it in a call-preserved register.
See my answer on Understanding volatile asm vs volatile variable, with an example of asm volatile("":::"memory") being a barrier for a local variable whose address escaped the function (sscanf("0", "%d", &i);), but not for locals that are still purely local.  It's exactly the same behaviour for exactly the same reason.

I assume that the above quote is talking about CPU reordering and not about compiler reordering.

It's talking about both, because both are necessary for correctness.
This is why the compiler can't reorder updates to shared variables with any function call.  (This is very important: the weak C11 memory model allows lots of compile-time reordering.  The strong x86 memory model only allows StoreLoad reordering, and local store-forwarding.)
pthread_mutex_lock being a non-inline function call takes care of compile-time reordering, and the fact that it does a locked operation, an atomic RMW, also means it includes a full runtime memory barrier on x86.  (Not the call instruction itself, though, just the code in the function body.)  This gives it acquire semantics.
Unlocking a spinlock only needs a release-store, not a RMW, so depending on the implementation details the unlock function might not be a StoreLoad barrier.  (This is still ok: it keeps everything in the critical section from getting out.  It's not necessary to stop later operations from appearing before the unlock.  See Jeff Preshing's article explaining Acquire and Release semantics)
On a weakly-ordered ISA, those mutex functions would run barrier instructions, like ARM dmb (data memory barrier).  Normal functions wouldn't, so the author of that guide is correct to point out that those functions are special.

Now what prevents the CPU from reordering mov 10 into i and mov 20 into j to above call pthread_mutex_lock()

This isn't the important reason (because on a weakly-ordered ISA pthread_mutex_unlock would run a barrier instruction), but it is actually true on x86 that the stores can't even be reorder with the call instruction, let alone actual locking/unlocking of the mutex done by the function body before the function returns.
x86 has strong memory-ordering semantics (stores don't reorder with other stores), and call is a store (pushing the return address).
So mov [i], 10 must appear in the global store between the stores done by the call instruction.
Of course in a normal program, nobody is observing the call stack of other threads, just the xchg to take the mutex or the release-store to release it in pthread_mutex_unlock.

A:

The short answer is that the body of the pthread_mutex_lock and pthread_mutex_unlock calls will include the necessary platform-specific memory barriers which will prevent the CPU from moving memory accesses within the critical section outside of it. The instruction flow will move from the calling code into the lock and unlock functions via a call instruction, and it is this dynamic instruction trace you have to consider for the purposes of reordering - not the static sequence you see in an assembly listing.
On x86 specifically, you probably won't find explicit, standalone memory barriers inside those methods, since you'll already have lock-prefixed instructions in order to perform the actual locking and unlocking atomically, and these instructions imply a full memory barrier, which prevents the CPU reordering you are concerned about.
For example, on my Ubuntu 16.04 system with glibc 2.23, pthread_mutex_lock is implemented using a lock cmpxchg (compare-and-exchange) and pthread_mutex_unlock is implemented using lock dec (decrement), both of which have full barrier semantics.


Q:

Python nested lists join lookup reference list

New to python so apologies if this is trivial.
I have a list
list = [3,1,0,2]

and a nested lookup
lookup = [[265,301,201],[225,302,191],[225,35,134],[28,82,158]]

I need to match every element in "list" with each corresponding element index in "lookup" and return the value of this element from "lookup".
The result should be:
result = [
[28,82,158],
[225,302,191],
[265,301,201],
[225,35,134]
]

A:

You can use a list comprehension:
result = [lookup[i] for i in list]

(Note that you shouldn't call a variable list.  It will shadow the builtin of the same name, and will lead to unexpected beahaviour sooner or later.)

A:

A regular list comp and indexing:
lst = [3,1,0,2]

print([lookup[i] for i in lst])
[[28, 82, 158], [225, 302, 191], [265, 301, 201], [225, 35, 134]]

Or a functional approach using __getitem__:
lst = [3,1,0,2]

lookup = [[265,301,201],[225,302,191],[225,35,134],[28,82,158]]

print(list(map(lookup.__getitem__, lst)))

[[28, 82, 158], [225, 302, 191], [265, 301, 201], [225, 35, 134]]

using operator.itemgetter:
lst = [3,1,0,2]

lookup = [[265,301,201],[225,302,191],[225,35,134],[28,82,158]]
from operator import itemgetter

print(list(itemgetter(*lst)(lookup)))
 [[28, 82, 158], [225, 302, 191], [265, 301, 201], [225, 35, 134]]


Q:

Contact forms on circle bundles whose fibres are Reeb orbits

Let $\pi: M \to \Sigma$ be a circle bundle over a closed surface $\Sigma$. When does $M$ admit a contact form whose Reeb orbits are the fibres of this bundle?

A:

These are known as Boothby-Wang fibrations. There are conditions that can be studied to say when your question can be positively answered. You can check Geiges Introduction to Contact Topology in Section 7.2.


Q:

ответ Ping в zabbix

Добрый день. Нужно в заббикс выводить график доступности хоста путем его пинга. Комманду предпологаю такую:
ping -s 991 -M do 1.2.3.4

Меня интересует время ответа. Как бы это реализовать в заббикс.

A:

В заббиксе есть стандартный функционал определения задержек и потерь через icmp – https://www.zabbix.com/documentation/2.4/ru/manual/config/items/itemtypes/simple_checks


Q:

MongoDB - Checking to see if multiple fields exist in a collection

I am looking for a way to see if two fields already exist in an collection.Ive been reading the docs but they dont seem to be helping too much.
I have seen that you can use $exist but can this compare multiple fields at the same time?
How would I go about achieving this?
I have a collection with something like this
{userId: ObjectId("57840667f862724c0f736a69"), artId: ObjectId("5783e368b30fb4482ba390eb")}

I want to check to see if this collection contains both
userId:ObjectId("57840667f862724c0f736a69") && artId: ObjectId("5783e368b30fb4482ba390eb")

A:

I think you can use and and $exist.
db.collection.find({
  $and : [
    { userId: { $exists: true } },
    { artId : { $exists: true } }
  ]
})


Q:

CodeIgniter : Get value from single column from table

I have a table that contains personal data, such as name, gender, address, etc. my question is, how to get the total number of men and women from my table?
This is my SQL query :
SELECT gender, COUNT(*) AS total
FROM personaldata
GROUP BY gender

This is my code so far in my model :
public function gender_count()
{
    $this->db->select('gender, count(*) as total');
    $this->db->from('personaldata');
    $this->db->group_by('gender');

    $query = $this->db->get()->row()->total;
    return $query->result();
}

So how to write that SQL query to CI model and controller? I just want to show the total gender in my site.
Thank you

A:

There are two ways to do that, you can choose which one you feel ease

Model:
public function gender_count()
{
    $response = array();
//for female
    $this->db->select('count(id) as ftotal');//id should be primary key
    $this->db->from('personaldata');
    $this->db->where('gender','f');
    $this->db->group_by('gender');
    $query = $this->db->get();
    if ($query->num_rows() > 0) {
        $response['f'] = $query->row('ftotal');
    }else{
        $response['f'] = 0;
    }
//for male
    $this->db->select('count(id) as mtotal');//id should be primary key
    $this->db->from('personaldata');
    $this->db->where('gender','m');
    $this->db->group_by('gender');
    $query = $this->db->get();
    if ($query->num_rows() > 0) {
        $response['m'] = $query->row('mtotal');
    }else{
        $response['m'] = 0;
    }
    return $response;//assosiative array
}

OR
public function gender_count()
{
    $response = array();
    $this->db->select('gender,count(id) as total');//id should be primary key
    $this->db->from('personaldata');
    $this->db->group_by('gender');
    $query = $this->db->get();
    if ($query->num_rows() > 0) {
        foreach($query->result() as $row){
          $response[$row->gender] = $row->total;
        }
    }else{
        $response['f'] = 0;
        $response['m'] = 0;
    }
    return $response;//assosiative array
}

Controller:
$data = array();
$genderCount = $this->Gender_model->gender_count();
$data['fcount'] = $genderCount['f'];
$data['mcount'] = $genderCount['m'];
$this->load->view('genderCount',$data);

View:
Female:<?php echo $fcount;?>
Male:<?php echo $mcount;?>


Q:

Simple ajax doesn't work in ASP.NET MVC Core 2

I have this C# code:
    public class HomeController : Controller
    {
        [Route("")]
        public IActionResult Index()
        {
            return View();
        }
        [Route("home/salam")]
        public JsonResult salam()
        {
            return new JsonResult("Alo Alo");
        }
    }

In my Index.cshtml I have this:
`

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

ppopyyyppyoptyphiopy

`

It compiles fine, but ajax doesn't work. Please help me. What should I do? The message "I'm here" appears but "Hello Dear" doesn't.

A:

your function is open, close it
function(){
    $.ajax({
                type: 'GET',
                url: '/home/salam',
                dataType:"jsonp",
                success: function () {
                    alert("Hello Dear");
                }
            });
}


Q:

Could not find artifact com.sun.kvem:kenv:jar:2.2 in central

I am trying to compile the source code of Proguard 4.6 in a maven project. The code has a dependency on:
<dependency>
    <groupId>com.sun.kvem</groupId>
    <artifactId>kenv</artifactId>
    <version>2.2</version>
    <optional>true</optional>
    <type>jar</type>
</dependency>

When I try compile it, I get:
Failed to execute goal on project proguard:
Could not resolve dependencies for project net.sf.proguard:proguard:jar:4.6:
Could not find artifact com.sun.kvem:kenv:jar:2.2 in central
(http://repo1.maven.org/maven2) -> [Help 1]

When I browse central (here), there is indeed no such jar in the central repository.
I don't know what kvem is. Why is it declared as type=jar in the pom.xml and why isn't it in central repository? How do I solve this issue?

A:

you need to do:
mvn install:install-file -DgroupId=com.sun.kvem -DartifactId=kenv -Dversion=kenv -Dfile=com.sun.kvem-2.2.jar -Dpackaging=jar  -Dgenerate-pom=true


Q:

Cannot import libgdal with python django

I get this error with Django:
>>> import django.contrib.gis.gdal
>>> print django.contrib.gis.gdal.libgdal.gdal_full_version()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'module' object has no attribute 'libgdal'

but I have this:
$ locate libgdal

/usr/local/lib/python2.7/site-packages/django/contrib/gis/gdal/libgdal.py
/usr/local/lib/python2.7/site-packages/django/contrib/gis/gdal/libgdal.pyc
/usr/local/lib/python2.7/site-packages/django/contrib/gis/gdal/libgdal.pyo

A:

Importing a package in python does not necessarily automatically import any subpackages/modules under it. When you do import django.contrib.gis.gdal, that runs __init__.py in the gdal directory; it's up to that file whether it then does import libgdal in order for that to become available through gdal. In this particular case, gdal imports (among others) gdal_full_version function  from libgdal into itself, but not libgdal as a whole, so you can just do:
>>> import django.contrib.gis.gdal
>>> print django.contrib.gis.gdal.gdal_full_version()
GDAL 1.6.3, released 2009/11/19

Or to be explicit as to where the function is actually defined, you could do:
>>> import django.contrib.gis.gdal.libgdal
>>> print django.contrib.gis.gdal.libgdal.gdal_full_version()
GDAL 1.6.3, released 2009/11/19


Q:

What's a proper way to handle shaders in latest three.js?

The older examples I could google work with the specific versions of Three.js. When I'm trying to make a simple example with the newest one, it doesn't work:
function shaders() {
    var vShader = [
        'void main() {',
            'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
        '}'
    ].join('\n');

    var fShader = [
        'void main() {',
            'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);',
        '}'
    ].join('\n');

    material = new THREE.ShaderMaterial({
        vertexShader: vShader,
        fragmentShader: fShader
    });

    //material = new THREE.MeshBasicMaterial({color: 0x00ff00, wireframe: true});

    geometry = new THREE.SphereGeometry(50, 32, 32);
    mesh = new THREE.Mesh(geometry, material);

    scene.add(mesh);
}

Full code listing available here: http://jsfiddle.net/doubleyou/Hhh89/
Note, that if you uncomment a commented line with material assignment, it will be working. So, guess, I initialize a shader material in a wrong way or something.
For what it's worth, Chrome doesn't show me any errors at all. Even if I make shaders code invalid, which is odd.

A:

Finally got an explanation.
I've been using CanvasRenderer. Should have been using WebGLRenderer instead.


Q:

Getting selected rows of report files from a WPF Datagrid on button click

This is my first question on stackoverflow and I am entirely new to programming in C# so please bear with me. I created an application using WPF in which I displayed a list of files with .rpt extension in a datagrid. The datagrid contains the list of filenames and there is also a checkbox column in the datagrid. These files are populated in the grid dynamically from a folder browser when I click on a button. I am stuck on the part of retreiving these files for printing when I click on a second button (print, as I need to call a service to print the selected files).
This is the code snippet that I have tried until now:
public partial class MainWindow : Window
{
    public class ReportFile
    {
        public string Path { get; set; }
        public string FileName { get; set; }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        string inputPath = AppDomain.CurrentDomain.BaseDirectory;

        System.Windows.Forms.FolderBrowserDialog fldDlg = new System.Windows.Forms.FolderBrowserDialog();
        fldDlg.SelectedPath = AppDomain.CurrentDomain.BaseDirectory;
        DialogResult result = fldDlg.ShowDialog();
        foreach (string str in Directory.GetFiles(fldDlg.SelectedPath))
        {

            ReportFile reportFile = new ReportFile();
            reportFile.Path = str;
            reportFile.FileName = System.IO.Path.GetFileName(str);
            dataGrid1.Items.Add(reportFile);
        }
    }

    private void button_Click_1(object sender, RoutedEventArgs e)
    {
        foreach (ReportFile drv in dataGrid1.SelectedItems.OfType<ReportFile>())
        {
            if (drv != null)
            {
                DataRow row = drv.Row;
                Title = row.ItemArray[3].ToString();
                System.Windows.MessageBox.Show(Title.ToString());
            }
        }

        var TransactionFactory = new TransactionFactory();
        var Transaction = TransactionFactory.NewTransactionString();
        var EnvironmentValue = (string)cmbEnvironment.SelectedValue;
        var CirieEngineServiceClientFactory = new CirieEngineServiceClientFactory(EnvironmentValue);

        var CirieEngineServiceClient = CirieEngineServiceClientFactory.NewCirieEngineServiceClient();
        var Form = new Cirie.Form()
        {
            Path = string.Empty,
            Title = string.Empty
        };

        var PackageID = Convert.ToInt16(txtPackageID.SelectedText);
        var Generation = Convert.ToInt16(txtGeneration.SelectedText);
        var formList = new List<Cirie.Form>();
        var stream = CirieEngineServiceClient.PrintFormCollection
            (Transaction,
             new Collection<Cirie.Form>(formList),
             PackageID,
             Generation
             );
    }
}

But I am not sure if it is correct since there is an exception being thrown: Unable to cast object of type 'ReportFile' to type 'System.Data.DataRowView'
I would really appreciate help on this one please!

A:

You could use the OfType method to cast the SelectedItems to ReportFile objects and then access any properties of the ReportFile class:
foreach (ReportFile drv in dataGrid1.SelectedItems.OfType<ReportFile>())
{
    //...
}


Q:

How can I "hack" the Thunderbird Lightning extension to fully color categories

(Note: While I'm not entirely sure if this be better asked on SuperUser, I guess the fact that you probably will have to mess around in the xpi/jar file with the css settings, should make it suitable for SO.)
Mozilla Thunderbird's Calendar extension, Lightning, will use different colors for different calendars, and just use a narrow vertical bar for the category color: (Light blue as calendar color and red as category color)

What I would like to find out is how I could go about changing/"hacking" the css styles that - surely - must be associated with this, buried somewhere in the plugin directory, so that in the example above, the event would be fully colored red.
Anyone know how to achieve this?

A:

The category-overlay.png image is merely a gradient overlay to give the category bar the right looks.
Two options here. One more easy but not as reliable, the other a bit more difficult:
Option A: Easy
Create a userChrome.css in your $profile/chrome/ directory. It should contain the following:

.calendar-color-box[categories~="mycategory"],
.calendar-event-box-container[categories~="mycategory"] {
   background-color: #abc123 !important;
}

You'll need to do this for each category you'd like to change the color for. Note that changing the color of the category in the Lightning options won't change the category color you set here.
Option B: More complete
You'll need to modify some files inside lightning.xpi here. This solution merely requires you to set the category colors in Lightning and will also work for newly added categories. Note that this way events without a category are transparent, if you want more you'll have to do it on your own.

Open lightning.xpi with a zip program
Enter the directory chrome/
Open the containing calendar.jar with a zip program
Descend into content/calendar/
Open calendar-multiday-view.xml

search "calendar-color-box" and remove it from the class attribute
a few lines above there is a <content> tag, add class="category-color-box" to it

Open calendar-month-view.xml and calendar-view-core.xml and do the same
Save the files back to calendar.jar
Save calendar.jar back to lightning.xpi
Install the modified lightning.xpi

If you'd rather see a patch, this applies to the latest comm-central source:
diff --git a/calendar/base/content/calendar-month-view.xml b/calendar/base/content/calendar-month-view.xml
--- a/calendar/base/content/calendar-month-view.xml
+++ b/calendar/base/content/calendar-month-view.xml
@@ -52,21 +52,20 @@

 <bindings id="calendar-month-view-bindings"
   xmlns="http://www.mozilla.org/xbl"
   xmlns:html="http://www.w3.org/1999/xhtml"
   xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
   xmlns:xbl="http://www.mozilla.org/xbl">

   <binding id="calendar-month-day-box-item" extends="chrome://calendar/content/calendar-view-core.xml#calendar-editable-item">
-    <content mousethrough="never" tooltip="itemTooltip">
+    <content mousethrough="never" tooltip="itemTooltip" class="category-color-box">
       <xul:vbox flex="1">
         <xul:hbox>
           <xul:box anonid="event-container"
-                   class="calendar-color-box"
                    xbl:inherits="calendar-uri,calendar-id"
                    flex="1">
             <xul:box class="calendar-event-selection" orient="horizontal" flex="1">
               <xul:stack anonid="eventbox"
                          class="calendar-event-box-container"
                          xbl:inherits="readonly,flashing,alarm,allday,priority,progress,status,calendar,categories"
                          flex="1">
                 <xul:hbox class="calendar-event-details">
diff --git a/calendar/base/content/calendar-multiday-view.xml b/calendar/base/content/calendar-multiday-view.xml
--- a/calendar/base/content/calendar-multiday-view.xml
+++ b/calendar/base/content/calendar-multiday-view.xml
@@ -2119,20 +2119,19 @@
       ]]></handler>
     </handlers>
   </binding>

   <!--
      -  An individual event box, to be inserted into a column.
     -->
   <binding id="calendar-event-box" extends="chrome://calendar/content/calendar-view-core.xml#calendar-editable-item">
-    <content mousethrough="never" tooltip="itemTooltip">
+    <content mousethrough="never" tooltip="itemTooltip" class="category-color-box">
         <xul:box xbl:inherits="orient,width,height" flex="1">
           <xul:box anonid="event-container"
-                   class="calendar-color-box"
                    xbl:inherits="orient,readonly,flashing,alarm,allday,priority,progress,status,calendar,categories,calendar-uri,calendar-id"
                    flex="1">
             <xul:box class="calendar-event-selection" orient="horizontal" flex="1">
               <xul:stack anonid="eventbox"
                          align="stretch"
                          class="calendar-event-box-container"
                          flex="1"
                          xbl:inherits="context,parentorient=orient,readonly,flashing,alarm,allday,priority,progress,status,calendar,categories">
diff --git a/calendar/base/content/calendar-view-core.xml b/calendar/base/content/calendar-view-core.xml
--- a/calendar/base/content/calendar-view-core.xml
+++ b/calendar/base/content/calendar-view-core.xml
@@ -46,21 +46,21 @@
     xmlns="http://www.mozilla.org/xbl"
     xmlns:html="http://www.w3.org/1999/xhtml"
     xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
     xmlns:xbl="http://www.mozilla.org/xbl">

   <binding id="calendar-editable-item">
     <content mousethrough="never"
              tooltip="itemTooltip"
-             tabindex="-1">
+             tabindex="-1"
+             class="category-color-box">
       <xul:vbox flex="1">
         <xul:hbox>
           <xul:box anonid="event-container"
-                   class="calendar-color-box"
                    xbl:inherits="calendar-uri,calendar-id"
                    flex="1">
             <xul:box class="calendar-event-selection" orient="horizontal" flex="1">
               <xul:stack anonid="eventbox"
                          class="calendar-event-box-container"
                          flex="1"
                          xbl:inherits="readonly,flashing,alarm,allday,priority,progress,status,calendar,categories">
                 <xul:hbox class="calendar-event-details">

Option C: Change Javascript
This would be the best working hack, although it requires javascript changes. Open calendar.jar as described in Option B and check out calendar-views.js, there are two functions: updateStyleSheetForViews() and updateStyleSheetForCategory(). I'll leave this to people that want to tinker with it themselves, but the idea would be to add a rule for .calendar-color-box[categories~=...] that overrides the default rule in case there are categories. This way if there is no category set, the calendar color is used, otherwise the desired category color.
Have fun :)

A:

This extension looks perfect for the functionality you want.
https://addons.mozilla.org/en-us/thunderbird/addon/calendar-tweaks/
To have just this, uncheck all the options, and check these:

apply category color to event backgruonds
use calendar color if no category color


Q:

Using a project's package in another project in eclipse

how can I use the classes of a package out of the main project where it has been defined?
for example imagine there is an Employee class in package people which belongs to ProjectOne. let's assume Employee is needed in another project (ProjectTwo) with the same features.What should I do there?

A:

Right-click on ProjectTwo in the Package Explorer. Go to Build Path -> Configure Build Path. Go to the Projects tab, click Add, select ProjectOne, and click OK, then click OK again to exit the project properties window.
Then import your classes as usual - within ProjectTwo, you should be able to see ProjectOne's classes as if they were in the same project.


Q:

Android : Exit application

I went throgh different questions realted to this topic and still have few doubts.
Que One: In my application i have multiple activities A->B->C
A->B2->C2..
A-B3-C3...
is the flow . I have "back" and "home" button for each activity to go to previous activity and A respectively.
Initially i was launching each of these as "single task" and everything appeared to be good.
Now i wanted to handle error condition and thus the exit application came to picture.
SO from my reading i understand its not "good" to launch each activity as single task
( i ma not very clear the reason or am i wrong here )
SO i changed all activities launch mode as standard
So one thing i noticed is switching between actvities throu "back" or "home" is slow than earlier. SO iam i doing the right thing here
Que two:now i have my code
    if (some error)
    {
        this.finish()
    }

    code line;

this is in my root activity A and will be hit before launching any other activity
But what i see is finish is executed but before application really exit , code line is executed leading to some exception. My expected behaviour is once i call finish , it is like a return from this activity and no more code executed here
Que 3: Now when we call a finish on the root activity, who will actually handle it.

A:

Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
ListActivity.this.startActivity(i);
finish();


Q:

Having trouble with jmHighlight

I am very new to Javascript (ok, I've done 'Hello World' alright =]) and my other web programming skills are very limited.
I am trying to implement jmHighlight into one of my already created webpages but found I can't even get it to work in a clean page of its own.  I've obviously made a very rudimentary mistake somewhere but can't figure out where so I'm hoping someone can help.
Here's what I've tried which doesn't work:
<!DOCTYPE html>

some text

        <input type="button" value="Try it" onclick="myFunc()">

The alert works so I think the basic code is ok, I think its more the syntax of the plugin I've gotten wrong.  The author shows his work here:  here on GitHub and altered his syntax in section 2 for a fixed keyword ('some') instead of using a text box for now.  The include is in the same location as my page, but doesn't show in the debugger when I preview the page as loaded...
I have also tried lifting the code from his basic example Fiddle here but still can't get it to work.  I've also had a look at other jmHighlight questions here on SO, but can't manipulate them to work for me.
If someone could kindly point me in the right direction, or supply me with a very simple but complete working example that I can dissect myself to figure out where I went wrong, I'd be very appreciative!

A:

This code is working in Chrome, I have tried it and here is a fiddle which also shows it is working.
The only thing I think may not be right is your path to jmHighlight or the version of jmHighlight.
jmHighlight was also renamed to jquery.mark. Here is a rawgit URL pointing to the .min.js:
https://rawgit.com/julmot/jquery.mark/master/dist/jquery.mark.min.js


Q:

Simplify google sheet formula "SUM / INDEX / MATCH"

I am trying to use google sheet to create a roster formula, to sum up the duty hour per week using INDEX/MATCH/SUM.
But it's too long, is there any way to simplify the formula?
Also, I realize "MATCH" cannot recognize blank cell (N20), can that be fixed too?
=IFERROR(SUM(INDEX($O$12:$O$20,MATCH(D17,$N$12:$N$20,0)),INDEX($O$12:$O$20,MATCH(E17,$N$12:$N$20,0)),INDEX($O$12:$O$20,AND(F17,$N$12:$N$20,0)),INDEX($O$12:$O$20,MATCH(G17,$N$12:$N$20,0)),INDEX($O$12:$O$20,MATCH(H17,$N$12:$N$20,0)),INDEX($O$12:$O$20,MATCH(I17,$N$12:$N$20,0)),INDEX($O$12:$O$20,MATCH(J17,$N$12:$N$20,0))),"Err")

A:

try:
=ARRAYFORMULA(MMULT(IFERROR(REGEXREPLACE(UPPER(B6:H14), "^"&TEXTJOIN("$|^", 1, L1:L10)&"$",
 VLOOKUP(REGEXEXTRACT(UPPER(B6:H14), "^"&TEXTJOIN("$|^", 1, L1:L10)&"$"), L1:M10, 2*
 SIGN(ROW(A6:A14)), 0)&""), UPPER(B6:H14))*1, TRANSPOSE(COLUMN(B:H))^0))


Q:

How to convert object into array of objects

I have a javascript object that I would like to convert into an array of objects
 {
        "mongo": {
            "status": true,
            "err": ""
        },
        "redis": {
            "status": true,
            "err": ""
        },
        "rabbitmq": {
            "status": true,
            "err": ''
        }
}

The expected output must be
 [
        "mongo": {
            "status": true,
            "err": ""
        },
        "redis": {
            "status": true,
            "err": ""
        },
        "rabbitmq": {
            "status": true,
            "err": ""
        }
]

What is the correct way to achieve this with javascript code?
Thanks.

A:

Your expected output is not syntactically correct in javascript. JS arrays can have only numeric indices starting from 0. In you expected output, you have shown string keys.
The syntactically and symantically correct output would be:
[
    {
        "name": "mongo",
        "status": true,
        "err": ""
    },
    {
        "name": "redis",
        "status": true,
        "err": ""
    },
    {
        "name": "rabbitmq",
        "status": true,
        "err": ""
    }
]

JS Code to achieve this:

var obj = {
    "mongo": {
        "status": true,
        "err": ""
    },
    "redis": {
        "status": true,
        "err": ""
    },
    "rabbitmq": {
        "status": true,
        "err": ''
    }
};
var arr = [];
for (key in obj) {
    arr.push(Object.assign(obj[key], {name: key}));
}
console.log('sdf', arr);


Q:

How to reduce time complexity in this problem

I have been recently asked this question in an interview and I am wondering how to answer this.

You have a 2D matrix of binary digits in any random order
0 0 0 0 0 0 0 0
1 0 0 1 1 1 1 0
1 0 0 0 1 1 1 1
1 0 1 1 0 1 1 0
1 1 0 0 0 0 1 1
1 0 1 0 1 1 0 0
And you need to find the occurance of this pattern
1
11

So, looking at the above matrix it is evident that the answer is 6.
And I solved it like this
unsigned int Findpairs(const std::vector<std::vector<unsigned int>>& A) {
    unsigned int count = 0;

    for (unsigned int i = 0; i < (A.size()-1); i++) {
        for (unsigned int j = 0; j < (A[i].size()-1); j++){
            if(A[i][j]==1 && A[i+1][j]==1 && A[i+1][j+1]==1){
                count++;
            }
        }
    }

    return (count);
}

The next question was to get a better time complexity.
I could not answer the exact solution.
Can someone help me with this? I just want to know this for my own curiosity.

A:

Here is a small optimization which is dependent on the input pattern.
unsigned int Findpairs(const std::vector<std::vector<unsigned int>>& A) {
    unsigned int count = 0;

    for (unsigned int i = 0; i < (A.size() - 1); i++) {
        for (unsigned int j = 0; j < (A[i].size() - 1); j++) {
            if (A[i + 1][j + 1] == 1) {
                if (A[i + 1][j] == 1 && A[i][j] == 1) {
                    count++;
                }
            }
            else {
                j++; //skip a column because our bottom right saw 0
            }
        }
    }

    return (count);
}


Q:

ngrx 4 selectors returning entire state instead of sub states

For some reason all of my selectors are returning the entire state object instead of the sub states that I thought they should. For example, I am trying to just return the customer State from reducers/customer.ts but instead I get an object with the entire State from index.ts.
I choose the particular structure below after examining the ngrx example app from github, clearly I am doing something(s) wrong.
File structure:

Here is actions/customer.ts:
import { Action } from '@ngrx/store';
import { State } from '../reducers/customer';

export enum CustomerActionTypes {
  Add = '[Customer] Add Selected Customer to Store'
}

export class Add implements Action {
  readonly type = CustomerActionTypes.Add;
  constructor(public payload: State) {
    console.log("from action: " + JSON.stringify(payload,null,2));
  }
}

export type CustomerActions = Add

And reducers/customer.ts:
import { ActionReducer, Action } from '@ngrx/store';
import { CustomerActionTypes, CustomerActions } from '../actions/customer';

export interface State {
  name: string;
  status: string;
  phone: string;
  stage: string;
  type: string;
  id: string;
  street: string;
  city: string;
  postalCode: string;
  email: string;
  state: string;
}

export function reducer(
  state: State,
  action: CustomerActions
): State {
  switch (action.type) {
    case CustomerActionTypes.Add:
      return action.payload

    default:
      return state;
  }
}

export const getCustomerState = (state: State) => state;

And reducers/index.ts:
//For reducers map
import * as fromMainNav from './main-nav-ui';
import * as fromTradeUI from './trade-ui';
import * as fromAppts from './appointments';
import * as fromCustomer from './customer';

//Whole application state
export interface State {
  mainNavUI: fromMainNav.State;
  tradeUI: fromTradeUI.State;
  appointments: fromAppts.State;
  selectedCustomer: fromCustomer.State;
}

//Reducer map
export const reducers = {
  mainNavUI: fromMainNav.reducer,
  tradeUI: fromTradeUI.reducer,
  appointments: fromAppts.reducer,
  selectedCustomer: fromCustomer.reducer
};

And imports in app.module.ts:
imports: [
    ...
    StoreModule.forRoot(reducers)
  ],

And lastly how I am am wiring it up in a component and using selector:
...
import * as fromCustomer from '../../../shared/state/reducers/customer';
...

public cust$: Observable<fromCustomer.State>;

constructor(
    ...
    public ngrxStore: Store<fromCustomer.State>
  ) {
      this.cust$ = ngrxStore.select(fromCustomer.getCustomerState);
    }

Any help would be appreciated, thanks!

A:

Try using createFeatureSelector inside reducers/index.ts to start from a top level feature state:
export const getAppState = createFeatureSelector<State>('wholeApp');

Then use it in a different selector to access your customer reducer:
export const getCustomer = createSelector(
  getAppState,
  (state: State) => state.selectedCustomer
);

From there you can keep going deeper into your state by chaining selectors, as example, if your component just needed to know about a customer's email adresse, it could just subscribe to this:
export const getEmail = createSelector(
   getCustomer,
   (state: fromCustomer.State) => state.email
);

For more details (and examples) I recommend checking this great article by Todd Motto:
https://ultimatecourses.com/blog/ngrx-store-understanding-state-selectors


Q:

What tools are needed for making 3D games?

Hi I'm new to 3D games developing, I can a little c++, C#, VB.Net, 3D Max, ArchiCad ..etc. my problem is where to get started, which tools I need to start a own 3D game like GTA, I have tried some tools like : 'Unity3D' (crashes on start), '3D Rad' (uses only built-in items), 'Game Maker A7' (only 2D games can be made there).. could you help me to find the tools of making a 3D game..plz
I'm using Windows XP SP 2, I don't have pixel shader 1.1 into my video card

A:

Go back and try Unity3D again.  It's a good product, and I'm sure with a bit of work you can figure out why it's crashing.


Q:

Splitting cells separated by a comma

okay guys i have seen a lot of questions about this but have not been able to find the answer i am looking for. I have been playing around with macro codes and trying to write some myself and big fail. So if anyone has a code that would do this, that would be awesome.

I need the Codes in column B seperated by a comma to be split into a new cell below and rest of the row copied with it. The range on this sheet is from Comumn A to N. Please see below for what i need.

The numbers in column B will always be 4 digits long and seperated by commas. I have found some codes i thought worked but all they did was copy the set of numbers and deleted the rest and repeatedly pasted the same number.
Any help on this will be greatly appreciated.

A:

x = 2
Do Until Cells(x, 2) = ""
    splt = Split(Cells(x, 2), ",")
    If UBound(splt) > 0 Then
        Number = Cells(x, 1)
        Rows(x & ":" & x + UBound(splt) - 1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        For Each e In splt
            Cells(x, 2) = Trim(e)
            Cells(x, 1) = Number
            x = x + 1
        Next e
    Else
        x = x + 1
    End If
Loop

If you will ever have codes that start with zero (i.e. 0432), make sure column B is formatted as text in your spreadsheet, or excel will convert it to 432 when it puts it into the cell.


Q:

preg_replace words not inside a url

I am using preg_replace to replace a list of words in a text that may contain some urls.
The problem is that I don't want to replace these words if they're part of a url.
These examples should be ignored:

foo.com
foo.com/foo
foo.com/foo/foo

For a basic example (written in php), I tried to ignore strings containing .com and optional slashes and chars, using a negative look ahead assertion, but with no success:
preg_replace("/(\b)foo(\b)/", "$1bar$2(?!(\w+\.\w+)*(\.com)([\.\/]\w+)*)", $text);
This call works just ignores the word before .com.
Any help would be really appreciated.

A:

In cases  like these, its much easier to think of the problem inverted. You want to match words not in an url. Instead think, you want to match the url and the words. So, your expression would look like this: url_match_here|(?:my|words|here). This will allow the regex engine to consume the URL first and then try to match those words. Thus, you never have to worry about matching the words inside an URL. If you want to maintain the text structure, you can use preg_replace, with the following expression (url_match_here)|(?:my|words|here) and replace by \1 to preserve the URL and the text.
I hope this helps.
Good luck.


Q:

JSF / Primefaces Link to Filesystem

I have a WebApplication, where I have to provide direct access to a mounted network drive on the client side (e.g. \\server\zentrale mapped to drive Z:\).
I tried following, but nothing works:
user files
<h:outputlink target="_blank" value="file:///server/zentrale/username/data">user files

user files
<h:outputlink target="_blank" value="file:///Z:/username/data">user files

I also added <disable-cross-context>false</disable-cross-context> in my jboss-web.xml - without success.
@BalusC mentioned in JSF 2 and a link to file system  to create a new webapp context.
So, how can I do this using WildFly 10 and Primefaces 6.1 ?
In an older version of our WebApplication we used the IE View plugin for Firefox, but this was last updated in 2013! Because we have to support other browser like Chrome and IE, we don't want to be dependent on some browser plugins!

A:

In https://developer.jboss.org/thread/227893 I found a hint, how to get access to the local filesystem on the server side.
standalone.xml
<subsystem xmlns="urn:jboss:domain:undertow:3.0">
    <buffer-cache name="default"/>
    <server name="default-server">
        <http-listener name="default" socket-binding="http" redirect-socket="https"/>
            <host name="default-host" alias="localhost">
                <location name="/" handler="welcome-content"/>
                <location name="documents" handler="document-handler"/>
                <filter-ref name="server-header"/>
                <filter-ref name="x-powered-by-header"/>
            </host>
    </server>
    <handlers>
        <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
        <file name="document-handler" directory-listing="true" path="\\server\Zentrale\docments"/>
    </handlers>
</subsystem>

To achieve this using jboss-cli.sh use the following commands:
/subsystem=undertow/server=default-server/host=default-host/location=documents:add(handler=document-handler)
/subsystem=undertow/configuration=handler/file=document-handler:add(path=\\\\server\\Zentrale\\documents, directory-listing=true)

A click on each link in page.xhtml opens a new tab in the browser where I can navigate in the server's file system - even on shared folders!
page.xhtml
Project 4711
<h:outputLink value="/documents/projects/project_4711/" target="_blank">Project 4711</h:outputLink>

This is the solution for my problem, but yes - it does not allow me to navigate on the clients local filesystem!


Q:

Scaling an image to crop in android

I am working on an android application that allows the user to crop an image. I have tried this code to scale the image to crop. But when I try to resize the area to crop, it moves both horizontally and vertically, only allowing to crop a square area. I want it to work in such a way that when I move it vertically it doesn't move vertically

      intent.setData(mImageCaptureUri);
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("return-data", true);

A:

Remove the following code, then you can crop any size
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);


Q:

Matlab image processing - replacing dark pixels with neighboring pixels

I am doing some image processing of the retina images.. I need to replace the blood vessels with background pixels so that I can focus on other aspects of retina. I could not figure out a way to do this. I am using matlab. any suggestions?

A:

Having worked extensively with retinal images, I can tell you that what you're proposing is a complex problem in itself. Sure, if you just want a crude method, you can use imdilate. But that will affect your entire image, and other structures in the image will change appearance. Something, that is not desirable.
However, if you want to do it properly, you will first need to segment all the blood vessels and create a binary mask. Once you have a binary mask, it's up to you how to fill up the vessel regions. You can either interpolate from the boundaries or calculate a background image and replace the vessel regions with pixels from the background image, etc.
Segmentation of the blood vessels is a challenging problem and you will find a lot of literature concerning that on the internet. Ultimately, you will have to choose how accurate a segmentation you want and build your algorithm accordingly.


Q:

Web Development - Security

In terms of security, is it generally a better practice to keep all of your javascript files embedded in the source html, or is it more secure to link to an external html file from the source html. Are they treated the exact same and I'm just being an idiot?
I am very new to web development and I don't really understand the encryption side of things:
(1) Embedded javascript
<!DOCTYPE html>
<html>
    <head>
    ...
    </head>

    <body>

        ...

        <script>
            function myFunction()
            {
                // is this secure?
            }
        </script>

        ...

    </body>
</html>

(2) External javascript
<!DOCTYPE html>
<html>
    <head>
        ...
    </head>

    <body>
        ...
        <script src="myFunction.js"></script> // or is this better?
    </body>
</html>

A:

Anything that makes it to the client side can be captured and viewed. So all JS files are open to viewed along with your HTML.
For security, if you have business logic or sensitive code that needs to remain unseen you need to place that on the server side and only access the results of that code running via API calls.


Q:

Problem in StatWeave

I visited http://www.stat.uiowa.edu/~rlenth/StatWeave/ and installed StatWeave according to the instructions. But my problem is that there are no Step by Step instructions given in the manual, and also that example .tex files are not provided so that I can check it. Test files are given with .odt and .swv extensions, and I don't know how to use them in the StatWeave. Any suggestions?

A:

I assume that you're interested in R, since you tagged your question with it. Also, I think you're interested in processing a tex file. In this case, as suggested by @daroczig, it is worth giving a try to Sweave.
The following works for me, at least with the R statistical package (I don't have SAS, but I works with Stata on my Mac OS 10.6). I just followed the on-line manual, §4.1 (pp. 6-7).
\documentclass{article}
\usepackage{Statweave}
\begin{document}
\RweaveOpts{prompt="> "}

\section{StatWeave example using R}

Here are some fake data:

\begin{Rcode}{label=summary,saveout}
x <- replicate(3, rnorm(100))
summary(x)
\end{Rcode}

The dataset is of size \Rexpr{nrow(x)}.
Here is the results of the call to \verb|summary(x)|:

\recallout{summary}
\end{document}

The above file, say 1.tex, might be compiled with
$ statweave --weave 1.tex

providing statweave is in your path. It generate the file 1.pdf which is shown below:

I installed statweave some time ago, and I just followed the instructions from the install jar file (run java -jar statweave.jar: it will install binaries in the specified directory, LaTeX style file and OpenOffice templates, and finally it asks you to check for external tools--R, Stata, SAS, Matlab, etc.--you want to enable).


Q:

The website cannot display the page

First post on here.
I am a developer for the company I work for and we have a word press site that is public (we host it).  For this query lets say the url is http://mywordpresssite
We have just copied the site internally to our DEV server so we can perform development on it.  The mySQL database has been copied as well and if I browse to the internal URL I can view the page.  Lets say the url is http://mywpsite.
The problem comes when I try to access the admin console on the dev site.  On the public site I would use http://mywordpresssite/wp-login.php and this works fine.  If I use http://mywpsite/wp-login.php I get the following web page.

I am not that familiar with word press, does anyone have any tips on how to resolve this or where I should be looking to change files etc.
Thanks
UPDATE
I am still having an issue with this but I am a bit further through identifying the issue.
I enabled error logging on the site and when I try to navigate to the admin page the error log displays the following:

[04-Apr-2017 07:31:22 UTC] PHP Warning:  Illegal string offset
  'remember' in D:\mywordpressstie\wp-includes\user.php on line 39
  [04-Apr-2017 07:31:22 UTC] PHP Warning:  Cannot assign an empty string
  to a string offset in D:\mywordpressstie\wp-includes\user.php on line
  39 [04-Apr-2017 07:31:22 UTC] PHP Warning:  Illegal string offset
  'user_login' in D:\mywordpressstie\wp-includes\user.php on line 54
  [04-Apr-2017 07:31:22 UTC] PHP Fatal error:  Uncaught Error: Cannot
  create references to/from string offsets in
  D:\mywordpressstie\wp-includes\user.php:54 Stack trace:
0 D:\mywordpressstie\wp-login.php(775): wp_signon('', '')
1 {main} thrown in D:\mywordpressstie\wp-includes\user.php on line 54

I have been googling it but my php/wordpress knowledge is limited.  I found the following URL link to patch, bit no idea how to use this.
Can anyone help?

A:

I fixed it!!!  Woohoo.
Using this link - link to patch
I edited the line it advises and it works fine.


Q:

Having two identical ids in different xml files

Can I assign the same id name to two different views which are in two different xml files?
It won't let me change it using "Edit ID.." button, but when I change it manually, it doesn't say anything and works fine. But might it become a problem and why?
If possible, please add a link or an general explanation on android visual tree build, I would really like to learn on the subject.
Thanks.

A:

It's fine to have the same ID in multiple XML files. The only time this might be a problem is if you had a nested layout containing an ID which is also present in the parent.
Having the same ID can actually be useful in some cases- for example if you load a different XML file in different circumstances (such as portrait and landscape) you can give views the same ID, so in code you just call findViewById once and it will work.