How to add a specific implementation of a Mock created with Autofixture?

Question: I am writing tests for class (lets call it Sut) which has some dependencies injected via constructors. For this class I have to use the constructor with the most parameters, therefore I used the AutoMoqDataAttributeGreedy implementation:
public class AutoMoqDataAttribute : AutoDataAttribute
{
    public AutoMoqDataAttribute() : base(new Fixture().Customize(new AutoMoqCustomization()))
    {
    }
}

public class AutoMoqDataAttributeGreedy : AutoDataAttribute
{
    public AutoMoqDataAttributeGreedy() : base(new Fixture(new GreedyEngineParts()).Customize(new AutoMoqCustomization()))
    {
    }
}

The constructor of my sut looks like this:
public class Sut(IInerface1 interface1, IInterface2 interface2, IInterface3 interface3)
{
    Interface1 = interface1;
    Interface2 = interface2;
    Interface3 = interface3;
}

One example test looks like this:
[Theory, AutoMoqDataAttributeGreedy]
public void SomeTest([Frozen]Mock<IInterface1> mock1 ,
                      Mock<IInterface2> mock2,
                      Sut sut,
                      SomOtherdata data)
{
    // mock1 and mock2 Setup omitted

    // I want to avoid following line
    sut.AddSpeficicInterfaceImplementation(new IInterface3TestImplementation());

    sut.MethodIWantToTest();

    //Assert omitted
}

The problem is that I need a specific implementation of IInterface3 for testing and I want to avoid adding a method to my SUT (Interface3TestImplementation) only for my unit test and I also I want to avoid repeating code since I have to add this instance in each and every test.
Is there a nice and neat way to have this implementation being added for all my test / for specific tests with Autofixture?
Answer: If you need to do this as a one-off test, then the answer by Enrico Campidoglio is the way to go.
If you need this as a general rule throughout all of your unit tests, you can customize the Fixture with a TypeRelay:
fixture.Customizations.Add(
    new TypeRelay(
        typeof(IInterface3),
        typeof(IInterface3TestImplementation));

This will change fixture so that, whenever IInterface3 is needed, an instance of IInterface3TestImplementation will be created and used.
Comment: Thanks, I actually need it for most of all my unit test but I like Enrico's solution which would reduce the code in the actual unit test body.
Comment: @zlZimon You can put the above in a Customization that you add in your `AutoMoqDataAttribute` constructor...
Comment: D'oh... I somehow did not think of that. Thanks again.
Answer: You can have AutoFixture create an instance of a concrete type and tell it to use that instance every time it has to provide a value for any of its implemented interfaces. Here's an example:
[Theory, AutoMoqDataAttributeGreedy]
public void SomeTest(
    [Frozen]Mock<IInterface1> mock1,
    [Frozen]Mock<IInterface2> mock2,
    [Frozen(Matching.ImplementedInterfaces)]IInterface3TestImplementation impl3,
    Sut sut)
{
}

In this case, AutoFixture is going to create an instance of IInterface3TestImplementation and use it every time it encounters an interface implemented by that type.
This means that if the constructor of Sut has a parameter of type IInterface3, AutoFixture is going to pass it the the same instance that's being assigned to the impl3 parameter, which you can use in your test.
As an aside, there are other ways of matching frozen instances to types and members other than just by interface. If you want to know more, take a look at the members of the Matching enumeration.
Comment: Thanks that was exactly what I was looking for.
Answer: Using your IFixture that you have created, you can call .Register against a specific interface and supply the object to use when that interface is then subsequently used.
e.g.
_fixture = new Fixture().Customize(new AutoMoqCustomization());
_fixture.Register<Interface3>(() => yourConcreteImplementation);

You could also use mocking that would allow you to then use .Freeze on the fixture and that way you could just set some expected calls against the interface and wouldn't need a completely concrete instance. You could let AutoFixture create a default implementation for you and apply the setup that you configured.
e.g.
var mockedInterface = _fixture.Freeze<Mock<Interface3>>();
mockedInterface
    .Setup(x => x.PropertyOnInterface)
    .Returns("some value");

Comment: Unfortunately I do need a concrete implementation for `Interface3`. I also do not understand your first suggestion since I do not create any IFixture. I am using AutoFixture to auto create all my mocks and my `sut` via the `AutoDataAttribute`.
Comment: This line here in your code will return an IFixture that you can then use. new Fixture().Customize(new AutoMoqCustomization()
Comment: Oh ok I thought you were referring to my example above where I do not create a `IFixture` "in code". The Problem is that I am creating the mocks and `Sut` via the xUni` Theory as a parameter in the actual Unit test.


Can std::make_unique be used with abstract interface?

Question: Consider the following line of code:
auto source1 = std::unique_ptr<IGpsSource>(new GpsDevice(comPort, baudrate));
auto source2 = std::unique_ptr<IGpsSource>(new GpsLog(filename));

How can that be written using the new std::make_unique function, supported by VS 2013?
Is it even possible?*
*My problem is that I don't know how to tell std::make_unique what kind of object to instantiate. Because only the constructor's parameters are passed in there seems to be no control over that.
Comment: @MarcoA. VS2013 supports a few C++14 bits, and `make_unique` is one of them.
Comment: Isn't it C++14? I thought VS2013 didn't support it
Answer: std::unique_ptr<Base> base_ptr = std::make_unique<Derived>();

As Angew said, the above should work fine. Provided Derived uses public inheritance. Just wanted to add that for completeness.
Answer: Yes, you can of course use make_unique for that, but it's not as useful as you might want. You have these options:
std::unique_ptr<IGpsSource> source1 = std::make_unique<GpsDevice>(comPort, baudrate);
auto source2 = std::unique_ptr<IGpsSource>{ std::make_unique<GpsLog>(filename) };

I would say the real question is "why do you want that?"

Unlike make_shared, make_unique has no allocation benefits over new. So if you need control of the pointer's type, what you're doing is just fine.
Why do you need the pointer to be typed to IGpsSource in the first place? An implicit conversion from std::unique_ptr<Derived> rvalues to std::unique_ptr<Base> rvalues exists. So if you're actually calling make_unique to initialise an IGpsSource pointer, it will work just fine. And if you want to transfer the pointer somewhere, you'll have to std::move it anyway, at which point the conversion can happen again.
Comment: Exception safety argument [from this answer](http://stackoverflow.com/a/20895705/673852) still applies to `make_unique`, not only to `make_shared`. So, `make_unique()` should be preferred over `unique_ptr(new Xyz)`.
Comment: @Ruslan Note that the exception safety criterion applies to multiple allocations being done in a single expression. The OP's case is quite different: they have only a single allocation, and want precise control over the pointer's type.
Comment: @ajmal-kunnummai's [answer](https://stackoverflow.com/a/49619801/754300) makes more succinct use of `std::make_unique()`.


time derivative of the Jacobian matrix of a nonlinear transformation

Question: I have a dynamical system whose state is a vector $\mathbf{y}\in \mathbf{R}^m$. The vectors $\mathbf{y},\dot{\mathbf{y}},\ddot{\mathbf{y}}\in \mathbf{R}^m$ relate to the vectors $\mathbf{z},\dot{\mathbf{z}},\ddot{\mathbf{z}}\in \mathbf{R}^n$ through the transformations
\begin{align}
\mathbf{y}&=g(\mathbf{z})\\
\dot{\mathbf{y}}&=J(\mathbf{z})\dot{\mathbf{z}}\\
\ddot{\mathbf{y}}&=J(\mathbf{z})\ddot{\mathbf{z}} + \dot{J}(\mathbf{z})\dot{\mathbf{z}}
\end{align}
where $J$ is the Jacobian matrix of the nonlinear transformation $g$.
What are the entries of $\dot{J}(\mathbf{z})$? For example, if $J_{ij}=\frac{\partial y_i}{\partial z_j}=a\sin(z_j)$, then what is $\dot{J}_{ij}$?
(There is a similar but unanswered question here.)
Answer: The Jacobian $J(\mathbf{z})$ is a matrix whose time derivative we are finding. The entries of $J(\mathbf{z})$ are expressed as
\begin{equation}
J_{ij}(\mathbf{z}) = \frac{\partial y_i}{\partial z_j}.
\end{equation}
I assume we can evaluate the entries of $J(\mathbf{z})$. For instance, in the example given in the question, we have that
\begin{equation}
J_{ij}(\mathbf{z})=a\sin(z_j)
\end{equation}
for some indices $i,j$. The time derivative of $J_{ij}(\mathbf{z})$ is
\begin{align}
\frac{\mathrm{d}}{\mathrm{d}t} J_{ij}(\mathbf{z}) &= \frac{\mathrm{d}}{\mathrm{d}t}\frac{\partial y_i}{\partial z_j}\\
&= \frac{\mathrm{d}}{\mathrm{d}t} a\sin(z_j)\\
&= a\dot{z}_j\cos(z_j).
\end{align}


Have you ever used kon-boot?

Question: Has anyone here ever used kon-boot? I guess it may work because of the few blog posts about it but I feel kinda concerned and am interested at hearing experiences from anyone who have used multiple times with no side effects.
I am slightly worried for any direct memory altering it tries to do.
I am also worried if this will do its job fine to hide the fact it puts in a low level trojan or if the author planned to do anything like that in a future release as it looks like closed source from the site.
Also I don't intend to gain illegal access but I find these sort of things very useful for my box of live discs I take every where, just in case.
OT: Other question that me be of interest to readers here
Answer: I've used it successfully on a test Ubuntu machine, never managed to get it running in Windows mode.  There are plenty of other ways of gaining access to a machine without passwords, all tried and tested and mostly open-sourced, and so there's no real reason to use Konboot IMHO.
Answer: Sounds like you have more to lose then to gain. Don't use it if you're worried about your network.
I would not rely on the opinion of anyone who could not audit source code.
If you wanted to be adventurous you could use it on an isolated system, then monitor that system's traffic on the swtich/router.
Answer: Kon Boot is perfectly safe. A new commercial version 1.1 is out, it can be obtained at www.kryptoslogic.com . It is a California based company, and they back and support the product entirely. Some discount coupons for it laying around the net, but still cheap at $15 bucks.

Have you ever used kon-boot?


cUrL in php : Nothing come in response [NULL]

Question: I am fetching data from thirdparty API using CURL in php. I have read the documentation and passing the same valid parameters to the request but nothing works.
I am showing the code removing "API KEY" due to confidentiality.
$service_url = 'https://api.birdeye.com/resources/v1/business/147197756121167?api_key=ApiKeyGoesHere';
    $curl = curl_init($service_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $curl_response = curl_exec($curl);
    if ($curl_response === false)
    {
        $info = curl_getinfo($curl);
        curl_close($curl);
        echo '
';
        die('error occured during curl exec. Additioanl info: ' . var_export($info));
    }

    curl_close($curl);
    $decoded1 = json_decode($curl_response,true);
    if (isset($decoded1->response->status) && $decoded1->response->status == 'ERROR')
    {
        die('error occured: ' . $decoded1->response->errormessage);
    }
    echo 'response ok!';
    var_export($decoded1->response);
    ?>

The Output it gives me is : response ok!NULL
Link to the documenataion of birdeye API.
http://docs.birdeye.apiary.io/#reference/business/get/get-business

I have tried testing with Terminal it gives me response.
Can Any One give me the way, where I am going wrong?
Comment: Does this api have any test  key so i can look on curl issue
Answer: Try this with your api key
 $urltopost = 'https://api.birdeye.com/resources/v1/business/147197756121167?api_key=ApiKeyGoesHere';
 $header=array("content-type"=>"application/json");
 $ch = curl_init ($urltopost);
 curl_setopt ($ch, CURLOPT_POST, true);
 curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 $returndata = curl_exec ($ch);
 $status_code = @curl_getinfo($ch, CURLINFO_HTTP_CODE);
 print_r($status_code);
 print_r($returndata);

Comment: Can you pls tell me where should I add this line? Shall I overwrite above curl_setup function?
Comment: After this  line in your code curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
Comment: because after adding your line it throws me "HTTP Status 500 - Internal Server Error" this error
Comment: sure you can check it :)
Comment: Sure m on mini-micro -10minutes break I will get back to you soon. Please be online :)
Comment: "HTTP Status 405 - Method Not Allowed" by applying your code.
Comment: replace  curl_setopt ($ch, CURLOPT_POST, true); to curl_setopt($ch, CURLOPT_HTTPGET, 1); in my code and check now
Answer: Check with this piece of code once. This works for me.
<?php
// Get cURL resource
$curl = curl_init();

// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => "YOUR API END POINT"

));

// Send the request & save response to $resp
$result = json_decode(curl_exec($curl),true);

// Close request to clear up some resources
curl_close($curl);

return $result;

Comment: Sure m on mini-micro -10minutes break I will get back to you soon. Please be online :)
Comment: it is giving me empty result


Shouldn't this function be not invertible?

Question: Given question:

Define a function f : $\ D \to \mathbb{Z}$ by $\ f(x) = x^2 + 5 $, where $\ D = \{-4, -3, -2, -1, 0\} $.
Find $\ f^{-1} $.

My answer is that there isn't an inverse of function f because f is not bijective, as per I was taught and stated in my lecture notes. While f is one-to-one (injective), f is not onto (surjective) since set D only has 5 elements and the co-domain is the set of integers - not every element in the co-domain has a preimage.
However, the model answer given is such:

$\ y = x^2 + 5 \to x^2 = y - 5 \to x = \sqrt{y - 5} $
$\ f^{-1}(x) = -\sqrt{x-5} $

I have tried searching on this and everywhere seems to say the same thing E.g. link1, link2, link3 - that for a function to be invertible, it must be bijective.
I am rather confused at the moment... am I wrong and the model answer is correct?
Thanks!
Comment: The way the question is stated you are right. If the question said find $f^{-1}:f(D) \to D$ then the given answer would have been right.
Comment: The question does not mention inverse or invertibility. It asks about $f^{-1}$. That is well-defined even for functions that are neither injective nor surjective.
Comment: Many times questions like this one are meant to be understood as: show $\;f\;$ is one-to-one and find its image $\;E\;$, and then $\;f:D\to F(D)=E\;$ is bijective and etc. It is not the most precise way to ask but sometimes it is what it must be understood. Check the source of the question.
Answer: You are technically right. The function f is not invertible because it is not surjective.
However, f is invertible when limiting the co-domain to the range f(D) of the function. In that case, the function is the inverse.

$\ f^{-1}(x) = -\sqrt{x-5} $

Perhaps a even nicer way of writing that would be:

$\ g : \{ x \in \mathbb{Z} , x \geq 5\} \to D$
$\ g(x) = -\sqrt{x-5}$

Hence:

$f(D) = \{5, 6, 9, 14, 21, 30\}$
$\ g|_{f(D)} = f^{-1}$

Perhaps the biggest question is how you should answer this question in the first place.
Sure, being technically correct is important for math, but perhaps seeing "the big picture" that there is a condition for a inverse function when limiting its domain to specific subset is just as important. Figuring out the overall intent of the questions can be a very useful skill when trying to prove a statement.
If this is a "homework/exam question" though, keep in mind that this "see the big picture" and "common sense" is subjective - from my experience, different fields and mathematicians have different expectations and it is often worth to talk with your instructor to see how things align.
For instance, if I was working with someone that pointed that the function was not invertible because of the domain I would say something like "Sure, you are right, but you understood what I meant." in the sense of "Hey, this is probably just a detail in the whole scheme of what we are doing".
Answer: Note that the range of $f$ is $f(D) = \{5, 6, 9, 14, 21, 30\}$
\begin{align}
   \ y &= x^2 + 5 \\
   x^2 &= y-5 &\text{Note that $y-5 \ge 0$.} \\
   x &= -\sqrt{y-5}
\end{align}


Adding options to Drupal search

Question: I've been working on a site and I need to change the search.
I've changed the search form with hook_form_alter(), added some checkboxes, ... Now I need to get the new data to the hook_search_execute() function?
How would I achieve that?
Answer: Drupal's search platform is rudimentary one. You can't really extend it, best you can do is to replace it. Most popular free platform now seems to be Apache Solr, connected to Drupal with Apache Solr Search Integration.
If Solr's to much, Search API integrates with views pretty neat, you can have one field for search and other as Views filters.
Answer: I found the answer to my problem. I alway wanted to use Search API, but wasn't sure how to do it.
I figured it out with:
https://stackoverflow.com/questions/8575289/extending-drupal-7-search

Adding options to Drupal search


Save scraping results one by one into Excel or CSV file in Python

Question: I have a crawler code as follows:
import requests
import json
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
import re
from datetime import datetime

def crawl(id):
    try:
        url = 'https://www.china0001.com.cn/project/{0:06d}.html'.format(id)
        print(url)
        content = requests.get(url).text
        soup = BeautifulSoup(content, 'lxml')
        tbody = soup.find("table", attrs={"id":"mse_new"}).find("tbody", attrs={"class":"jg"})
        tr = tbody.find_all("tr")
        rows = []
        for i in tr[1:]:
            rows.append([j.text.strip() for j in i.findAll("td")])
        out = dict([map(str.strip, y.split(':')) for x in rows for y in x])
        return out

    except AttributeError:
        return False

data = list()
for id in range(699998, 700010):
    print(id)
    res = crawl(id)
    if res:
        data.append(res)

if len(data) > 0:
    df = pd.DataFrame(data)
    df.to_excel('test.xlsx', index = False)

In this code, the result dataframe df will be writen to an Excel file after the whole scraping process is finished.
Now I want to save the scraping results one by one into Excel or CSV file during the scraping process, how could I modify the code above?
Thanks.
Updates:
MAX_WORKERS = 30
ids = range(700000, 700050)
workers = min(MAX_WORKERS, len(ids))

with futures.ThreadPoolExecutor(workers) as executor:
    res = executor.map(crawl, sorted(ids))

data = list(res)

if len(data) > 0:
    df = pd.DataFrame(data)
    df.to_csv('test.csv', mode = 'a', header = True, index = False)

Answer: Try Using to_csv with header=False, index=False
Ex:
for id in range(699998, 700010):
    res = crawl(id)
    if res:
        df = pd.DataFrame([res])
        df.to_csv('test.csv', mode='a', header=False, index=False)

Comment: Sorry, I get an error: `TypeError: to_excel() got an unexpected keyword argument 'mode'`
Comment: Oh sorry that option is only available in `.csv` for excel you need to use `startrow`
Comment: So, I need to use `df.to_csv('test.csv', mode='a', header=False, index=False)`, right?
Comment: I try to apply your code to multiprocess scraping, but it raises an error `AttributeError: 'bool' object has no attribute 'keys'`, could you please have a look to updates of my question? Thanks a lot.
Answer: I'd recommend looking at my question on here:
What is the problem with the pandas to csv in my code?.
I'd recommend looking at the answers for the daily sheets then apply and modify it to fit your program


Regex not operator

Question: Is there an NOT operator in Regexes?
Like in that string : "(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)"
I want to delete all \([0-9a-zA-z _\.\-:]*\) but not the one where it is a year: (2001).
So what the regex should return must be: (2001) name.
NOTE: something like \((?![\d]){4}[0-9a-zA-z _\.\-:]*\) does not work for me (the (20019) somehow also matches...)
Comment: There is a String like above and I want to regex it up, that the result of the regex is: `(2001) name`.
Answer: Not quite, although generally you can usually use some workaround on one of the forms

[^abc], which is character by character not a or b or c,
or negative lookahead: a(?!b), which is a not followed by b
or negative lookbehind: (?<!a)b, which is b not preceeded by a
Comment: But `[^abc]` should mean not `a` or `b` or `c`, not "not the string `abc`".
Comment: negative look(ahead|behind) also allows for easy negation of multiple letters, e.g. `you(?!tube)` or `(?<!docker)hub`
Comment: Yep, I think negative look-behind is (?<!a)b -- reference: http://www.regular-expressions.info/lookaround.html
Comment: Thanks. `%[^sdf]` or `%(?!(s|d|f))` equals to "contains %", but not "%s", "%d" or "%f".
Comment: `a(?!b)` (a not followed by b) is brillant. Best answer.
Answer: No, there's no direct not operator. At least not the way you hope for.
You can use a zero-width negative lookahead, however:
\((?!2001)[0-9a-zA-z _\.\-:]*\)

The (?!...) part means "only match if the text following (hence: lookahead) this doesn't (hence: negative) match this. But it doesn't actually consume the characters it matches (hence: zero-width).
There are actually 4 combinations of lookarounds with 2 axes:

lookbehind / lookahead : specifies if the characters before or after the point are considered
positive / negative : specifies if the characters must match or must not match.
Comment: Thank you the ?! is what I was suggesting too, but anyway if I use `\((?![\d]{4})[0-9a-zA-z _\.\-:]+\)` there is still `(20019)` in it
Comment: I escape the closing parenthesis `)` because I want to match the **literal** character `)` (just as you do at the very beginning and the very end of your regex!). Then *after* I matched that, I end the lookahead by using an unescaped `)`.
Comment: In the edit of your question you put the `{4}` *outside* the lookahead and in this comment you put it *inside*: which one did you try? Also: if you want `(20019)` to match, then you must add the `\)` *inside* your lookahead: `\((?![\d]{4}\))[0-9a-zA-z _\.\-:]+\)`
Comment: With the regex above in your comment, it works. But I don't understand that... I don't get why you escape the following part ``\((?![\d]{4} -->\)<--)[0-9a-zA-z _\.\-:]+\)`` Then there is a bracket not closed, isn't it?
Comment: Got it. I was a little bit confused by all that characters. Thank you.
Comment: Pardon the edit. Already handled in comments, so I reverted it.
Comment: if you don't need to test for anything else afterwards then the pure '(?!...)' sequence works quite well.
Answer: You could capture the (2001) part and replace the rest with nothing.
public static string extractYearString(string input) {
    return input.replaceAll(".*\(([0-9]{4})\).*", "$1");
}

var subject = "(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)";
var result = extractYearString(subject);
System.out.println(result); // <-- "2001"

.*\(([0-9]{4})\).* means

.* match anything
\( match a ( character
( begin capture
[0-9]{4} any single digit four times
) end capture
\) match a ) character
.* anything (rest of string)
Comment: @lorikku java != javascript
Comment: Use `.replace()` with a global regex flag, since `.replaceAll()` is not supported by a lot of browsers and also node.
Comment: @zyexal Oh oops! I didn't realise it was java haha, my bad!
Answer: Here is an alternative:
(\(\d{4}\))((?:\s*\([0-9a-zA-z _\.\-:]*\))*)([^()]*)(( ?\([0-9a-zA-z _\.\-:]*\))*)

Repetitive patterns are embedded in a single group with this construction, where the inner group is not a capturing one: ((:?pattern)*), which enable to have control on the group numbers of interrest.
Then you get what you want with: \1\3

Regex not operator


Exclude current node from entity reference view (for related news)

Question: In Drupal 7 I have a news content type with a simple related news selection list. This works like a charm, I use an entity reference view to fill the list and new news-items are created just like they should be. But once the news-item is published it will of course be shown in the list. If you select it, the standard behaviour will be to render its full content view, resulting in a recursive content error.
How can I create an entity reference view that excludes the current node? I have found a lot of related issues, but nobody seems to answer the question of using parameters at all in this special kind of view. I tried to add an argument to the filter using the token syntax which says "AND Nid not equals [node:id]" but that turns out to be ignored. I also found that when you include the view it is possible to send parameters to it, but I was unable to find documentation for how to use them.
Does anybody have more information/documentation about this?
Answer: there is a patch fixing that issue and helping you to use <code>[node:nid]</code> as an arg here.

Otherwise, did you try Entity Reference View Widget ?

The module has a way of hiding selected items from the View. Simply
  add a base field contextual argument (Product ID for products, Node ID
  for nodes, etc) and in the "More" fieldset enable "Allow multiple
  values" and "Exclude". Then edit the Entity Reference field, and in
  the widget settings enable "Pass selected entity ids to View ".
Comment: Thanks for the leads, I will look into it further. At the very least I misspelled nid as id there. Still I probably need the patch. Do you also have a hint of where to find more info about how to use submitted arguments from the content type?
Comment: What are you trying to achieve exactly ?
Comment: I just want to know how the argument system for entity reference works at all. It's a bit weird that there is no documentation for such a potentially powerful feature.
Comment: I don't really know, usually I set a custom PhP filter (or a contextual filter with php "when argument is not available") and use current_path, get the nid out of it and load it. I'd advise you to do the same, it's the simpliest for that use.
Comment: I am using aliases and clean URL's, how can I get the nid out of the path then? Also it seems like a hacky solution if there is an internal parameter passing mechanism.
Comment: By the way, I could not get the Entity reference view widget to display, although I follow the advice in the README.
Comment: You can get actual node by doing `$path = explode('/', current_path()); $nid = $path[2];` . More info on current_path() [here](http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/request_uri/7#comment-40018)


How can the expected value of an estimator in least square equation be equal to real parameter?

Question: Since the estimated parameter is constant then it's expected value will also be constant which would mean by proving
E(b1) = B1
we are proving that b1 = B1
because E(b1) = b1.
Answer: The expectation of your regression parameter is taken with respect to the noise. That is, you can draw many samples from the underlying population (as described by your noise term) and for each sample estimate the parameter. Thus, the parameter is not constant any more, but a random variable, so it makes sense to investigate its expectation. It turns out that under certain conditions, this expectation exists and is equal to the true parameter value.


$.ajax request in Rails 4 app doesn't render view

Question: I'm new to Rails and I'm trying to submit model data to a controller method, from javascxript, and render the list of results...
function submitResults() {
  resultURL = "/result";
  resultData = JSON.stringify(results);
  $.ajax({
    type: "POST",
    url: resultURL,
    data: { results: resultData},
    contentType: "application/html",
    dataType: "html"
  });

The server shows the controller method is executed and the view is rendered...
Started POST "/result" for 127.0.0.1 at 2014-11-14 17:36:32 -0600
Processing by ResultsController#create as HTML
  Result Load (0.7ms)  SELECT "results".* FROM "results"
  Rendered results/index.html.erb within layouts/application (366.0ms)
Completed 200 OK in 4722ms (Views: 408.3ms | ActiveRecord: 1.3ms)

but the browser doesn't render the view. Here's my create method that's triggered by the $.ajax call...
def create
  result = Result.new(result_params)
  result.save
  @results = Result.all
  respond_to do |format|
    format.html { render :index }
  end
end

Why doesn't the browser load the index view?
Answer: You ajax call is not doing anything with the response, define callback functions for it. E.g.:
$.ajax({
  type: "POST",
  url: resultURL,
  data: { results: resultData},
  contentType: "application/html",
  dataType: "html"
}).done(function(response) {
  //attach the response somewhere in the DOM.
});

Check the AJAX doc for all callbacks.
BTW, you usually do not want to load a whole html page through an ajax call. Seems like the page you are rendering includes everything (seems to be using the default layout). In such a case, making AJAX calls can have no benefits (and make things harder) and you might want to do the post through an html form.
Comment: Oh, sorry, I just update the answer. In your case, I suggest going with an html call. javascript has no benefit here. But if you want to do it with jquery, you can use $(document).html(response), which will keep the url the same, but change the whole DOM.
Comment: Thanks again, that makes sense. I'm really just trying to figure out a way to call my create method from javascript. Using $.ajax is the only way I've found so far. What do you mean by "html call"? Can you provide a quick code snippet that I can use to research futher?
Comment: Well, if you want to do it through javascript, then $.ajax is the best way, but again I suggest that if the result of the POST (call to create) is going to be a browser page change, then do not do it through javascript. Rails has helper methods that help you create html forms (I mean html, with no javascript). See [here](http://guides.rubyonrails.org/form_helpers.html)
Comment: Thanks. Unfortunately I can't use forms due to some of the tools I'm using to create the data that I'm posting. If I can't use forms and you don't suggest I submit through javascript, is there simply no solution? Either way, I appreciate your help.
Comment: Thanks. It depends, you can still do so through javascript but changing your controller to return a page partial, a javascript script or a json object. OR you can have javascript prepare an html form you already have in the dom on page load(which seems to not be possible in your case). There might be other ways I am not aware of too.
Comment: What's preventing you from using a regular html form?  Even if you have dynamic data you can add that data as hidden form elements and still submit the form as you wish.


Add a trust hostname in mysql

Question: how have I to add a trusted hostname in the mysql configuration?
webserver.mysomain.com
dbserver.mydomain.com

I would like to add the webserver.mydomain.com in the mysql database installed in the dbserver.mydomain.com
so all the connections that come from the webserver.mydomain.com must be accepted.
thanks
Answer: I am not sure what you are trying to achieve here nor whether mysql has a concept of trusted hosts. But if you are doing this for security reasons, then do it at the user level when adding users in mysql. In other words, you will have to setup a user in mysql which connects from the webserver only, you can do this through the grant privileges options -
mysql> grant all privileges on *.* to firstname.lastname@example.com identified by 'password';
mysql> flush privileges;

On top of that, modify your firewall rules to allow mysql connections, port 3306, from webserver.mydomain.com - In iptables you can do it this way:
/sbin/iptables -I INPUT -s webserver-ip-address -p tcp --dport 3306 -j ACCEPT

Comment: Setting up users like this is great as long as you do not configure `my.cnf` with `skip-host-cache` or `skip-name-resolve`. +1 !!!
Comment: Hi @Danielt. thanks for your reply. So is not possible set just a record in order to trust of the webserver hostname for all the requests?
Comment: @Michelangelo - Not that I am aware of. Don't take my word for it though, as I am not a DB administrator. And yet, I don't see the point of adding a trusted host, as you have to use a username/pass to access a database and to accomplish that you have to add the users in mysql. It is during this process that you specify the host from which the user is allowed to login.

Add a trust hostname in mysql


Is "Concave Hull" correct terminology?

Question: Can we call the envelop of a set of points having non-convex boundary as "Concave Hull"?
Comment: So is $\{0, 1\}$, an envelop of $\{0,1\}$, a concave hull in this definition?
Comment: You should start defining it in a more precise way than "the envelop". For example, if you have a concave quadrilateral, there are two more concave quadrilaterals with the same vertices. Note also that the intersection of concave sets may be convex.
Answer: You sort of can, but the definition of the boundary becomes strange. For example, you can always find a non-intersecting polygon that has all the points in the set as vertices, and consider this your "concave hull."
As a proof, join the dots in a cycle in any order and number them with this order (so for $n$ points we will have points $P_i$ for $1\leq i \leq n$ with $P_i$ immediately before $P_{i+1}$ where subscripts are taken modulo n).
Now suppose that two edges $P_a P_{a+1}$ and $P_b P_{b+1}$ cross. These are diagonals of a convex quadrilateral $P_a P_b P_{a+1} P_{b+1}$, and so we have $|P_a P_b| + |P_{a+1}P_{b+1}| < |P_aP_{a+1}| + |P_b P_{b+1}|$. So the total sum of lengths decreases. Note that there are a finite number of orderings of the $n$ points, so we choose one with minimal sum of lengths. Then no two edges can cross, since we could use the operation to decrease the sum of lengths, causing a contradiction. So this polygon has no crossings.

Is "Concave Hull" correct terminology?


Best ways to reduce number of DOM elements

Question: Everyone agrees that less DOM elements means better page performance. It means better javascript performance, especially in older browsers.
But where are the best places to look to reduce DOM elements? What are the common culprits that you guys have come across that are easy fixes to get that number down?
Answer: use:

    etc..

in stead of:

        etc..

... when possible, that is. Sometimes you need the additional div for layout purposes. But when not necessary, don't use it.
Comment: Thanks for the suggestion. I was hoping this would turn into a similar discussion like "Common jQuery pitfalls" but I guess there just aren't common suggestions for this issue.
Comment: Why use  and  at all? Use a regular  tag alone. That would more than halve the nodes in your menu.
Comment: There will be more suggestions forthcoming as developers begin to realize the importance google is placing on page rendering speed.
Comment: can we have any online smart enough tool that can do this?
Answer: Rather than using
 tags, use regular  tags and apply styling to a custom class.
Remove all
 tags also, they count as a node, again, use styling for spacing instead.
Especially in nav menus placed in footers:

Home

Blog

Could be replaced with:
Home
Health Blog

Which would reduce number of nodes from 5 to 2.
And finally, we use heavy code in our header, for account login, UPI, basket etc. Some of these could be replaced with a single
 or  tag, which when clicked pulls in the required 150 nodes via XMLHTTPRequest.
Comment: It would great to see a blog post explaining further these useful changes.
Answer: If you are using ASP.NET server controls then that might be a good place to start. Some of the server side controls, while great for fast development, will render themselves with excessive markup. I'm not advocating you don't use server side controls, but you might find some modules of your site that are good candidates for DOM reduction by
1) rewriting the markup yourself or
2) building the markup with the System.Web.UI.HtmlControls namespace.
Good candidates for this approach are components appearing on your site frequently (header, footer, navigation menus). Candidates are also not frequently changed or modified unless you are comfortable maintaining this style.
Another ASP.NET specific technique is to use a System.Web.UI.WebControls.PlaceHolder to work with dynamically instead of a div or panel with the runat="server" attribute. The placeholder control won't render any additional elements, only what you've added to it.
Answer: Anywhere where you are using an element to affect layout is usually something you can think about. Often times you can actually use less elements combined with CSS to achieve the same result. Hard rules are difficult as it depends a lot on the specific case.


copy string one place to another

Question: copy string between comma
input
(aaa),(ddD),(sss),(ppp)

p=malloc(sizeof(char)*200);
gets(p);

i want hold input
p[0]="(aaa)"
p[1]="(ddD)"
p[2]="(sss)"
p[3]="(ppp)"

Answer: You may have to use strtok.
Here is the complete solution to all your problems:
// tokens.c

#include <stdio.h>
#include <string.h> /* for strtok, strlen and strcpy. */
#include <stdlib.h> /* for malloc, realloc and free. */

static char **tokens = NULL; /* Dynamic array of string tokens. */
static int token_count = 0; /* Number of tokens added. */

/* Grows the `tokens' array as needed and appends `tok' to it. */
static void
copy_token (char *tok)
{
  if (token_count == 0)
    tokens = malloc (sizeof (char*));
  else
    tokens = realloc (tokens, sizeof (char*) * (token_count + 1));
  tokens[token_count] = malloc (strlen (tok) + 1);
  strcpy (tokens[token_count], tok);
  ++token_count;
}

/* Extracts tokens from `s' and calls copy_token to add it to `tokens'. */
static void
tokenize_by_comma (char *s)
{
  char *tok = strtok (s, ",");
  while (tok != NULL)
    {
      copy_token (tok);
      tok = strtok (NULL, ",");
    }
}

/* If you run copy_after, the total length of all tokens
   must not exceed BUFF_SIZE. */
#define BUFF_SIZE 1024
static char s_copy[BUFF_SIZE + 1];

/* Makes a string of all the tokens by moving `s' next to `after'. */
static char *
copy_after (const char *s, const char *after)
{
  int i;
  int appended = 0;
  strcpy (s_copy, "");
  for (i = 0; i < token_count; ++i)
    {
      int is_s = (strcmp (tokens[i], s) == 0);
      int is_after = (strcmp (tokens[i], after) == 0);
      if (is_after)
        {
          strcat (s_copy, after);
          strcat (s_copy, ",");
          strcat (s_copy, s);
          appended = 1;
        }
      else if (!is_s)
        {
          strcat (s_copy, tokens[i]);
          appended = 1;
        }
      if (i != (token_count - 1) && appended)
        strcat (s_copy, ",");
      appended = 0;
    }
  return s_copy;
}

/* Prints the `tokens'. */
static void
print_tokens ()
{
  int i;
  for (i = 0; i < token_count; ++i)
    printf ("%s\n", tokens[i]);
}

/* Frees the memory allocated for `tokens'. */
static void
free_tokens ()
{
  int i;
  for (i = 0; i < token_count; ++i)
    free (tokens[i]);
  free (tokens);
  token_count = 0;
  tokens = NULL;
}

/* Test. Pass the tokens as a single command line argument. */
int
main (int argc, char **argv)
{
  tokenize_by_comma (argv[1]);
  print_tokens ();
  if (argc == 4)
    {
      printf ("%s\n", copy_after (argv[2], argv[3]));
    }
  free_tokens ();
  return 0;
}

Test run:
$ ./tokens "(aaa),(ddD),(sss),(ppp)"
(aaa)
(ddD)
(sss)
(ppp)
$ ./tokens "(aaa),(ddD),(sss),(ppp)" "(ddD)" "(ppp)"
(aaa)
(ddD)
(sss)
(ppp)
(aaa),(sss),(ppp),(ddD)

Comment: okey your answer is okey. i amasending another question ,can you give me answer
Comment: @gcc Please preserve the old question so that others will benefit from the answers. Raise the new question as a new entry, not by editing the old one.
Answer: Avoid using gets(3), it lead to some interesting issues even in the early days of the Internet due to easy buffer overflow. Use the fgets(3) instead.
Comment: That is not stack overflow, it is buffer overrun.
Comment: Overrun of a buffer on the stack ... yeh, you are right, will update.
Answer: If you're sure you're always going to have four inputs, you can use something like:
scanf("%[^,],%[^,],%[^,],%[^,]", p[0], p[1], p[2], p[3]);

if you don't know the number of inputs, you'd probably do the reading in a loop instead:
for (i=0; i<limit; i++)
    if (!scanf("%[^,],", p[i]))
        break;
if (i<limit)
    scanf("%[^\n]", p[i]);

or, if you prefer, you could write the loop like this:
for (i=0; i<limit && scanf("%[^,],", p[i]); i++)
    ;

Either way, this reads data that doesn't contain a comma followed by a comma (that is read to verify its presence) until that fails. Assuming the data is in the proper format, that will fail when there's data without a trailing comma. We then do one more read after the loop to read the remainder of the line into the last item.
Note that if your data can also contain a comma, something like:
(aaa,bbb),(ccc,ddd)
where the first data item should be "(aaa,bbb)" and the second "(ccc,ddd)", this would not work -- for something like that, you could rewrite the conversion for an individual input to something like: "%[^)])," to read up to the closing parenthesis, followed by a parenthesis followed by a comma.

copy string one place to another


Http Server - Are Netty FileRegions reusable?

Question: I am currently working on an http server and some things are behaving kind of strange.
I want to generate dynamic content and also just provide static files.
Serving dynamic generated content works without problems.
Since I want to profit from zero copy I use FileRegions to serve static files.
My channel pipline contains the following handlers (in this order):

HttpRequestDecoder
HttpResponseEncoder
HttpObjectAggregator
ApiMapper

The ApiMapper is sharable and derived from the SimpleInboundHandler.
On creation the ApiMapper creates a FileRegion from a static file.
Now everytime the "/" uri is requested this happens:

A DefaultHttpReponse is written to the ChannelHandlerContext.
The DefaultHttpReponse is not reused and contains headers for
Content-Type and Content-Length
The ReferenceCount of the FileRegion is increased using its retain method.
Then writeAndFlush is called on the ChannelHandlerContext with the FileRegion as parameter.
To the returned ChannelFuture a ChannelFutureListener is added which prints "DONE".

The first response works as expected, the browser gets the full file and displays it correctly and "DONE" gets printed.
But if the "/" uri is called again the browser doesn't show anything and just loads forever BUT "DONE" gets printed.
Then after I restarted the server I used telnet to make the calls manually. The first response is correct, but then I noticed that the second call only returns a header, but no content.
"DONE" still gets printed.
So my question: Can the same FileRegion object be used multiple times? Am I doing anything other wrong?
Answer: No you can not write the same FileRegion multiple times this way as the transferred state is updated on the DefaultFileRegion object. You will need to create a new DefaultFileRegion instance for each write here.
Also you need to ensure you send a LastHttpContent after your FileRegion as otherwise the state-machine in HttpResponseEncoder will not be in the correct state when you write the second HttpResponse.
Comment: Therefore I could reuse LastHttpContent.EMPTY_LAST_CONTENT? Would I have to increase the reference count before sending it?
Comment: May it be better to create a direct ByteBuf, store the file content in it and reuse it then creating a new DefaultFileRegion every time?
My current application is not very time critic and load heavy, but I'm curious for future projects.


What is the time complexity of an algorithm that loops over a list of strings and then also loops over each character of each string?

Question: I just did an interview where my solution involved this algorithm, but I could not say with confidence what the time complexity was.
Psuedocode example:
arr = ["hello", "this", "is", "some", "different", "length", "strings"]

function (arr)
    for string in arr
        for char in string
            // do stuff in constant time

I initially thought that the complexity as O(N * M) where N is the length of the array and M is the length of each string, but if the strings vary in length I cannot characterize all their lengths with a constant M.
EDIT: strings in the array don't have to be real words and can be any string of arbitrary length
Comment: I assume that the average length of the words won't change, since they're real words.  So then the only changing quantity is the length of the array.  So, as @Max says, the complexity is O(N).
Comment: It's linear, so O(n) (it'a been 30 years, since I've done that, so not an answer)
Comment: The total number of operations done is the sum of the numbers of characters in each string.  You could express that another way, as the number of strings multiplied by the average number of characters per string.
Comment: @CryptoFool I used real words here as an example but let's assume these can be any string of arbitrary length
Comment: I see you now say your lists contain arbitrary strings.  Do those strings tend to grow in size as the list's size increases? How would you expect the average string size to change when you have 1 million strings vs 100K strings?
Comment: @CryptoFool So you could say the time complexity is O(M) for each string in the array, where M is the average number of characters in each string, and O(N) for the whole algorithm where N is the length of the array?
Answer: In this case, where the amount of work you do doesn't depend solely on the number of elements in the input array but also on a property of those elements (namely, their length), you're correct that simply describing the algorithm as linear or O(n) would be inadequate.
If all the strings are indeed of arbitrary length, you could technically describe the time-complexity as being 'pseudo-polynomial' or 'pseudo-linear'. Although the lengths of the strings are arbitrary (as you put it, you can't give a fixed value to 'm'), you could still describe the complexity as O(nm) where m is the length of the largest string in the input (It's not important that m is unknown or arbitrary: you could say the same thing about n). It would also be correct to say the algorithm is in O(nm) or even Θ(nm) for m as the average length of the input strings. These are just specific ways of saying that it is pseudo-linear.
But if you make more qualifying assumptions or re-frame what you interpret as the 'input' of the algorithm, then you could describe it as linear. For example, if you can bound the maximum length of any string in the input by any constant (eg if you know there will be no string longer than 10,000 characters), then saying the algorithm is O(n) would be completely correct. You could also say that the algorithm is linear in the total number of characters in the input (rather than in the number of words), or linear in the average input string length.


Libgdx - finding objects attributes from another class

Question: I have a class Sword that is instantiated to create several objects in my game and hold them in an Array structure. How do I find the attributes each object of Sword class from another class ?
How my spawned swords look
This code allocate and generate the Sword(s) Renderer class:
private List<Sword> swords = new ArrayList<Sword>();

Then in public Renderer() method I do:
for (int i = 0; i<10 ; i++ ) {
            swords.add(new Sword());
        }

In the  render() they are displayed on the screen:
for (Sword sword : swords) {
    sword.createMe();
}

And here is my Sword class:
 public class Sword {
    private TextureRegion sprite;
    private static int xx;
    private static int yy;
    private int x;
    private int y;
    private int size;
    private Random r;
    public Sword() {
        r = new Random();
        x = (r.nextInt(10))*GameRender.tilesize;
        y = (r.nextInt(10))*GameRender.tilesize;
        size = GameRender.tilesize;
        sprite =getSprite();
    }

    private TextureRegion getSprite() {
        int id = r.nextInt(2);
        System.out.println(id);
        if(id==1){
            sprite=AssetLoader.s1;
        }else sprite=AssetLoader.s2;
        return sprite;
    }

    public void createMeShape(){
        GameRender.shapeRenderer.rect(x, y, size, size);
    }

    public void createMe() {
        GameRender.batch.draw(sprite, x, y, size, size);
    }

    public static void Update() { }
}

So how do i find the value of  x, y from the Render class (I cant use static because it will only find one swords position) for collision detection or how i check if swords x,y is same like playerx, playery (ints from GameRenderer class)?
Comment: You would need to add a getter method. See the following questions in SO [Why use getters and setters?](http://stackoverflow.com/questions/1568091/why-use-getters-and-setters) and [How do getters and setters work?](http://stackoverflow.com/questions/2036970/how-do-getters-and-setters-work)
Answer: Add a getter in your Sword class.
// Returns the sword x location
public int getLocX()
{
    return this.x;
}

There's many ways you can go about this, i.e. using a Vector instead. The implementation is up to you.
On a side note, I would highly recommend you use Box2D for collision detection in libgdx.
Comment: Why the **getLocX()** needs to be static? Have a read at what a static variable/method is: [Java – static variable with example](http://beginnersbook.com/2013/05/static-variable/) and [Java: when to use static methods](http://stackoverflow.com/questions/2671496/java-when-to-use-static-methods).
Comment: i cant use this because when i use somewhere getLockX() it needs to be static. I guess i need to use Voctors.
Comment: Nvm. The vectors worked perfectly, thankyou i didnt even thought about vectors before this


como pegar dados de fora e adicionar em uma função ja existente em Python

Question: Estou criando um joguinho de dados mas quando quero colocar uma continha de pontos não estou conseguindo...
def get_dados():
  dado1 = int(input("Digite o número para o primeiro dado: "))
  dado2 = int(input("Digite o número para o segundo dado: "))
  return dado1, dado2
dado1, dado2 = get_dados()

Aposta
def aposta(fichas):
  aposta = 0
  while(aposta >= 0):
      try:
        aposta = int(input("Digite sua aposta: "))
        if(aposta > 49 and aposta < 301):
          fichas -= aposta
          print("Suas fichas agora são: ", fichas)
          break
        else:
          print("Sua aposta deve ser maior ou igual a 50 e menor ou igual a 300!")
      except ValueError:
        print("\nDigite uma opção válida!")
aposta(fichas)

def jogarDados(dado1,dado2):
  primer_dado=random.randint(1,6)
  segund_dado=random.randint(1,6)
  print("Jogando os dados...")
  time.sleep(2)
  print("...")
  print("O resultado dos dados foram:", primer_dado, "e", segund_dado)
  if (primer_dado == dado1 or segund_dado == dado2) or (primer_dado == dado2 or segund_dado == dado1):
    print("parabéns, você acertou sua aposta...")

    fichas=fichas+aposta+aposta
    print("suas fichas atuais são: ",fichas)
  else :
    print("perdeu a sua aposta")
    #print("infelizmenente você perdeu essa rodada, e junto com a rodada perdeu sua aposta... nao desista.. ainda da tempo")
jogarDados(dado1,dado2)

o código esta assim mas estou tendo dificuldade em especial nessa parte:
print("O resultado dos dados foram:", primer_dado, "e", segund_dado)
  if (primer_dado == dado1 or segund_dado == dado2) or (primer_dado == dado2 or segund_dado == dado1):
    print("parabéns, você acertou sua aposta...")

    fichas=fichas+aposta+aposta
    print("suas fichas atuais são: ",fichas)

Answer: Faça assim, renomeie a função aposta() para get_aposta(), daí você poderá chamá-la assim:
aposta = get_aposta(fichas)

E quando for a vez de chamar a função jogarDados(), esta terá acesso de leitura ao conteúdo da variável "aposta" que foi definida anteriormente.


Show that $\text {ran} (T + K)$ is closed.

Question:
Let $\mathcal H$ be a Hilbert  space. Let $T \in \mathcal L(\mathcal H)$ and $K$ be a compact operator on $\mathcal H.$ If $\text {ran} (T)$ is a closed subspace of $\mathcal H$ then show that $\text {ran} (T+K)$ is also closed.

Let $\{(T + K)x_n\}_{n \geq 1}$ be a sequence in $\text {ran} (T + K)$ converging to $x \in \mathcal H.$ If $\{x_n\}_{n \geq 1}$ is a bounded sequence then $\{Kx_n\}_{n \geq 1}$ will have a convergent subsequence say $\left \{Kx_{n_k}\right \}_{k \geq 1}$ converging to $y$ (say). Then $Tx_{n_k} \to (x - y).$ But since $\text {ran} (T)$ is closed it follows that there exists $z \in \mathcal H$ such that $(x - y) = Tz.$ So $x = y + Tz.$ Now I get stuck and couldn't proceed further. Because $y$ might not necessarily be in the range of $K.$ Instead what I can say is that there exists a closed ball $B$ of some positive radius such that $\overline {K(B)}$ contains $y.$ Also I have no idea how to proceed when $\{x_n\}_{n \geq 1}$ is unbounded. Some help is very much required at this moment.
Thanks for your time for reading.
Comment: what is $ran(T)$?
Comment: @Praphulla Koushik $\text {ran} (T)$ represents the range of the operator $T.$
Comment: Assuming $range(T)$ is a closed subset, I think that, if $(x_n)$ is unbounded, then, the sequence $(T+K)(x_n)$ does not even converge.. Have you tried in this direction?
Comment: @Praphulla Koushik Yes, I have tried but couldn't succeed. I don't get a proper argument here. May be there is some clever way to do it.
Answer: The result if FALSE.  For a counter-example, take $T$ to be the zero operator and $K$ any compact operator with a non-closed range.


How many measurements should be done?

Question: I am measuring time of a computer operation. The operation should run roughly same time each time I measure it. How many times should I measure it to get good average and standard deviation?
originally posted here: https://physics.stackexchange.com/questions/64917/how-many-measurements-should-be-done , but I think that this forum is more appropriate for my question
Comment: Please note that reposting across SE fora is discouraged. The correct thing to do if you post in one place but think it belongs in another is to flag it and ask for it to be moved.
Answer: The easy rule of thumb is that more is better. If it's cheap and easy, take more measures.  It depends on how much variance there is between the measures - that is, how much measurement error there is, and how accurately you want to measure it.   If the measures are always exactly the same, then one will do it. If they are widely different, you'll need more.
The problem has existed for a long time in psychometrics - how many questions do I need to ask someone to get an idea of their (say) math ability?
The answer is given by the Spearman Brown prophecy formula: http://en.wikipedia.org/wiki/Spearman%E2%80%93Brown_prediction_formula  This tells you how the reliability increases as a function of increasing the number of measures.
Answer: That really depends on your definition of 'good'.
What kinds of things do you need to say?
If sufficient moments exist, the variance of the mean will decrease as $\frac{1}{n}$. ... and the variance of the variance and of the standard deviation also decreases as $\frac{1}{n}$  (for large $n$, anyway - e.g. for the variance of the variance you end up with $1/n \times$ <something that eventually goes to a constant> ).
So, for example, if you specify the width of a confidence interval you require, you can compute the approximate $n$ you should need to obtain it, as long as you have some idea of the quantities involved.

How many measurements should be done?


Can travis-artifacts be used to upload to S3 from a pull request?

Question: I have an org repo at github.com/numenta/experiments, and a forked version at github.com/rhyolight/experiments. When trying to get artifact uploads to S3 working as described in this blog post, I used the travis encrypt command to do this with the -r rhyolight/experiments option, and it worked, as you can see on line 60 in the travis output.
I created a pull request against the original repo, and the build failed there with the error:
Missing required arguments: aws_access_key_id, aws_secret_access_key (ArgumentError)

That tells me that travis was unable to decrypt the secure environment variables, probably because this is being executed in a different repository than where the hashes were created. Ok, that makes sense. So I recreated the secure variables with the -r numenta/experiments slug instead of using my own github username. So, I get a familiar upload error when the build runs on rhyolight/experiments, which I expected, but I also get the same upload error when it runs against the numenta/experiments from within a pull request.
To experiment, I merged the pull request to see if the secure values would be extracted properly once they were merged into master and no longer running from a pull request... and it worked!
Is there any way to publish artifacts with the travis-artifacts project from within a pull request to another repository?
Thanks in advance!
Answer: After chatting with support at Travis, the answer is no.


Java : error in SQL syntax

Question: I am trying to retrieve information from my database, with following query :
 String Retrieve
                    = "SELECT o.order_id , o.betalingsKenmerk , o.betaalMethode , o.tijdstipBezorging , o.datum"
                    + ", o.adres , o.huisnummer , o.postcode , o.woonplaats , o.landCode , o.extrainfo , o.opmerking"
                    + ", o.altEmail , o.voornaam , o.achternaam , o.bedrijfsnaam , o.telnummer , o.betaald , o.bezorgkosten"
                    + ", o.totaalExBzg , o.siteCode , o.opmerking"
                    + ", IF(o.transactieID = -1, 1,0) "
                    + "AS pickup, r.rest_id, TRIM(CONCAT(r.naam, ' ', r.filiaal)) AS restname"
                    + "FROM thuis.order o IGNORE INDEX(connectieid, doorberekenen)"
                    + "INNER JOIN connectie c IGNORE INDEX(methode)"
                    + "ON o.connectieId = c.id"
                    + "AND c.methode = 26 "
                    + "INNER JOIN restaurant r"
                    + "ON o.restaurantRest_id = r.rest_id"
                    + "WHERE o.datum >= TIMESTAMP(CURDATE())"
                    + "AND o.order_statusOrder_status_id = '1'"
                    + "AND o.order_statusOrder_device_id = ?"
                    + "AND o.doorberekenen = '1'"
                    + "AND ((o.bevestigingsId IS NULL OR o.bevestigingsId = 0) AND o.bevestigdDoor IS NULL)";

But I get an error:

[17-03-2015 10:20:57] [FATAL] [OrderCollector]
  Error : com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'thuis.order o IGNORE INDEX(connectieid, doorberekenen)INNER JOIN connectie c IGN' at line 1

I have tried this query on the database from Sql manager within netbeans and it works just fine, but when I try to retype it for java it just keeps giving out the error above.
I am unable to find the solution !
Comment: Thank you @marc_s for editing and I will pay more attention as to make sure it will not happen again !
Comment: add a backtick in order ` `
Comment: have you tried what @AbhikChakraborty mentioned. If Yes, please update.
Answer: You are missing a space
change
"FROM thuis.order o IGNORE INDEX(connectieid, doorberekenen)"

to
" FROM thuis.order o IGNORE INDEX(connectieid, doorberekenen)"

Without it restnameFROM becomes a single word and the FROM clause is not found.
Similarly you should add a space at the start or end of most of your lines.
This should work :
String Retrieve
                    = "SELECT o.order_id , o.betalingsKenmerk , o.betaalMethode , o.tijdstipBezorging , o.datum"
                    + ", o.adres , o.huisnummer , o.postcode , o.woonplaats , o.landCode , o.extrainfo , o.opmerking"
                    + ", o.altEmail , o.voornaam , o.achternaam , o.bedrijfsnaam , o.telnummer , o.betaald , o.bezorgkosten"
                    + ", o.totaalExBzg , o.siteCode , o.opmerking"
                    + ", IF(o.transactieID = -1, 1,0) "
                    + "AS pickup, r.rest_id, TRIM(CONCAT(r.naam, ' ', r.filiaal)) AS restname"
                    + " FROM thuis.order o IGNORE INDEX(connectieid, doorberekenen)"
                    + " INNER JOIN connectie c IGNORE INDEX(methode)"
                    + " ON o.connectieId = c.id"
                    + " AND c.methode = 26 "
                    + " INNER JOIN restaurant r"
                    + " ON o.restaurantRest_id = r.rest_id"
                    + " WHERE o.datum >= TIMESTAMP(CURDATE())"
                    + " AND o.order_statusOrder_status_id = '1'"
                    + " AND o.order_statusOrder_device_id = ?"
                    + " AND o.doorberekenen = '1'"
                    + " AND ((o.bevestigingsId IS NULL OR o.bevestigingsId = 0) AND o.bevestigdDoor IS NULL)";

Answer:
add a backtick in order  –  Abhik Chakraborty

Did the trick, but since you answered in a comment I can't accept it as an answer but thank you !
Query looks like this now :
String Retrieve
                    = "SELECT `o`.`order_id` , `o`.`betalingsKenmerk` , `o`.`betaalMethode` , `o`.`tijdstipBezorging` , `o`.`datum`"
                    + ", `o`.`adres` , `o`.`huisnummer` , `o`.`postcode` , `o`.`woonplaats` , `o`.`landCode` , `o`.`extrainfo` , `o`.`opmerking`"
                    + ", `o`.`altEmail` , `o`.`voornaam` , `o`.`achternaam` , `o`.`bedrijfsnaam` , `o`.`telnummer` , `o`.`betaald` , `o`.`bezorgkosten`"
                    + ", `o`.`totaalExBzg` , `o`.`siteCode` , `o`.`opmerking`"
                    + ", IF(`o`.`transactieID` = -1, 1,0) "
                    + "AS pickup, `r`.`rest_id`, TRIM(CONCAT(`r`.`naam`, ' ', `r`.`filiaal`)) AS restname"
                    + " FROM `thuis`.`order` o IGNORE INDEX(connectieid, doorberekenen)"
                    + "INNER JOIN `connectie` c IGNORE INDEX(methode)"
                    + "ON `o`.`connectieId` = `c`.`id`"
                    + "AND `c`.`methode` = 26 "
                    + "INNER JOIN `restaurant` `r`"
                    + "ON `o`.`restaurantRest_id` = `r`.`rest_id`"
                    + "WHERE `o`.`datum` >= TIMESTAMP(CURDATE())"
                    + "AND o.order_statusOrder_status_id = '1'"
                    + "AND o.order_statusOrder_device_id = ?"
                    + "AND o.doorberekenen = '1'"
                    + "AND ((o.bevestigingsId IS NULL OR o.bevestigingsId = 0) AND o.bevestigdDoor IS NULL)";

Comment: The reason for this is because `order` is a keyword in SQL.

Java : error in SQL syntax


MySQL convert into uppercase does not working

Question: I'm using MySQL PASSWORD() with manual way since its not working (deprecated) in MySQL 8
CONCAT('*', UPPER(SHA1(UNHEX(SHA1('PWD')))))

Uppercase Upper() conversion is not working with MySQL 5.7.
Any suggestions?
Comment: did you try 'UCASE(...)' ?
Comment: `SELECT CONCAT('*', UCASE(SHA1(UNHEX(SHA1('123456')))))` gives the same results. *6bb4837eb74329105ee4568dda7dc67ed2ca2ad9
Comment: They both work for me https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=e996e89045e3ad6210224aa77cdfc0d4
Comment: I'm getting the results with lower case
Answer: Be sure you are using the proper charset..

Returns the string str with all characters changed to uppercase
  according to the current character set mapping. The default is
  utf8mb4.

https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_upper
so check for you charset and eventually change the value you need in select
and just a suggestion if the bugs i related  to the nested  call try using a nested  subquery  eg:
select  concat('*', UPPER(t.col))
 from ( select SHA1(UNHEX(SHA1('PWD'))) col
) t

Comment: `SELECT UPPER('abc')` returns `ABC` but `SELECT CONCAT('*', UPPER(SHA1(UNHEX(SHA1('123456')))))` returns *6bb4837eb74329105ee4568dda7dc67ed2ca2ad9 in MySQL 5.7
Comment: @user12342428  .. i have add  a suggestion  hope is useful,..
Answer: Upper function inside another function is not working in some MySQL versions. Its a MySQL bug.
https://bugs.mysql.com/bug.php?id=12903


Relacionamento muitos para muitos com Asp.net MVC e Entity Framework

Question: Estou criando um projeto para estudar Asp.net MVC 5 junto com Entity Framework 6, e me deparei com uma grande dúvida em um relacionamento de muitos para muitos. Utilizei model gerado a partir da base de dados, e criei os controllers e views automáticamente pelo Visual Studio.
Em minha base de dados tenho o relacionamento de muitos para muitos entre a tabela Usuário e Projetos, o que resulta na tabela Equipe_Projeto como segue a imagem abaixo:

Essa tabela, como o próprio nome diz, está desenhada para armazenar os dados dos usuários que farão parte de algum projeto, ou de vários.
Ao criar o meu edmx em meu projeto do Visual Studio, a tabela Equipe_Projeto, não é criada nas classes models, e somente o relacionamento vai no edmx, como na imagem abaixo:

Logo, me deparo com a questão de como vou popular a minha tabela de Equipe_Projeto? Estou um pouco perdido aqui em como vou relacionar os meus usuários com os projetos, utilizando asp.net MVC?
No código do método Create do projeto tenho o código a seguir, e neste não há nada que relacione a tabela Equipe_Projeto:
// GET: Projeto/Create
public ActionResult Create()
{
    ViewBag.prioridade = new SelectList(db.prioridade, "prioridade1", "prioridade1");
    ViewBag.status = new SelectList(db.status, "status1", "status1");
    ViewBag.responsavel = new SelectList(db.usuario, "id", "nome");
    return View();
}

// POST: Projeto/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,nome,descricao,data_inicio,responsavel,prioridade,status")] projeto projeto)
{
    if (ModelState.IsValid)
    {
        db.projeto.Add(projeto);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    ViewBag.prioridade = new SelectList(db.prioridade, "prioridade1", "prioridade1", projeto.prioridade);
    ViewBag.status = new SelectList(db.status, "status1", "status1", projeto.status);
    ViewBag.responsavel = new SelectList(db.usuario, "id", "nome", projeto.responsavel);
    return View(projeto);
}

A grande dúvida é esta, como trabalhar com o relacionamento muitos para muitos, de forma que eu consiga inserir dados em mais de uma tabela ao mesmo tempo, no meu caso na tabela Projeto, e Equipe_projeto, definindo assim os usuários que fazem parte do projeto.
Obs: Eu tenho uma grande experiência já com projetos em WebForms, porém agora estou indo atras do aprendizado em asp.net mvc, entity framework e webapi.
Answer: A criação das tabelas por EDMX faz o Entity Framework configurar essa tabela associativa pela Fluent API, dentro do seu arquivo de contexto (uma classe que deriva DbContext). Por experiência própria, não recomendo usar desta forma por três motivos:

Não é claro como e em que momento o Entity Framework fará a associação pra você;
A associação não pode ser estendida, receber mais propriedades, regras, etc.
O seu exemplo já mostra que não existe Scaffolding (prototipação automática) da associação, e ela tem que ser feita manualmente.

O ideal seria você criar o Model Equipe_Projeto manualmente, associando Projeto e Equipe como 1 para N. Isto evita a confusão.
Além disso, não recomendo você continuar muito tempo nesta abordagem com o arquivo EDMX. Com o uso de Attributes, essa abordagem se torna rapidamente obsoleta.
Comment: @EricoSouza Usar Attributes em EDMX fica bem complicado. Eu faria toda a declaração de *Models* textualmente, por classe. Pode até não ser intuitivo no começo, mas o ganho que se tem com validação e regras de negócio com esse tipo de disciplina vale todo o esforço.
Comment: @EricoSouza Sim, são as melhores práticas em ASP.NET MVC e EF até então.
Comment: Valeu @CiganoMorrisonMendez, obrigado. Seguindo o seu conselho, vou criar o model manualmente e fazer a associação. Feito isso, eu altero o controller do Projeto para que ele também deva "enxergar" esta associação, assim inserindo na base de dados também os usuários que fazem parte do projeto. E qual maneira você me recomendaria na questão do uso de Attributes do edmx?
Comment: @CiganoMorrizonMendez, atualmente venho utilizando classes de metadados, nela tenho os Attributes, e validação e regras nela e não no EDMX. Você acredita que seja válido essa abordagem?


Spivak Caculus chapter 9 problem 27, about Derivatives and Induction

Question: Problem 27 states:
If $S_n(x)=x^n$, and $0\le k\le n$, prove that:
$$S_n^{(k)}(x)=\frac{n!}{(n-k)!}x^{n-k}$$
The answer book says:
Proof by induction on k. The result is true for $k=0$. If
$$S^{(k)}(x)=\frac{n!}{(n-k)!}x^{n-k}$$
then $$\quad\quad\quad S_n^{(k+1)}(x)=\frac{n!(n-k)}{(n-k)!}x^{n-k-1}\quad\quad\require{enclose}\enclose{circle}{1}$$
$$\quad\quad\quad\quad\quad\quad\,\, =\frac{n!}{[n-(k+1)]!}x^{n-(k+1)}$$
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I feel some process is missing in $\require{enclose}\enclose{circle}{1}$. I know it's true, because previous exercise asked to prove: $$ if:\quad S_m(x)=x^m, \quad\quad then:\quad S^{'}_m(x)=mx^{m-1}$$ Let $m=n-k$, is it sufficient to say "Rising $x$ to $-1$ power will multiply $n-k$ on its left." for $\mathbf {any\,\; higher-order}$ derivative?
Another question, should the induction require the result to be true for $k=1$,but not $k=0$?
I know the answer is right, but I missed something here. Thank you!
Answer: The idea is not to raise $x$ to $-1$. If you differentiate $x^{n-k}$, what you get is $(n-k)x^{n-k-1}$. That's all that is needed (and all that is used).
And the induction proof starts by proving that the statement holds when $k=0$. The other step is to prove that if it holds for a cetain $k$, it also holds for $k+1$.
Comment: Thank you so much! I got the first question. but still not sure if $k=0$ is proved it.
The text says: 1 is in A, and k+1 is in A whenever k is in A.
Comment: That identity, with $k=0$, is just $S_n(x)=\frac{n!}{(n-0))!}x^{n-0}$. Since $\frac{n!}{(n-0))!}x^{n-0}=x^n$, it is a trivial assertion.


What note is this on the piano?

Question: My daughter has to learn a song and she is stumped on a specific note: the D  note (re) with a # sign before:
Second note in the following picture:

Which key should she play that note with?
Comment: If her teacher hasn't even explained what the black keys are, get thee to a new teacher pronto!
Comment: Just curious, is your daughter playing white notes for the F, C, and G's in this piece or is she playing them as F sharp, C sharp, and G sharp (the black note just to the right of the notes mentioned??
Comment: @CarlWitthoft yeah, it just seemed that they don't know what a sharp is, based on the way the question was worded, so just making sure we are not missing all those sharps in the key sig.
Answer: Aryaman's answer answers the question - but with a question such as this, the following is important.
Yes, the note in question is D#, the black key which is the right-hand one of the two blacks together. However, that note is 'foreign' to the key - it's not in the key sig. So it needs to be shown with that accidental. That accidental then lasts for the rest of the bar, unless cancelled.
Therefore, the other D in that same bar needs to be played as D#, even though there's no other accidental.In other words, the last note in that bar is also D#. Any D notes in subsequent bars will revert to D nat. unless another # sign is added. It's a trap beginners can fall into.
Answer: Play C#, D#, E and D#
Points to remember:

Sharp/Flat that are preceding a note will override sharp/flat of key signature.
Sharp/Flat of a note will be continued till the end of the bar.
Answer: The question is a but unclear, but the first note (right above the p, and below the 2) is a C Sharp - even though there is no sharp next to it, there is a C Sharp in the Key Signature.
The note after that is the D Sharp - here, the sharp is added to that note in particular, and not the key signature.
Just in case you're unaware, the "Sharp" notes are (usually) the black, smaller keys in a piano. The C Sharp is between the C and D white notes, and the D Sharp is between the D and E white notes.
Answer: This D# is probably because this piece modulates from one key to another, sometimes you get a change of key signature but often modulations just use accidentals to indicate this.
Most probably in this piece, there is a modulation from the original key (A major) to the dominant key (E Major). This is reiterated by the D# resolving stepwise up which indicates it operates like the leading tone.
Comment: The D# could also come from a secondary dominant, in this case B Major, which would lead to the real dominant, E Major.
Answer: The # sign means sharp.  The sharp sign means to raise a note to the next higher note -- the one immediately to the right. Instead of playing the regular note, you'll play the next higher note instead.
Placing a # in front of a D note means to play D sharp, which is the black note immediately to the right of D on the piano.
Everything the other answers say about key signatures and sharps is correct. I merely added this answer because it seems that you (and your daughter), are unfamiliar with the term "sharp", so I wanted to explain that term to you.
Hope this helps!
Comment: OK I see. I wasn't attempting to insult her intelligence, just trying to answer as specifically as possible. Thanks for clearing up. In that case, i defer to my colleagues' fantastic answers. Welcome to Music SE!
Comment: Hi. She is familiar with the sign. Her problem was that at the beginning of the row there were also 3 sharp signs. And playing `re` sharp did not "sound right" ( her words) when she played the song. Thank you all for the kind answers
Comment: Sorry for not being too clear. I am a programmer and I feel I do not know all the facts (I have no artistic skills)
Comment: No worries! Do the other answers (Aryaman and Tim's) answer your question? If not I can attempt to clear it up further.

What note is this on the piano?


Finding a relation between the integral bounds?

Question:
If $a,b,c,d,u_1,u_2$ are real numbers, what is $\frac{u_1}{u_2}$?
I get that $\frac{u_1}{u_2} = \frac{b}{d} = \frac{a}{c}$ but apparently this is wrong and the answer is $\frac{b}{d}$.  Why?
Comment: What steps did you take to get your answer?
Comment: So what I basically did was rewrite the integrals as 2*integral(0,a/u1) + integral(a/u1, b/u1) for the first equation, then 2*integral(0,c/u2) + integral(c/u2, d/u2).  Then by inspection I just set a/u1 = c/u2 and b/u1 = d/u2
Comment: I don't see why equality of the integral sums in your comment implies the limits must match up. True, IF they match one gets equality of the integral sums...
Comment: Jason-- I've put up an answer in which I give what seems to be a case wherein the bounds don't match, and even the "answer" you mention (from a text?) doesn't hold. However IF that answer holds it is also $a/c$ as you mention.
Answer: Let the function $p(u)$ be the integral
$$p(u)=\frac{2}{\sqrt{\pi}}\int_0^u e^{-t^2}\ dt.$$
The two equal sums of integrals are then
$$p(a/(u_1))+p(b/(u_1))=y, \\ p(c/(u_2))+p(d/(u_2))=y. \tag{1}$$
The problems "answer" then says that it follows that $u_1/u_2=b/d.$ The latter is equivalent to $b/u_1=d/u_2.$ Now if this happens to hold, then from (1) we can get also
 $p(a/(u_1))=p(c/(u_2)),$ and then since $p(u)$ is injective we do get also $u_1/u_2=a/c$ (your other answer candidate).
However consider the following example: We take $p(.5)+p(2)=y=1.5158...$ and try for another equation $p(.6)+p(k)=y$ (the same $y$ as above). When calculated this means that $p(k)$ should be $.911966...$ and we have $p(1.206)=.911906...,\ p(1.207)=.91216...$ and thus by continuity there is a choice of $k$ between $1.206$ and $1.207$ for which we have
$$p(.5)+p(2)=y,\\ p(.6)+p(k)=y,$$
where $y$ is about $1.5158.$ To fit this into the original setup we can then have
$$a/u_1=.5,\ b/u_1=2,\\ c/u_2=.6,\ d/u_2=k=1.206...$$
But in this example we do not have $b/u_1=d/u_2,$ and so do not have what the answer claims, namely $u_1/u_2=b/d.$


Verificar a relação de dois objetos em uma lista

Question: Preciso extrair de um texto puro o total do valor de um acordo. Eu tenho centenas de documentos com alguns valores, e percebi que geralmente o maior valor é também o valor total do acordo, mas em alguns casos, não.
def ata_values(text):
    padrao = re.findall(r'\$\s*(\d{1,3}(?:\.?\d{1,3})+(?:\,\d{2})?)', text)
    padrao = [p.replace('.', '') for p in padrao]
    padrao = [p.replace(',', '.') for p in padrao]
    padrao = [float(p) for p in padrao]

    return padrao, max(padrao)

isso me retorna:
([2500.0, 833.33, 833.33, 833.34, 2500.0], 2500.0)
([1000.0, 800.0, 200.0, 1000.0], 1000.0)
([280.0, 14000.0, 21000.0], 21000.0)    21000.0)
([3000.0, 15000.0, 7000.0, 7000.0, 7000.0, 700.0, 700.0, 700.0, 700.0, 700.0, 700.0, 700.0, 700.0, 700.0, 700.0, 750.0, 750.0, 750.0, 1083.33, 1200.0, 1600.0, 1616.67, 140.0], 15000.0)

sendo a primeira lista padrao com todos os valores encontrados, e o segundo max(padrao) é o maior valor de cada lista. Neste exemplo as duas primeiras linhas estão corretas, mas as duas ultimas não, nessas o segundo maior é o correto. Percebi que na maioria das listas que tenho esse erro, existe um padrao, a lista contem o valor total mais um valor que corresponde a 2% do valor total.
Como eu poderia verificar antes de pegar os valores maximos, se existe dentro de cada lista um numero X mais um número que corresponde a 0.02*X?
for x in padrao:
    for y in padrao:
        if x == y*0.02:
            return x
        else:
            return max(padrao)

Comment: Na terceira linha o resultado esperado seria 14000 e 280 corresponde a 2% desse total. Na quarta linha o resultado esperado seria 7000 e 140 corresponde a 2% desse total
Answer: padrao.sort(reverse=True)
maior = padrao[0]
if maior* 0.02 in padrao:
   maior = padrao[1]

Mas como escrevi inicialmente como comentário: Bem arriscada essa abordagem - principalmente se os documentos são de texto livre. Será que não tem uma coisa mais consistente, ainda que seja mais difícil de achar com uma única expressão regular? tipo, aparece a palavra "total" próxima ao numero, ou numa sessão específica do documento, ou sempre próximo do final do documento? Nesse caso você primeiro isolaria um trecho onde deve aparecer o valor total e só depois se preocuparia em pegar o número.


Visual Studio 2015 Diagnostic Tools Memory Usage & C++ Debugging

Question: I have Visual Studio Enterprise 2015 and a native C++ project. I would like to analyze memory usage. Our software runs as a Windows service, so I typically debug by attaching to the running service. I found that when I do that the Diagnostic Tools Memory Usage is not available:

However, when I start the software through the debugger (by pressing F5) the Memory Usage tool shows up:

Is it supposed to be like that, ie. is the Memory Usage Diagnostic Tool not supported when attaching to a process?
The Memory Usage Diagnostic Tool is missing both when attaching to a locally running process as well as when remote debugging (attaching to a process on another machine).
Answer: The Diagnostic Tools native memory profiler will support attaching to a process in the upcoming Visual Studio 2015 Update 1.  There will be a CTP preview release coming out this Fall that you can try out.
Comment: Here is link to the Update 1 download that now supports profiling via attach to process: https://www.visualstudio.com/en-us/news/vs2015-update1-vs.aspx


what does "6/6 CI" mean in music sheet for guitar?

Question: I found this music sheet on the internet for my training to play classical guitar and now i'am confused what's "6/6 CI" mean in the music sheet? (Canon in D transposed to C for guitar)

UPDATE
Thankyou for your answer @Aaron, and one more question about this, is it true "C" to be used is in this screenshot? but the orange line move to fret number 1 because "I" on the 6/6 CI indicates fret 1 and "C" on the 6/6 CI indicates chord C and 6/6 mean press all strings, so "6/6 CI" is like chord "F" ?
Comment: To your question: Yes. The notes being played are F-F-A-C, which make an F major chord. However, the "C" in this case is not a chord symbol; it does not mean a C major chord. The "C" means to barre the strings. See the duplicate post for a complete explanation.
Answer: The notation indicates a barre.

"C" means that a barre is to be used ("B" is also sometimes used).
"6/6" means to barre all six strings
"I" means to barre at the first fret (it's a Roman number [i.e., capital] "I", rather than a lower-case "l".)


An accented or a non-accented passing tone?

Question: Okay, this might seem like a silly question, but I didn't find a quick answer through Google, so here it goes. I was just sketching a little pastiche in the style of Bach in the key of B minor. I started with the melody and added a bassline and harmonies underneath it. Usually I just listen and decide intuitively or based on the harmony if the melody note has a "pull" down/upwards, but I was wondering if there are any "rules" when one should treat note as an accented or as a non-accented passing tone in a two-part counterpoint setting.
In the image below, I was thinking if it would be weird to treat the C# as an accented passing tone and harmonize it with a D in the bass instead of E, which would then resolve down to B and form a nice 6th between bass and melody.
Comment: Regardless of the terminology, I think you'll find examples of both cadences in Bach's keyboard music.  You might be interested to compare the bass part of _Bist du bei mir_ in the manuscript orchestral score with that in Anna Magdalena's music book.  Sometimes the bass has ^1 ^4 ^5 ^1 in the keyboard version, but if I recall correctly the score (Stölzel's original version?) always has ^1 ^3 ^5 ^1.
Answer: The accented vs non-accented is just in reference to whether the passing note falls on the strong part of the beat or the weak part.
A non-chordal note on different parts of the beats give different effects. Depending on what the harmony allows and what effect the composer desires one could choose one over the other. Hence the distinction is made between two versions of essentially the same thing.
Answer: There aren't rules per se, but the solution presented makes the most sense in the given context.
In this case, the C# is an accented upper neighbor, since the harmony changes at that point. Had the remain-in-G-major option been chosen, then it would be an accented passing tone.


Pairwise Comparison of rows in a matrix

Question: I have a simulation code that produces a binary matrix in matlab always with 10 rows but a varying number of columns.
For example here:
 1     0     0     0
 0     0     0     0
 0     1     0     0
 1     0     0     0
 1     0     0     0
 1     0     1     0
 0     0     0     1
 1     0     0     0
 0     0     0     0
 0     0     0     0

I want to do pairwise comparision between the rows to determine how many elements are different between the two rows, ultimately to create a 10x10 symmetric matrix with the number of differences between the rows. Eg. Row 1 compared with Row 2...and so on.
So the (1,2) element (as well as the 2,1 element) of this matrix would compare row 1 with row 2 and would be 1 in this case as there is only a single difference.
I know this could be done with lots of loop coding, however feel there is likely a simpler way that I do not know of.
How should this be accomplished?
Answer: Without any look you can do:
A=[1 0 1; 0 1 1; 1 1 1 ; 0 0 0];
A*(1-A)'+(1-A)*A'
ans =
 0     2     1     2
 2     0     1     2
 1     1     0     3
 2     2     3     0

What it says is that a is different than b iff a=1 and b=0, or a=0 and b=1,
which is equivalent to a*(1-b)+b*(1-a).
Every entry in the result matrix holds the number of differences between rows (i,j). By performing matrix multiplication you calculate the above for every entry of any pair of rows, and sum up the results.

Pairwise Comparison of rows in a matrix


To detect and trigger event - Excel

Question: I have a barcode scanner. So when the barcode is scanned using a gun, the value normally is entered to textfield placed on the screen.
So I have made an excel macro. And when the barcode is scanned, the text appears on the cell ending with the new line character (text+"\r\n" is provided by the scanner itself). So an event is triggered and does the rest.
The problem is that the event is only triggered with a new line character. What if the barcode scanner didn't provide \r\n after every barcode output. How do I deal with such situations?
How do I detect it and trigger event?
Comment: from my (limited) work with bar code guns, there was a setting on the gun to determine if CR/LF was entered after the code. A bar code itself tends not to have new line characters
Comment: `SendKeys` could help simulate a return-key-press, triggering your event. Not sure how you'd detect input though.
Comment: @SeanCheshire but that again is hardware dependent. Telling/Explaining clients would be pain
Answer: If you create a userform to take the input, you can use the keydown or keypress events to detect keys pressed. You would have to know what the end condition of the barcode would be, so you know when to send the value to the cell to be processed.
Keydown will give you shift state, and also capture pageup/pagedown/other special keys
Private Sub UserForm_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
    ByVal Shift As Integer)

Keypress will only work with keys that produce a typeable character
Private Sub UserForm_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

Without userforms, you will have to rely on enter/newline to trigger the Change event in the worksheet
Answer: add a Worksheet_Change event as follows into the sheet module:
Private Sub Worksheet_Change(ByVal Target As Range)

    ' Add code here to check for
    ' new line and add if not present

End Sub

Or if you have the data in a Userform textbox then use the following:
Private Sub TextBox1_Change()

    ' Add code here to check for
    ' new line and add if not present

End Sub

Comment: this won't work when enter is not pressed. if the cell is still in edit mode, Worksheet_Change event is not fired, as `ESC` can still be pressed to abort the change
Comment: any update to the s/s will trigger the change event. Im not familiar with barcode machines and any edge cases but if the data is in a textbox of a userform you can use the change event of the textbox

To detect and trigger event - Excel


MongoDB Node JS - to delete an entry from an object inside a document object

Question: I'm trying to create a command in Node JS using native mongodb driver, to remove the key value pair from an object which is inside the document object.
I have a mongoDB collection in the following format:
    {
    "name" : "PrakashPM"
    "data" : {
               "Jan-2017" : "2,3,1",
               "Dec-2016" : "1,2,0",
               "Nov-2016" : "9,9,9"
             }
    },
    {
    "name" : "Valavan"
    "data" : {
               "Jan-2017" : "1,1,1",
               "Dec-2016" : "3,3,3",
               "Nov-2016" : "9,9,9"
             }
    }

My target is to remove "Dec-2016" : "1,2,0" which is inside "name" :
  "PrakashPM"

My Code:
var mongoName = 'PrakashPM';
var mongoDate = "'data'.'Dec-2016'";
// TRIALS
// var mongoDate = "data.'Dec-2016'";
// var mongoDate = "data.Dec-2016";

var mongoVal = "'1,2,0'";
// TRIALS
// var mongoVal = "1,2,0";

mycollection.update( { name: mongoName },
{ $unset: {mongoDate : mongoVal} }
);

NOTE: I'm doing the above operations inside a PUT request function.
I tried many possible ways (TRIALS) for the input values (mongoDate, mongoVal) but I'm not able to achieve the result below.
Also, is it possible to remove the key value pair entry, just by using the key? (i.e. in this case {$unset: {mongoDate}} or something like that)
EXPECTED RESULT:
    {
    "name" : "PrakashPM"
    "data" : {
               "Jan-2017" : "2,3,1",
               "Nov-2016" : "9,9,9"
             }
    },
    {
    "name" : "Valavan"
    "data" : {
               "Jan-2017" : "1,1,1",
               "Dec-2016" : "3,3,3",
               "Nov-2016" : "9,9,9"
             }
    }

Comment: Can you provide more sample of `req.body` content? Especially, what is the difference between `req.body.timerData` and `req.body.time`. Also what is `timerName` in your code?
Comment: Sorry for all the confusions. @SantanuBiswas I have edited the question with proper values. I'm able to retrieve the record using `find( {name: mongoName})` ; the problem is with the $unset condition or may be additional query in the first argument.
Comment: See my reply below. Figured out your problem and provided solution.
Answer: Assuming that req.body.timerDate has the month-date string value exactly as in MongoDB, this should work. (See documentation).
You have to use string as key. You cannot use variable names there.
// Assuming that req.body.timerDate
// has the month-date as stored in MongoDB (case-sensitive match)

var reqDate = "data." + req.body.timerDate;
var reqName = req.body.name;

var _unset = {};
_unset[reqDate] = "";

mycollection.update({ name: reqName }, { $unset: _unset })

Answer: Use the following example as a guide to updating your collection. You need to use the bracket notation to create your query and update documents i.e. you require an update operation which has the structure:
db.mycollection.update(
    { 'name': 'PrakashPM' },
    {
        '$unset': {
            'data.Dec-2016': ''
        }
    }
)

So, using the variables to construct the objects to use in your operation
var mongoName = 'PrakashPM';
var timerDate = 'Dec-2016';
var query = {};
var update = {'$unset': {}};
query['name'] = mongoName;
update['$unset']['data.'+timerDate] = '';

db.mycollection.update(query, update)

Answer: You are trying to use variables as keys in a object.
mycollection.update( { timerName: mongoName },
{ $unset: {mongoDate : mongoVal} }
);

This does not work as you expect and is a general JavaScript concept (not mongodb problem).
You are sending a query to mongo to update a row where the key "timerName" equals the content of the variable "mongoName".
But the proper key is "name".
Try this:
mycollection.update( { name: mongoName },
{ $unset: {data : mongoVal} }
);

Comment: Sorry, my bad. I have edited my question in order to avoid confusions. I'm able to retrieve the record using `find( {name: mongoName})` ; the problem is with the $unset condition. Even in your suggestion, instead of data, shouldn't it be `'data'.'Dec-2017'` or `data.Dec-2017`? BTW, my suggestions didn't work as well.


Is a slash chord the same as an Inversion?

Question: Say we have a C/G (C chord with G in the bass). Is this a Slash Chord or Second Inversion of C Major chord? Are slash chords and inversions the same exact thing?
Answer: Typically, yes: a slash chord is just an alternative way of notating an inversion.
C/G, as you said, means "a C-major chord with G in the bass," which is exactly the same as a C-major chord in second inversion.
But not all slash chords are understood as inversions. The notion of the "rock dominant," for instance, is a IV chord above V, or F/G in the key of C.


A question about merged Poisson process

Question: Question here:
Iwana Passe is taking a multiple-choice exam. You may assume that the number of questions is infinite. Simultaneously, but independently, her conscious and subconscious faculties are generating answers for her, each in a Poisson manner. (Her conscious andsubconscious are always working on different questions.) Conscious responses are generated at the rate $λ_c$ responses per minute. Subconscious responses are generated at the rate $λ_s$ responses per minute. Assume $λ_c \neq λ_s$. Each conscious response is an independent Bernoulli trial with probability $p_c$ of being
 correct. Similarly, each subconscious response is an independent Bernoulli trial with probability $p_s$ of being correct. Iwana responds only once to each question, and you can assume that her time for recording these conscious and subconscious responses is negligible.
All my solutions are based on the fact that conscious and subconscious responses form the merged Poisson process.
(a)
If we pick an interval of T minutes, what is the probability that in that interval Iwana will make exactly $r$ conscious responses and $s$ subconscious responses?
My solution: Because this is the merged Poisson process, so the probability when conscious happens    is $\frac{\lambda_c}{\lambda_c+\lambda_s} $ , similar for the subconscious. Thus the probability is $$ \binom{r+s}{r} \frac{(\lambda_c)^r(\lambda_s)^s}{(\lambda_c+\lambda_s)^{s+r}} $$
But the given answer is:
Since the conscious and subconscious responses are generated independently,
P($r$ conscious responses and s subconscious responses in interval $T$)
= P($r$ conscious responses in $T$)P($s$ unconscious responses in $T$) = $$ \frac{(\lambda_cT)^re^{-\lambda_cT}}{r!}\cdot \frac{(\lambda_sT)^se^{-\lambda_sT}}{s!}$$
I think that the total events are given, the interval T is not in the business.
Appreciate  if you help! Thanks!
A similar question:
Answer: What you wrote is $\textsf{Pr}(R=r\land S=s\mid R+S=r+s)$. What they wrote (and what the question asked for) is $\textsf{Pr}(R=r\land S=s)$. The latter depends on the interval, the former doesn't.
Comment: *If we pick an interval of T minutes*  I think it is the given condition. What's the wrong?
Comment: @standerQiu: I wouldn't consider that as a condition but as the specification of the random variables we're looking at. I guess you could interpret "pick" probabilistically in that sentence and consider it as a condition, but I don't see how that would change things -- you'd then just add that condition in both cases -- the main point would be the same, that you considered $R+S$ as given and they didn't.
Comment: They are different -- the given condition would not involve with time. How could I get out of the trap? It seems to be a language game..
Comment: @standerQiu: I'm afraid we seem to be talking past each other. Perhaps you could explain your question to a native English speaker and have them translate it?
Comment: Er... I don't know about any native speaker.. I am sorry, is that my English too awkward..? But I think I grasp your idea.. What I mean different is that you say **he main point would be the same, that you considered R+SR+S as given and they didn't.** .  I don't agree with you because if I do not treat *If we pick an interval of T minutes* as a condition, the time **T** would be involved
Comment: @standerQiu: Whether you think of $T$ as a condition or a part of the problem specification is just a conceptual difference; it doesn't change the fact that $T$ is involved. Their expression (involving $T$) is correct; it would still be correct if you wrote it as "$P (\text{$r$ conscious responses and $s$ subconscious responses}\mid\text{interval $T$ was picked})$" instead of "$P (\text{$r$ conscious responses and $s$ subconscious responses in interval $T$})$".
Comment: I add a similar question and given answer above. Could you see that? Because of that question, I am confused when to involve time..
Comment: Before that question, I also think what you think. lol..
Comment: @standerQiu: The two parts of that question correspond directly to the two calculations we've been talking about. In part (a), the total number of jobs is not given, and the answer will depend on the time interval (in this case given as three minutes). In part (b), the total number of jobs is given; then the time interval no longer matters and the probability (conditioned on the total number of jobs) depends only on the relative probabilities of the types of jobs.
Comment: @standerQiu: I think it might be a good exercise for you to derive that from first principles, i.e. not use the fact that we know the conditional probability won't depend on the time interval, but calculate it using the time-dependent unconditional probabilities and show that the time interval drops out when you conditionalise on the sum.
Comment: Oh! Thank you for you last comment!!!!!  Can I ask the last question? I used to think that *exactly r conscious responses and s subconscious responses* was the total number of jobs *r +s* given... But it seems not?
Comment: @standerQiu: I'm not sure I understand that question. If you're *given* that there are exactly $r$ conscious responses and $s$ subconscious responses, then you're also given the sum $r+s$ -- but that's not what's happening here -- the sum $r+s$ is given, and the question asks for the probability of that sum arising from exactly $r$ conscious responses and $s$ subconscious responses (as opposed to, say, exactly $r+1$ conscious responses and $s-1$ subconscious responses, which would have the same sum).
Comment: Oh!! I think that the *main idea* of the question is the probability **during a time interval** instead of **fixed exact job events**!!!! That's what you express. Thank you very much!!!!!!!!!!!!!! You are so nice and patient!!!!!!!!!!!!!!!!!

A question about merged Poisson process


Jump Menu Style Dropdown To External Links

Question: I'm attempting to create a jump menu of links to external websites, and I would like to be able to order the links within this menu differently depending on the organic group of the current user attempting to access it. So far I've tried to accomplish this using views with nodequeue, and have come somewhat close, but its beginning to feel like a dead end..
 Does any module(or combination of modules exist) which would allow me to accomplish this without having to write my own?
Ideally each will be able to reorder the links according to their personal preference and override the default ordering of links. but that is not essential at this point
Answer: you could create a node type link and a Views jump menu that loads said node types.
Comment: Please explain the process so that people except the OP can understand.
Comment: This was one of the first things I tried. I created a content type to try to do this already, however, views has NO option to use the Link field of node as a url in a jump menu..