Generic unboxing of boxed value types

Question: I have a generic function that is constrained to struct. My inputs are boxed ("objects"). Is it possible to unbox the value at runtime to avoid having to check for each possible type and do the casts manually?
See the above example:
   public struct MyStruct
    {
        public int Value;
    }

    public void Foo<T>(T test)
        where T : struct
    {
        // do stuff
    }

    public void TestFunc()
    {
        object o = new MyStruct() { Value = 100 }; // o is always a value type

        Foo(o);
    }

In the example, I know that o must be a struct (however, it does not need to be MyStruct ...). Is there a way to call Foo without tons of boilerplate code to check for every possible struct type?
Thank you.
Comment: Interesting question. The information is all there but there doesn't seem to be a way to "generically cast to derived". Very frustrating. Somebody mentioned dynamics (needs 4.5). And I wonder whether one could construct something with expression trees.
Answer: .NET Generics are implemented in a manner that allows value types as a generic type parameter without incurring any boxing/unboxing overhead. Because your're casting to object before calling Foo you don't take advantage of that, in fact you're not even taking advantage of generics at all.
The whole point of using generics in the first place is to replace the "object-idiom". I think you're missing the concept here.
Whatever type T happens to be, it is available at run-time and because you constrained it to struct guaranteed to be a struct type.
Your TestFunc could be written like this without problem:
public void TestFunc()
{
    MyStruct o = new MyStruct() { Value = 100 }; // o is always a value type

    Foo<MyStruct>(o);
}

Looking at Foo, it would look like this in your example:
public void Foo<T>(T test)
    where T : struct
{
    T copy = test; // T == MyStruct
}

EDIT:
Ok, since the OP clarified what he wants to call the generic method but doesn't know the type of his struct (it's just object). The easiest way to call your generic method with the correct type parameter is to use a little reflection.
public void TestFunc()
{
    object o = new DateTime();

    MethodInfo method = this.GetType().GetMethod("Foo");
    MethodInfo generic = method.MakeGenericMethod(o.GetType());
    generic.Invoke(this, new object[] {o});

}
public void Foo<T>(T test)
    where T : struct
{
    T copy = test; // T == DateTime
}

Comment: But what if I don't know that o will be a MyStruct? It could by any struct or value type? TestFunc is only an example, in my application the data comes from a Dictionary where the value can by anything. However, I know that it must be a struct and therefore I would want to call Foo without checking for the concrete type.
Comment: But why do you need the concrete type? The point of using generics is to abstract away from the concrete type. Do you need to cast an object to the concrete type or what? Then you'd need to look into casting by example.
Comment: I do not need the concrete type, but since I can not cast to "struct" I need to know the concrete type to call Foo().
Comment: You can use reflection to do that (see above).
Comment: @Johannes: yeah, I thought about this, too. This will actually work like the OP wants. But is this a proper solution? I dont think so. There must be a better way, but since we dont know his intention/goal that is hard to tell...
Comment: Thank you! In my case this is a working solution. Not pretty, but if it saves me a lot of unnecessary code, it will do :)
Comment: Thank you SO much Rudolph. I had begun to think I found C#'s limits. I love your reflective approach (should have known reflection solves all in C#)! It cured the ache in my head ;)
Answer: No; you're using object, which is (by definition) not a struct/value type. Why are you intentionally boxing the value in this way?
Comment: @sluromatic: I can see the difficulty, then. Unfortunately, there is no way to do what you're trying to do without knowing the actual concrete value type.
Comment: All my values are stored in a Dictionary, if I could have a Dictionary I would be glad to use that :) I am not "intentionally" boxing the value in my real application, this was just a simple example.
Comment: No, you can use a little reflection magic (see my answer below).
Answer: The whole point of using generics is to avoid situations like this.
When you actually "close" the generic with a type of struct, you eliminate the need for runtime type checking: ie.
Foo<MyStruct>(MyStruct test);

Your implementation of Foo, can safely assume that it's dealing with a struct.
Comment: Yes, but I don't know that is a MyStruct, I only know that it is a struct. It can be MyStruct2, MyStruct3, int, char, etc.
Comment: Exactly, in those cases you'd make the call as Foo(MyStruct2 test) Foo(MyStruct3 test) etc... I'm not entirely sure why you'd use generics just to work around their main feature (design time type parameterization)
Comment: Ok, example. I have a generic class Value but also an interface IValue (compare to List and IList). I know that all my IValues are some concrete version of Value. But in order to call any methods of Value I have to cast to the concrete type, e.g. Value, Value etc.
Answer: (Marked as CW because you can't pass an instance of ValueType to a generic requiring a struct, but it might be helpful for others who come across this question).

Instead of declaring o as an object, you can use a type of System.ValueType, which can only be assigned struct values; you cannot store an object in a ValueType.
However, I'm honestly not sure if that does anything in terms of (un)boxing.  Note that ECMA-334 11.1.1 says:

System.ValueType is not itself a value-type. Rather, it is a class-type from which all value-types are automatically derived.
Comment: Any instance of `ValueType` is, ironically, a reference. This won't work for generics restricted to value types.
Answer: I dont know exactly what you are trying to archieve, but you could pass a delegate/lambda to unbox the value, and select some value in the struct you are interested in:
(Updated this code snippet after slurmomatics comment)
public void Foo<TValue>(object test, Func<object, TValue> ValueSelector)
           where TValue : struct
{
    TValue value = ValueSelector(test);

    // do stuff with 'value'
}

public void TestFunc()
{
    object o = new MyStruct() { Value = 100 };

    // Do the unboxing in the lambda.
    // Additionally you can also select some
    // value, if you need to, like in this example
    Foo(o, x => ((MyStruct)x).Value);
}

Update:
Then do this:
public static void Foo<TUnboxed>(object test)
                     where TUnboxed : struct
{
    try
    {
        TUnboxed unboxed = (TUnboxed)test;
    }
    catch (InvalidCastException ex)
    {
        // handle the exception or re-throw it...
        throw ex;
    }

    // do stuff with 'unboxed'
}

public void TestFunc()
{
    // box an int
    object o = 100;

    // Now call foo, letting it unbox the int.
    // Note that the generic type can not be infered
    // but has to be explicitly given, and has to match the
    // boxed type, or throws an `InvalidCastException`
    Foo<int>(o);
}

Comment: Hm, no. I still have the same problem that I have an object o, not a MyStruct o. I know that is has to be a struct at runtime but I do not know the concrete type at compile time.
Comment: Ok, thanks. The problem however remains. I don't know that is is an int (or MyStruct etc.), I only know that is a value type (struct).
Comment: @slurmomatic: You dont know the type of the variable? Maybe you should rethink your design? Of course you could play around with the reflector, but is that really a proper solution? I dont think so.
Comment: @slurmomatic: BTW: what do you want to do in that generic function, what does 'do stuff' stand for?
Comment: I want to write a function that works with all structs. I know that I am providing a struct, I just don't know what concrete type (which may even be defined in a different library).
My application is to upload a data array onto the GPU, the data may be any value type. I don't care which type.
Comment: @slurmomatic: Ok, but what do you do with the struct then if you have unboxed it out of the object? I mean, you dont know what type the struct is of!? Sorry for the dumb questions, but I still dont get your intention. Maybe I could help you then.

Generic unboxing of boxed value types


How to avoid Battuta in this case of first species counterpoint

Question: In this exercise on first species counterpoint, the top melody is the cantus firmus and the bottom one my counterpoint.
I am not a musician and just learned the rules. This is the second exercise from this website.
The annotation "battuta" was generated by Sibelius' review plug-in for checking first species counterpoint.
The following is my question, that probably comes from me misunderstanding the rules.
Question: How to avoid battuta for this cantus firmus?
Here is what I thought. The cantus firmus ends in D. So, I end the counterpoint on D an 8ve lower. (I am not sure if there are other options. Perhaps unison?) The cantus firmus approaches the last note from above. If I put the counterpoint melody to approach the last note from above, we would have a similar motion landing on an 8ve. I think this would give a hidden 8ve.

Edit: Yes, in this linked question there is the definition of battuta. This is, an 8ve approached by contrary motion from outside, from a larger interval. This is the reason why I don't know how to avoid it in this exercise. To avoid it, my counterpoint melody would have to arrive to D from above, but then we get to an 8ve from similar motion, which is hidden 8ve.
So, I must be wrong in thinking that I cannot transgress one of these rules:

battuta
hidden 8ve
End with an 8ve or unison.

Edit: I will try something like ending with CBAAD. However, I think that using exactly this ending would produce successive jumps E3, A3, C4 in measures 5 to 7.
Comment: Welcome! Wow, I'm learning something new today. I *think* [this](https://music.stackexchange.com/questions/10870/meaning-of-battuta-in-counterpoint) ought to clear it up; if not, please edit this question to talk about what that one leaves unclear.
Comment: Note, Sibelius might be misapplying the term. I'm seeing some differing definitions, but most involve one of the voices moving by leap while one moves stepwise.
Answer: It's fine to end on a unison. Throughout these kinds of exercises, it's best practice to keep the two parts within an octave of each other (though a tenth is not out of the question), and ending on a unison is a standard option.
By making them an octave apart in this case, it's unavoidable that one runs into battuta, parallel octaves, or hidden octaves or fifths.
Answer: Note that you have more than one choice in how to write such a counterpoint. Just try not to let the second voice get this low towards the end. E.g. after note 6 (A in the second voice you could do C B A A D.


Back to login screen from any subview of navigation controller

Question: I am using navigation viewController for Swipping between viewControllers.
I have a  logout  button on a subview of navigation controller. How can i go back to login screen when clicked on  logout  button?
Note : .xib file contains only two place holders

File's owner
First Responder
Answer: If your loginViewcontroller is rootviewcontrollerand and you have only oneNavigation controller` to reach particular view then in that particular view you can write on logout button's click,
   self.navigationController?.popToRootViewControllerAnimated(true)

If you have two NavigationController between to reach that view then,
 self.navigationController?.navigationController?.popToRootViewControllerAnimated(true)

Likewise you can handle multiple navcontroller also.
Answer: Assuming the very first view in your navigation controller is the login view controller, you can do:  navigationController!.popToRootViewControllerAnimated(false)
Comment: Yes, login controller is initial view controller. but this line of code is not working for me. Any suggestion please?
Answer: If your Login controller is root controller then you can move like this
self.navigationController?.popToRootViewControllerAnimated(true)

else
//Move to login view
let viewControllers = self.navigationController?.viewControllers as NSArray!
for vc in viewControllers {
    if vc.isKindOfClass(LoginViewController.classForCoder()) {
        self.navigationController?.popToViewController(vc as! UIViewController, animated: false)
        break
    }
}

Comment: how can i make login viewController as root controller?
Comment: Make root view controller : http://stackoverflow.com/questions/15774003/changing-root-view-controller-of-a-ios-window, http://stackoverflow.com/questions/22653993/programatically-change-rootviewcontroller-of-storyboard


ROC for more than 2 outcome categories

Question: How do you construct ROC Curves when there are more than two outcome categories (in my case, I have four)?  I've heard you should do this for the most popular group. Are there any other ideas? Are there functions in R to help with this?
Comment: What about ROC curves makes them insightful to you?  Are you really interested in concordance probabilities ($c$-index; ROC area; pure discrimination measure)?  I find the ROC area to be helpful even though the curves are not helpful to me.  And you can generalize the idea of concordance probability to multiple categories using Somers' $D_{xy}$ rank correlation coefficient.
Comment: Do you mean how to construct ROC's when there are +2 **models**?
Comment: Or do you mean that there are 4 outcome categories?
Comment: Categories :) I edited my post
Comment: I would suggest checking out this answer: http://stats.stackexchange.com/questions/38541/creating-roc-curve-for-multi-level-logistic-regression-model-in-r
Comment: Nice one @FrankHarrell . ROC Curves are a great way to visualize how good are your classifiers if you put many of them on 1 plot :)
Comment: How does that give you any insight?
Comment: The Higher the Curve is, the better the classifier is
Comment: How does the area under the curve not capture that?
Comment: It does not capture the situation You chociaz the cut argument. Even the AUC is Higher from one Curve it does not mean there exists an argument from lover-auc Curve that Give Higher value of ROC Curve :p I think it's how's more than AUC. But it might be only my opinion.
Comment: I haven't seen an example yet where someone viewed an ROC curve and it led to an action that was both useful and correct.
Answer: Several ideas and references are discussed in:

A simple generalization of the area under the ROC curve to multiple class classification problems.
Multi-class ROC (a tutorial) (using "volumes" under ROC)

Other approaches include computing

macro-average ROC curves (average per class in a 1-vs-all fashion)
micro-averaged ROC curves (consider all positives and negatives together as  single class)

You can see examples in some libraries like scikit-learn.
See also this other thread in CrossValidated:
How to compute precision/recall for multiclass-multilabel classification?
Comment: FYI - the link to the multi-class ROC tutorial doesn't work
Comment: @rocinante Fixed.
Comment: @Josh that's the vast and outstanding piece of literature :) Thank you very much. That was something I was looking for! CV is a great place.
Answer: One of the ideas is to use one-vs-all classifier. This answer gives move information about it, including some R code.
Here's a plot from that answer
Comment: Very usefull comment. Thanks for that! Nice idea by the way.

ROC for more than 2 outcome categories


error r: invalid subscript type "closure" in a simple regression

Question: unfortunately i am a beginner in r. I d like to run a simple linear regression model in r with the comand lm, but every time i try the following error occurs:

Error in xj[i] : invalid subscript type 'closure'

The regression model ist just as follows:
REG1 <- lm(flowpercent~ret+tna+fundage+number_shr_cl,data = reg, na.omit)
 #-flowpercent is a calculated variable:

reg$flowpercent <- reg$flow_dollar/lag(reg$tna, n=1)

 #-fundage is also calculated:

reg$fundage <- as.numeric(difftime(ref_date,reg$InceptionDate, units = "days")/365.25)

ret, tna, number_shr_cl are variables from a database
hopefully some can help me to solve my problem.
Many thanks in advance.
Comment: what's in `reg` ?
Comment: reg is the name of the data.frame.
Comment: Welcome to SO. Please read [mcve] and [ask] so as to create questions that the helpful people here can easily answer. Luckily, in your case, I can guess what has happened and have answered it anyway.
Answer: Your third argument is na.omit. You probably saw someone writing something like na.action = na.omit. However, if you look up the help for lm by typing ?lm, you will see:
Usage:

     lm(formula, data, subset, weights, na.action, ... # etc

which tells you that the third argument to lm is subset. So, you are passing the object called na.omit to the subset argument, which lm tries to use to subset your data.  Unfortunately, na.omit is an R function (aka a "closure"). Not surprisingly, R does not know how to use this function to subset your data. Hence the error.


How to get the unselected population in python random module

Question: So, I know I can get a random list from a population using the random module,
l = [0, 1, 2, 3, 4, 8 ,9]

print(random.sample(l, 3))
# [1, 3, 2]

But, how do I get the list of the unselected ones? Do, I need to remove them manually from the list? Or, is there a method to get them too?
Edit: The list l from example doesn't contain the same items multiple times, but when it does I wouldn't want it removed more than it's selected as sample.
Answer: Because your list can contain multiple same items, you can change to the approach below:
import random

l = [0, 1, 2, 3, 4, 8 ,9]

random.shuffle(l)
selected = l[:3]
unselected = l[3:]

print(selected)
# [4, 0, 1]
print(unselected)
# [8, 2, 3, 9]

Comment: The problem is that the list can contain multiple same items if selected once I would want them removed only once not all of them. And, I can use for loop and list's remove method for that but I was looking if there was already a method to do that.
Answer: l = [0, 1, 2, 3, 4, 8 ,9]
s1 = set(random.sample(l, 3))
s2 = set(l).difference(s1)

>>> s1
{0, 3, 8}

>>> s2
{1, 2, 4, 9}

Update: same items multiple times
You can shuffle your list first and partition your population after in two:
l = [7, 4, 5, 4, 5, 9, 8, 6, 6, 6, 9, 8, 6, 3, 8]

pop = l[:]
random.shuffle(pop)

pop1, pop2 = pop[:3], pop[3:]

>>> pop1
[8, 4, 9]

>>> pop2
[7, 6, 8, 6, 5, 6, 9, 6, 5, 8, 4, 3]

Comment: Yes! Using shuffle and pop to make the same effect is a clever idea!
Answer: If you want to keep track of duplicates, you could count the items of each type and compare the population count to the sample count.
If you don't care about the order of items in the population, you could do it like this:
from collections import Counter
import random

population = [1, 1, 2, 2, 9, 7, 9]
sample = random.sample(population, 3)
pop_count = Counter(population)
samp_count = Counter(sample)

unsampled = [
    k
    for k in pop_count
    for i in range(pop_count[k] - samp_count[k])
]

If you care about the order in the population, you could do something like this:
check = sample.copy()
unsampled = []
for val in population:
    if val in check:
        check.remove(val)
    else:
        unsampled.append(val)

Or there's this weird list comprehension (not recommended):
check = sample.copy()
unsampled = [
    x
    for x in population
    if x not in check or check.remove(x)
]

The if clause here uses two tricks:

both parts of the test will be Falseish if x is not in check (list.remove() always returns None), and
remove() will only be called if the first part fails, i.e., if x is in check.

Basically, if (and only if) x is in check, it will bomb through and check the next condition, which will also be False (None), but will have the side effect of removing one copy of x from check.
Comment: Thanks for explaining it in this much detail, really appreciate ya.
Answer: You can do with:
import random

l = [0, 1, 2, 3, 4, 8 ,9]

rand = random.sample(l, 3)
rest = list(set(l) - set(rand))

print(f"initial list: {l}")
print(f"random list: {rand}")
print (f"rest list: {rest}")

Result:
initial list: [0, 1, 2, 3, 4, 8, 9]
random list: [2, 9, 0]
rest list: [8, 1, 3, 4]


adicionar um ouvinte no editText

Question: como eu faço para fazer uma ação ser executada, toda vez que o usuário digitar alguma letra no editText, pesquisei mas não achei oque queria, se alguém souber pelo menos uma dica de como pesquisar já ajuda
Answer: No seu EditText você faz adiciona o método addTextChangedListener() da seguinte forma:

package genesysgeneration.svg;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        EditText editText = (EditText)findViewById(R.id.editText);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                //aqui você executa uma determinada ação antes da modificação do editText

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                //aqui você executa uma determinada ação durante a modificação do editText

            }

            @Override
            public void afterTextChanged(Editable s) {

                //aqui você executa uma determinada ação depois da modificação do editText

            }
        });

    }
}

Nele você tem 3 opções para a execução de uma ação, antes do edtText ser modificado, durante e depois. Você escolhe um dos três de acordo com a sua necessidade.

adicionar um ouvinte no editText


How can I rebuild node / view cache based on the contents of an entityqueue

Question: I have
Content types:

front_banner
news

Entity Queues:

front_banner -> only ever contains one front_banner node
news -> contains multiple news nodes

Views:

front_banner -> displays rendered nodes (default)
news -> displays rendered nodes (teaser)

The front banner content type has a field in it that determines whether the text colour should be light or dark when display (sets a class in the twig template, works fine).  The news content type also makes use of the front_banner's overlay style field like so:
function mymodule_preprocess_node(array &$vars) {
  if ($vars['node']->bundle() == 'news'){

    // Set the overlay class (dark/light).
    $entity_subqueue = \Drupal::entityManager()->getStorage('entity_subqueue')->load('front_banner');
    $items = $entity_subqueue->get('items')->getValue();
    $front_node = node_load($items[0]['target_id']);
    $vars['overlay_class'] = $front_node->get('field_overlay_style')->getString();
  }
}

All of this works perfectly well, my problem occurs when I alter the front_banner node or entityqueue: the cache is obviously not set to refresh for news items when that occurs.
1. Which render cache do I need to rebuild?
Is it the view cache? or the node's render cache? or both?
2. How can I do it?
I have tried creating my own cache tag and flushing it like so:
function mymodule_entity_presave(EntityInterface $entity) {
  $tags = ['entity_type:' . $entity->getEntityTypeId() . '.' . $entity->bundle()];
  Cache::invalidateTags($tags);
}

function mymodule_node_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if ($build['#node']->bundle() == 'news'){
    //dpm($build);
    $tags=['entity_type:node.front_page_banner', 'entity_subqueue:front_banner'];
    $build['#node']->addCacheTags($tags);
  }
}

(entity_subqueue:front_banner tag is provided by the entityqueue module)
I cannot get the news node page itself to change the overlay style, nor can I get the view that displays news nodes to change the overlay style when the front_banner node is saved.

[Edit 1:] I looked into Views Custom Cache Tags - this does allow me to state which tags I want to affect the views cache - I tried putting the two relevant tags in my view to no effect.  Perhaps this means it's the node cache that is giving me grief?
Comment: You can give a try to [Views Custom Cache Tags](https://www.drupal.org/project/views_custom_cache_tag) module. The module allows to add custom tags to views which can be invalidated programatically during hook_node_presave() as per mentioned on project page.
Comment: Thanks for the tip, I should have included that attempt in my question, edited.
Comment: You can disable the content type cache ie news content type cache programatically as well you can disable views cache of news from views UI
Comment: You are using a different (set of) tags in invalidateTags then you attached to your view. Guess that's your mistake.
Comment: I can assure you that `'entity_type:' . $entity->getEntityTypeId() . '.' . $entity->bundle()` renders down to `entity_type:node.front_page_banner`, and that `entity_subqueue:front_banner` is provided by the entityqueue module.  Can you elaborate if I'm missing something else?
Answer: Every view that lists nodes is tagged with node_list and will be invalidated when a node is added, changed or deleted, so you don't need to worry about adding your nodes to the view.
But you do need to add the entity_subqueue tag to your view's cache tags, and you need to add the entity_subqueue tag and banner content type to your news content type's build array.  I haven't tested the way you're adding it, but I know you can add cache tags to a node in hook_entity_view:
  function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

      if ($entity->bundle() == 'news') {

        $tags = ['entity_type:node.front_page_banner', 'entity_subqueue:front_banner'];
        $build['#cache']['tags'] = array_merge($build['#cache']['tags'], $tags);

      }
    }

I know this is similar to what you were doing, but need to add it to the build array, not the node object.
Then you need to add the entity queue to the build array of your view
function mymodule_views_pre_view(ViewExecutable $view, $display_id, array &$args) {

  if ($view->id() == 'news' || $view->id() == 'front_banner') {
    $view->element['#cache']['tags'][] = 'entity_subqueue:front_banner';
  }
}


Why my poly lines are not perfectly drawn on the road of google map in android?

Question: I was trying to draw a poly line on the road but it gets deviate from the road and the poly line draws over the building near by the road.After a long search I got this link ("snap to road").where I need to send the set of latitude and longitude with pipe line separator along with the road api and it will return the accurate lat long which near to the road points.But I just want to draw on live which mean every single lat long should be accurate.
<code>  HashMap<String, String> map = new HashMap<String, String>();
  map.put(Constants.URL,"https://roads.googleapis.com/v1/snapToRoads?path="
      +d + "," +e+"&key=API KEY");
</code>
What I did is I'll call the road api whenever the lat long get changes on my android mobile so it will return the accurate lat long to me but there is a limitation in google that I can only request the api up to 2500/day requests.
So is there any alternate way to achieve my requirement?.
Comment: SnapToRoad simply find the nearest road coordinates and return. Is this what you need? What are you trying to achieve?
Comment: yes it returns me the nearest road co ordinates..it is working perfect my question ,is there any way to get the perfect co ordinates without calling the road api,why google is not giving the perfect co ordinates internally?like any specific jar or any lib?
Comment: Could you please specify what are you exactly trying to achieve?
Comment: ya sure...I am getting latitude and longitude from location manager which is not accurate so my poly line went off from the road.Now my poly lines are perfect when i pass the current lat long to the snap to road api which returns the perfect road co-ordinates and then I will draw poly line accordingly.Here I don't want to call the road api to get the perfect co ordinates.Is there any alternate solution to achieve nearest road co-ordinates?
Comment: Does your location manager getting location fix from GPS only?
Comment: yes..poly line are not perfectly drawn..
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/98813/discussion-between-muhammad-babar-and-asif-sb).
Answer: This might help you, I wrote an extensive answer for someone who had the similar issue with. Check it out, hope it would help you too
https://stackoverflow.com/a/11357351/975959
Comment: I think your url is almost close to my requirement..but my question there is no api required to call to get the nearest road co-ordinates?


How can I make a pop up stop appearing after a user clicks the link?

Question: I've used JavaScript to set a cookie when the user clicks on the popup notice but after closing the browser completely, the cookie expires and the notice is shown again when navigating to the page.
I want the user to have the option to essentially say "Don't show this again".
1) Is there a better way to do this like saving the data to the db?
2) Can I set the cookie so it doesn't expire when the window is closed?
Here is the code to set the cookie. If cookie isn't set to "visited" it calls another function to showLightBox().
$j(document).ready(function() {

        $j(function() {
                    checkCookie();

                });

        function checkCookie() {
                var hasVisit = getCookie("hasVisited");

                if(hasVisit != "visited") {
                    showLightBox();
                }
        }

        function getCookie(c_name) {
            var c_value = document.cookie;
            var c_start = c_value.indexOf(" " + c_name + "=");

                   if (c_start == -1)
                   c_start = c_value.indexOf(c_name + "=");

           if (c_start == -1)
           c_value = null;
           else
          {
              c_start = c_value.indexOf("=", c_start) + 1;
              var c_end = c_value.indexOf(";", c_start);
              if (c_end == -1)
              c_end = c_value.length;

                   c_value = unescape(c_value.substring(c_start,c_end));
          }
            return c_value;
        }

        function setCookie(cookieName, value) {

            document.cookie = cookieName + "=" + value;
        }

Comment: How are you setting the cookie?
Comment: Sure your way to create the cookie is not totally correct. Cookies should be set to live for many days.
Comment: http://www.w3schools.com/js/js_cookies.asp
Comment: Just updated my question.
Comment: There is [tag:jquery] plugin for cookies.
Comment: Why dont you use server side scripting for this(PHP) ?
Answer: Did you by any chance use a session cookie? they expire when you close the browser.
You can continue reading here :
Why cookies dont expire after closing browser?
Answer: You can set the date when the cookie will be expired like this.
document.cookie="username=suman; expires=Thu, 18 Dec 2020 11:00:00 GMT";

Now this cookie will be deleted on 18th dec 2020. By default the cookie will be deleted when your browser is closed.
Update:-
In your case the cookie will set with the date on which it will be expired.
function setCookie(cookieName,value){
    document.cookie = cookieName+"="+value+"; expires=Thu, 18 Dec 2020 11:00:00 GMT";
}

You may put any date you want at date field.
Answer: You are probably not setting an expiration for the cookie, so it defaults to a session cookie that expires on browser close.
If you are already using jQuery I recommend using the wonderful jQuery Cookie plugin, which makes setting and retrieving cookies a total piece of cake.  See the readme/documentation for details and enjoy only having to write a couple lines of code instead of 50.
Answer: Why don't you use localStorage in html5 for achieving this since it is persistent,
Like when a user clicks on the link for the first time set the flag
localStorage.setItem('clicked', "yes");

Then again check if this value is set,
   if(localStorage.getItem('clicked')!=null){
     //clicked
   }
   else
   {
    //not clicked
   }

If this value is set then show "Don't show this again" else don't ...


USB sound card's microphone does not pick up anything from amplifier

Question: So here's my setup right now. My electric guitar is connected to my amplifier using the standard 1/4" jack cord. The amplifier has a 1/4" headphone socket at the back, and I connected it to a USB sound card using another 1/4" jack cord with a 1/4" to 3.5mm adapter. The end with the adapter is then plugged into a USB sound card and the USB sound card is plugged into my computer.
In short, electric guitar --> amplifier --> adapter --> USB sound card --> computer.
I'm using Audacity to record, and the input setting is set to "Microphone (USB Audio Interface)" which I'm assuming is the USB sound card. I tried to record, yet the sound card did not pick up anything.
Link to the specs of the sound card I'm using: http://www.cdrking.com/?mod=products&type=view&sid=13986&main=154
Can anyone identify what's wrong with my setup? I tried plugging in the sound card into different USB ports and it's registered in Audacity, it really just doesn't pick up anything. I'm just starting to get into recording and don't have much experience with this side of music. Thanks in advance.
Comment: We need to know WHAT USB audio interface you have.
Comment: press Ctrl + p in audacity to open your preference. You'll find the interface option. Check if your sound card is in the list.
Answer: The "USB soundcard" is not exactly the hottest thing to be had.  It has a microphone input and a headphone output: those are Skype quality.  I presume that you plugged your amp's headphone output into the microphone input because otherwise you trivially cannot hear a thing.
Now the levels of the headphone output are not exactly compatible with microphone input levels here, and the microphone input will likely carry "plugin power" that the headphone output will not be overly happy with (basically, if it has electrolytic output capacitors, those will likely be reversely biased which is pretty bad news for their longevity).
However, if anything I'd expect the headphone levels to be higher than what the microphone input expects.  So you should be hearing something.
You might want to do yourself a favor and get yourself a proper USB sound card with proper microphone inputs (those have XLR inputs, not 3.5mm phone jacks) and possibly a DI box for getting from amp to USB sound card.
Line inputs on such a soundcard are usually 6.3mm phone jacks but not stereo connections (like your headphone socket) but rather balanced connections.  That's not straightforward to wire properly either without a DI box in between.
Does your amp really only have a headphone output?


If $x^2+y^2 \equiv 0\pmod{p}$, then $p \equiv 1 \pmod{4}$

Question:
Prove that if $x^2+y^2 \equiv 0\pmod{p}$ where $p$ is a prime and $x,y$ are not both divisible by $p$, then $p \equiv 1 \pmod{4}$.

I tried using that $x^2 \equiv -y^2 \pmod{p}$ and conjectured that $-1$ must a quadratic residue modulo $p$, but I am not sure how that would help.
Comment: Possible duplicate of http://math.stackexchange.com/questions/1843150/prove-that-if-p-equiv-3-pmod4-then-x2y2-not-equiv-0-pmodp.
Comment: @Puzzled417 Not to be harsh, but that one is pretty available via the magic of Google.
Comment: See http://math.stackexchange.com/questions/122048/1-is-a-quadratic-residue-modulo-p-if-and-only-if-p-equiv-1-pmod4
Comment: How do I rigorously prove that $-1$ must be a quadratic residue modulo $p$?
Answer: Since $p \not \mid y$, there exists integer $y'$ such that $yy' \equiv 1 \pmod p$. Then multiply both side of the congruence with $y'$ to get that:
$$(xy')^2 \equiv -(yy')^2 \equiv - 1 \pmod p$$
So hence $-1$ is a quadratic residue modulo $p$. To prove that $p \equiv 1 \pmod 4$ from this note that:
$$1 \equiv x^{p-1} \equiv (x^2)^{\frac{(p-1)}{2}} \equiv (-1)^{\frac{(p-1)}{2}} \pmod p$$
This implies that $\frac{(p-1)}{2}$ is even and hence $p \equiv 1 \pmod 4$
Comment: I also like this! +1
Comment: I am confused how you got $x^2 \equiv -1 \pmod{p}$. If you mean for $x$ to be $xy'$ you would have to show that $xy'$ is coprime with $p$.
Comment: @Puzzled417 If you're reffering to the second equation $x$ is some number such that $x^2 \equiv -1 \pmod p$, and it's existence was proved from the first part. Anyway it's trivial that $(xy, p') = 1$. As $p \not \mid x, y'$ from the condition and the fact that $y'$ has a modular inverse
Answer: No. The way the question is worded, $p=2$ also works.
Anyway, $y \neq 0 \pmod p,$ this means $y$ has a multiplicative inverse $\pmod p,$ for no better reason than $\gcd(y,p)=1$ and we have integers with $ys+pt=1.$
$$x^2 + y^2 \equiv 0 \pmod p,$$
$$x^2 \equiv -y^2 \equiv 0 \pmod p,$$
$$ \frac{x^2}{y^2} \equiv -1  \pmod p,$$
$$ \left( \frac{x}{y} \right)^2 \equiv -1  \pmod p.$$
Answer: by definition, there exists some $k$ so that $pk=x^2+y^2$. wlog, assume that $k$ is prime (otherwise look at its factorization etc.)
If $p$ does not divide $x$ or $y$, then $p^2$ does not divide $x^2+y^2$. But then, use this theorem (the top answer).
Since $p^1$ is an odd power, we deduce that $p \equiv 1 \mod 4$
Answer: Not an Elementary Proof
If you know anything about finite fields, then you can show that the group of units of a finite field $\mathbb{K}$ is cyclic (otherwise, you can show that there exists a positive integer $m<|\mathbb{K}|$ such that $x^m=x$ for all $x\in\mathbb{K}$, meaning that $|K|\leq m$, a contradiction).  If $C_n$ is the cyclic group of order $n\in\mathbb{N}$ and $d$ is a natural number such that $d\mid n$, then there exists an element $x\in C_n$ of order $d$.
Combining these two observations, you get that the group of units of the field $\mathbb{F}_p$ of $p$ elements is the cyclic group $C_{p-1}$.  Hence, if a positive integer $d$ satisfies $d\mid p-1$, then there exists $x\in\mathbb{F}_p$ such that $x^d\equiv 1\pmod{p}$ but $x^j\not\equiv 1\pmod{p}$ for all positive integer $j<d$.  In particular, if $p\equiv 1\pmod{4}$, then $d=4$ leads to $x^4\equiv 1\pmod{p}$ but $x^2\not\equiv1\pmod{p}$, for some $x\in\mathbb{F}_p$.  Then, [...].  I leave the rest to you.
Comment: I like this as well, +1


remove a instance from memory after doing "add" into a list

Question: the code is very simple:
  myKpi = "a";
  Data.add(myKpi);

and then I want to remove myKpi from memory because it has been saved in the list Data.
I have read that I can do sth like myKpi=null, but I don´t know if it will afect the value of Data.
Comment: You can't remove it from memory since, well, it is saved in the list Data. Therefore `myKpi=null` has no meaning as long as the list contains a reference to that object.
Comment: No, `myKpi=null` will not affect the value already stored in `Data`. Why not try it yourself and see?
Comment: Ummm, this is Java right? It's garbage collected, so just let the garbage collector handle it. Unless you have a burning desire to micro manage your memory like this, in which case you may want to look into unmanaged language like C++.
Comment: `Data.add(myKpi)` doesn't introduce another copy of the `String` in memory. Setting `myKpi` to `null` will make no difference.
Comment: List `Data` is itself in memory, along with all objects that it contains. It does not store copies of your items, though, only references.
Comment: `Data` violates the Java naming conventions.
Answer: First, myKpi is just a reference to the instance. That means you can't "remove" myKpi from memory (at least not the instance it references).
Second, since the instance that is referenced by myKpi is added to Data you can't remove that instance since both references refer to the same instance.
Third, you can't manually remove an instance from the heap. All you can do is remove all references and then "ask" the JVM to do garbage collection (via System.gc()) which it will probably do but there's no guarantee it will be done (and what will actually be deleted).
Answer: How about
Data.remove(myKpi);

What type of List do you use?
Comment: You could create an extra Method for like adding myKpi because in that case the variable would just exist temporarily.


Error: Failed to find 'ANDROID_HOME' environment variable

Question: Sou iniciante no desenvolvimento móvel e estava estudando o IONIC, quando fui tentar gerar o apk do projeto teste deu o seguinte erro:

WARN: ionic.project has been renamed to ionic.config.json, please
  rename it. Running command:
  /home/lupum/Documentos/testeionic/hooks/after_prepare/010_add_platform_class.js
  /home/lupum/Documentos/testeionic
add to body class: platform-android
Error: Failed to find 'ANDROID_HOME' environment variable. Try setting
  setting it manually. Failed to find 'android' command in your 'PATH'.
  Try update your 'PATH' to include path to valid SDK directory.

Executei o comando:
sudo ionic build android

E antes disso:
sudo cordova platform add android

Andei procurando formas de resolver e encontrei algumas que falavam para mudar o PATH de onde encontrava o ANDROID.
executei os seguintes comandos:
export ANDROID_HOME=/</usr/local/android-studio/>/android-sdk-linux
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Pois o meu android encontrasse em: /usr/local/android-studio/
E a plataforma do android em: ~/Android/Sdk/platform-tools$
Através desse artigo:
https://stackoverflow.com/questions/36198165/failed-to-find-android-home-environment-variable
O problema persiste.
Desde já agradeceria a ajuda.

Olá pessoal esses são os meus diretórios, como seria a forma correta de setar no path ?
Answer: Isso parece estar errado:
export ANDROID_HOME=/</usr/local/android-studio/>/android-sdk-linux

O corretor provavelmente seria isto:
export ANDROID_HOME=/usr/local/android-studio/android-sdk-linux

Se a instalação estiver na pasta de usuário, você deve usar o caminho absoluto (esse parece ser o seu erro), você fez:
export ANDROID_HOME=Android/Sdk/tools/
export PATH="$PATH:Android/Sdk/platform-tools/"

E depois:
export ANDROID_HOME=home/lupum/Android/Sdk

Veja que ambos você tentou usar caminhos relativos, o que as variaveis de ambiente não vão conseguir indentificar.
Primero essas variaveis de ambiente sempre precisam de caminhos absolutos, porque se não fizer assim elas não vão saber a o que é relativo
Segundo, caminhos absolutos sempre começam com / (Linux, Mac, Like-Unix) e se for Windows sempre começa com C:, D:, etc.
Então se você tem certeza que a instalação está nesta pasta /home/lupum/Android/Sdk o caminho digitado deve ser:
export ANDROID_HOME=/home/lupum/Android/Sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Note que Linux e Mac são case-senstive, ou seja se o nome da pasta tem letras todas em minuscula e você digitar uma letra em maiuscula ele não vai encontrar, então digite igual ao que está na pasta.
Comment: Quando executo os comandos acima dá esse erro:                                               WARN: ionic.project has been renamed to ionic.config.json, please rename it.
Running command: /home/lupum/Documentos/DOGIT/IONIC/ionic-bitcoins-master/hooks/after_prepare/010_add_platform_class.js /home/lupum/Documentos/DOGIT/IONIC/ionic-bitcoins-master

add to body class: platform-android

Error: 'ANDROID_HOME' environment variable is set to non-existent path: /usr/local/android-studio/android-sdk-linux
Try update it manually to point to valid SDK directory.
Comment: Também já cheguei a atualização do Android SDK mais fala que já é de fato a versão mais nova. Então o erro é outro, também não é de permissão acredito.
Comment: @CRISLANIO Eu editei a resposta, leia novamente por favor.
Answer: Para configurar o ambiente de desenvolvimento Android
Defina a variável de ambiente ANDROID_HOME com base na localização do Android SDK. Além disso, considere a adição ANDROID_HOME/tools e ANDROID_HOME/platform-tools ao seu caminho.
Mac OS X
export ANDROID_HOME=/local-de-instalacao/android-studio/android-sdk-macosx
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Linux
export ANDROID_HOME=/usr/local/android-studio/android-sdk-linux
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Windows
set ANDROID_HOME=C:\local-de-instalacao\android-studio\android-sdk-windows
set PATH=%PATH%;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools

Para mais detalhes, veja aqui este artigo sobre Installing the Android Development Environment(en).
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54274/discussion-on-answer-by-ack-lay-error-failed-to-find-android-home-environment)


Show that the equation $2-x=\frac{lnx}{4}$ has a unique root in the interval 0<x<$\infty$

Question: $Show \quad that\quad  the \quad equation \quad 2 - x = \frac{lnx}{4}\quad  has \quad a \quad unique \quad root \quad x=\eta \quad in\quad  the \quad interval \quad 0<x<\infty$.
-from Martin Braun's Differential equations and their applications p.87.

I tried to solve this problem with the theorem that
if f(x) and f'(x) are continuous in the interval [a,b], with |f'(x)|≤$\lambda$<1, and $x_{n+1}=f(x_n)$ all lie in the interval [a,b], then the iterates $x_n$ converges to a unique number $\eta$ satisfying $\eta$=f($\eta$).
But, $f(x) = 2 - \frac{lnx}{4}$, obtained from $ x = 2 - \frac{lnx}{4}$, has derivative $f'(x) = \frac 1 {4x}$. And, obviously, $|f'(x)|≥1$ when $0<x≤\frac 1 4$. Hence, it seems that the theorem couldn't be applied, and this is where I stuck.
Can someone help me?
Thanks!
Answer: Do you know what the graphs of these functions look like? If not try wikipedia or a graphing calculator.
Now, notice that $\operatorname{ln}x$ increases from $-\infty$ to $\infty$. The other function only decreases though... If two cars are going opposite direction and they never change course, how many times will they meet?
The theorem that you are mentioning doesn't really fit here. For that matter it is more advanced than the context of the problem...
Comment: Many thanks!! Seems I was obsessed with using the theorems..


Likelihood of errors based on a sample

Question: I frequently do something like: load a bunch of data, and then scan some fraction of it randomly to verify that no errors occurred. The more data I verify, the greater my certainty that no errors occurred anywhere.
I'm curious about how I can express this formally. My thought process is:
Suppose there are $n$ records, of which $k$ contain errors. The probability of a randomly selected one containing an error is $k/n$ and conversely, the probability of selecting one without an error is $1-k/n$. If I model this as a Bernoulli process, I believe the probability of $t$ samples all having no error is $\left(1-k/n\right)^t$. So given some information about the data, I can get the probability of finding no errors.
But what I really want is the reverse: given that I found no errors, what confidence do I have that there are less than $k_{act}$ errors in actuality? I think I could use Bayes' theorem here, but that would require me having some priors which seem difficult to estimate.
Can I just set my formula equal to, say, $.95$ and solve, and then claim I've found a 95% confidence interval?
By the way, I'm interested for curiosity's sake. I think a more realistic attempt would take into account that errors would tend to propagate, for example.
Comment: See the (oddly-named) Wikipedia article [Rule of three (medicine)](http://en.wikipedia.org/wiki/Rule_of_three_%28medicine%29)
Comment: Incidentally, your title is confusing in that (a) it uses likelihood in the common, not the statistical, meaning of the terms and (b) it uses errors in the sense of defects or negatives, rather than random errors!
Comment: Are you perhaps asking [this question](http://stats.stackexchange.com/questions/18754/sample-size-to-determine-if-success-proportion-is-zero)?
Answer: Your problem is called Laplace's succession rule, namely that if you have seen no error in a batch of $t$ independent draws from a Bernoulli $B(p)$, the (posterior) probability that the next draw will error-free is
$$
\dfrac{t+1}{t+2}\,.
$$
This is Bayesian in that you put a uniform prior on the probability of error, $p$. No need to "estimate" anything.
The way you presented the problem is slightly different in that you are working on an hypergeometric assumption, hence the probability of having $t$ draws with no error is
$$
\dfrac{{t \choose n-k}\times 1}{{t \choose n}}
$$
rather than the $(1=\frac{k}{n})^t$ you proposed. If $n$ is large compared with $t$, it does not make too much of a difference. Otherwise, if you put a uniform prior on $k$, you recover once again Laplace's rule,
$$
P(k=0|X_t=0) = \dfrac{t+1}{t+2}\,.
$$
(This is detailed in Section 4.3.1 on The Bayesian Choice. The Wikipedia entry is unnecessarily convoluted.)

Likelihood of errors based on a sample


How can I organize my content using hierarchical taxonomy?

Question: My question is rather simple, but I don't know how to do it ?
I want to display a content with various fields, but I want the user to browse "hierarchically". For instance :

Choose brand : BMW
Choose model : BMW / Z3
Choose specific model : BMW / Z3 / 2.0 i

I already made a taxonomy "Brand", a taxonomy "Model", I have a view that shows all brands.
What can I do ?
Thanks for advice, it would help me a lot !
Comment: Have you tried any of the following modules? [Hierarchical select](https://www.drupal.org/project/hierarchical_select) or [Simple hierarchical select](https://www.drupal.org/project/shs). The latter has a Views filter.
Answer: I had a similar implementation on a drupal 6 site using Hierarchical Select. The drupal 7 branch turned out to be working slightly differently when I first tried to make the move.
There is also Simple hierarchical select which was probably developed because of these 'differences' between d6 and d7:

"This module has been inspired by Hierarchical select but is much simpler (…)."

I haven't tried 'Simple hierarchical select' yet, but if I would re-build that d6 site again, I would probably go for 'Simple hierarchical select'.
Both let you generate a taxonomy tree with dependend parent-child-relationships. So instead of having one taxonomy brandand one one taxonomy model you would have a taxonomy tree taht would contain all the branches down to specific model.
In my case is was venues which then also contained the upper branches like cityand country.
PS: You could however also use entity references to build complex hierarchical content trees. You would then for example have a content type brand and a content type model referencing each other.  Nowadays I find this approach more convenient than dealing with taxonomy trees – but that's of course depending on personal preferences and/or content structure.
Comment: I tried the module - so if I am understanding well, I will have to use sub-terms in the taxonomy ? For instance, the taxonomy I named "Brand" will also contain the "model types" and the "models" ?
Comment: yes – afaik using one of the above modules you would only have one taxonomy tree.
Comment: That sounds a bit 'dramatic' – good luck! Btw: you can also build rich content trees *without* using texonomy trees – I updated my answer accordingly…
Comment: That's where I am lost : can you help me a bit more ? Do you have an example I can check of entity references ? Because my taxonomy is going to be VERY HUGE and if something more convenient than taxonomy is usable, I'll give it a try - I just didn't know anything else existed :) Thanks a lot for your help !
Comment: It really depends on your content structure and your workflow. If you prefer to present rather large, 'ready-made' taxonomy trees to your editors, then taxonomy is probably the way to go. If you instead like adding new child nodes 'on the fly' then entity reference can be an alternative. This article http://www.digett.com/blog/04/04/2012/rip-taxonomy-module-drupal-7 made me think – while some of if may be very true, other paragraphs are a bit 'over the top'. But still it can be a good starting point to re-think the idea of 'content trees' instead of 'taxonomy trees'.
Comment: In fact, this was EXACTLY what I aimed to do, I watched this video https://www.youtube.com/watch?v=AcVz8Thxq48 to have a glimpse, and I won't use taxonomy anymore for my website. Thanks a lot !
Comment: Just one additional thought: the *entity reference* approach can however become a bit 'clumbsy'. Currently working on a website with hundreds of cross-referencable nodes, the 'free tagging' field "entityreference_prepopulate" becomes a bit slow or cluttered. Thinking about adding the 'entity reference view' module to solve this… But still wouldn't trade the current setup for taxonomies.
Comment: Yes, I understand what you mean - but with +1000 references in the website, it comes very handy : I managed to do whatever I wanted ; if I want to organize things differently, I'll only have to make a new content type and that's done.

Thanks for solving a big problem that I had :D


XSS in Drupal 7 Views Replacement token

Question: I am working on a Drupal 7 site that uses a replacement pattern %1 inside a View header to generate a URL with the Organic Group id(og_group_ref).
The view header markup is
Create Convo

Example URL of a page is site/b_posts/2, so the link created would be /node/add/post?og_group_ref=2.
This is vulnerable to XSS, since accessing the URL site/b_posts/%22%20onmouseover=%22alert%28559%29%22%20test=%22/2 would result in a JS alert getting executed on mousing over the link. How to protect against this? I used the latest version of Views and this is still happening.
Comment: Welsome to Drupal Answers. How do you create this link exactly?
Answer: You must enable validation on your contextual filter.
More information found here:
https://drupal.org/node/1578564
http://nodeone.se/en/learn-views-with-nodeone-part-23-validation-of-contextual-filter-input

XSS in Drupal 7 Views Replacement token


How to set individual fields permission on content type fields based on roles using field permssion

Question: I am using field permission module. I want some fields to be editable for other roles which I set using field permission module, but when I login as that user role I don't get the edit option on the node.
What I am actually trying to achieve is this:

I have created a content type with fields.
I want editor role users to submit pictures for that post.
They should not be able to edit other fields but just this.
Answer: Field permissions do not add permissions, but only take permissions away.
If a user is not allowed to edit a node, giving him the permission to edit a field won't work. Instead you must give him permission to edit all nodes (of a certain type) and deny access to all field he may not edit. (and yes that can be a struggle if you add fields in the future)
Comment: **Thanks** This worked for me. Definitely i do understand you concern with regard to add new fields latter and give them permissions again. Anyways this worked for now. Thanks again


While trying to start react app i am facing the below error and it is not compiling why?

Question: I got a notification in vs-code to activate tc(type-script) and i activated it. After that when i am trying to run basic example app(npx create-react-app my-app) given in the react docs, i am facing the below error. Can any one tell the best way to overcome this issue?
./src/index.js 1:77
    Module parse failed: Unexpected token (1:77)
    File was processed with these loaders:
     * ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
     * ./node_modules/babel-loader/lib/index.js
    You may need an additional loader to handle the result of these loaders.
    > $RefreshRuntime$ = require('E:/ReactJS preparation(GD)/ReactProject with API's/my-app/node_modules/react-refresh/runtime.js');
    | $RefreshSetup$(module.id);
    |

Comment: Did you try to restart VS?
Comment: Yep...i fully uninstalled VScode and installed again but i am facing the same issue.
Answer: The problem could be in the way you named your folder, including spaces and apostrophe (the ' in API's).
Answer: Yes, Guillermo is right, you are seeing this error because of the path of the file:
E:/ReactJS preparation(GD)/ReactProject with API
the spaces are preventing the file to be accessed correctly. I had a similar issue with ' in the name.
Comment: Yes, it what I said "Guillermo is right" and added some clarification to help. Why is that not ok? (I also upvoted his answer).
Comment: he says 'it could be' and then not much else. I wanted to confirm that for me that was the issue and give clearer steps to fix (particularly for newbies and for people scrolling for answers with steps and code like myself).


For complex z showing $\cos(z+ \pi) = -\cos(z)$

Question: As the title states, for complex $z$ I want to show $\cos(z+ \pi) = -\cos(z)$.
My first attempt was to change $\cos$ into $(e^{iz} + e^{-iz}) /2$ but then I figured using the identity $\cos(z) = \cos(x)\cosh(y)+i\sin(x)\sinh(y)$ was better since $\cos(x+ \pi)=-\cos(x)$ for real $x$. But now I'm unsure how to proceed.
Comment: The easiest way is to use the [principle of permanence](https://en.wikipedia.org/wiki/Principle_of_permanence#Applications), but this principle is not trivial.
Answer: Hint: Recall that $e^{\pi i} = e^{-\pi i} = -1$ and that $e^{u+v} = e^{u}e^{v}$ and go with your first way.
Answer: In both cases you must get the same answer. For instance, with the second one we have, for $z=x+iy$,
\begin{align}
\cos(z+\pi)&=\cos(x+\pi+iy)\\
&=\cos(x+\pi)\cosh y+i\sin(x+\pi)\sin y\\
&=(\cos x\cos\pi-\sin x\sin \pi)\cosh y+i(\sin x\cos \pi +\sin\pi\sin x)\sinh y\\
&=\left[(\cos x)(-1)-(\sin x)(0)\right]\cosh y+i[(\sin x)(-1)+(0)\cos x]\sinh y\\
&=-\cos x\cosh y-i\sin x\sinh y \tag 1
\end{align}
Added:
Now,
$$-\cos z=-(\cos x\cosh y+i\sin x\sinh y)=-\cos x\cosh y-i\sin x\sinh y\tag 2$$
By comparing ($1$) and ($2$) the identity follows.
Comment: But isn't that -(cos$x$cosh$y$+isin$x$sinh$y$)?
Comment: Which is different from -(cos$x$cosh$y$-sin$x$sinh$y$)?
Comment: @Lupin: I don't understand what are you asking.
Answer: The sleek, more complex-analytic way to do it: Let $f(z) = \cos z + \cos(z+\pi)$. Then $f$ is entire, and $f(x) = 0$ for $x \in \mathbb{R}$. Hence, by the identity theorem, $f(z) = 0$ for all $z \in \mathbb{C}$.
Comment: That's the principle of permanence...
Answer: Just continue your approach:
$\cos(z) = \cos(x)\cosh(y)+i\sin(x)\sinh(y)$
Then just plug in $z+\pi$ instead:
$\cos(z+\pi) = \cos(x+\pi)\cosh(y)+i\sin(x+\pi)\sinh(y)$
And observe that both $\cos(x+\pi)=-\cos(x)$ and $\sin(x+\pi)=-\sin(x)$ and you get:
$\cos(z+\pi) = -\cos(x)\cosh(y)-i\sin(x)\sinh(y) = -\cos(z)$


Changing git user on local branch before pushing to remote

Question: I am in the following situation:
I was given a development machine, with all the repos tied to somebody else's git credentials. I created a new local branch, made a bunch of commits, across 9 or 10 repos. I now have an account on the company's git server and I want to push my local branch to the remote server (same branch, don't need to change anything there).
However, I need it to show all the commits as being made by me, not by the other person who was using this laptop before me.
Is there a way to do this? Do I need to somehow go back and change the user associated with all these local commits to myself and, if so, how can I do that? Open to hacks if necessary.
Comment: As always with `git`, you'll need to go back and redo all of the commits to change something about them, even just the author. As long as the commits haven't been pushed elsewhere yet (which seems like the case here), this is fine, and the script below looks good. Just as a warning to people coming to this later, though, who might not realize the context when Google lands them here - don't change history (commits) you've already shared with others!
Answer: Checkout GitHub's script for "changing author info":

To change the name and/or email address recorded in existing commits,
  you must rewrite the entire history of your Git repository.
Warning: This action is destructive to your repository's history. If
  you're collaborating on a repository with others, it's considered bad
  practice to rewrite published history. You should only do this in an
  emergency.
Changing the Git history of your repository using a script
We've
  created a script that will change any commits that previously had the
  old email address in its author or committer fields to use the correct
  name and email address.
Note: Running this script rewrites history for all repository
  collaborators. After completing these steps, any person with forks or
  clones must fetch the rewritten history and rebase any local changes
  into the rewritten history.
Before running this script, you'll need:

The old email address that appears in the author/committer fields that
  you want to change
The correct name and email address that you would
  like such commits to be attributed to

Instructions:

Open Terminal.
Create a fresh, bare clone of your repository:

git clone --bare https://github.com/user/repo.git`
cd repo.git

Copy and paste the script, replacing the following variables based on
  the information you gathered:

OLD_EMAIL
CORRECT_NAME
CORRECT_EMAIL
#!/bin/sh

git filter-branch --env-filter '

OLD_EMAIL="email@example.com"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="firstname.lastname@example.com"

if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_COMMITTER_NAME="$CORRECT_NAME"
    export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_AUTHOR_NAME="$CORRECT_NAME"
    export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

Press Enter to run the script.
Review the new Git history for errors.
Push the corrected history to GitHub:
git push --force --tags origin 'refs/heads/*'
Clean up the temporary clone:

cd ..
rm -rf repo.git

Comment: Note that this will change the author of *all* the commits made by the original author, not just those you made after you inherited the laptop. If the original author has made any commits in the repository, and you rewrite **all** of the history, and you're on a team, I can almost guarantee you that nobody will be too happy with you for doing this. **Make sure you only change the commits you made**
Comment: As with all git commands that rewrite history, **make sure you understand what it does**, this includes force-pushing. To be honest, I think you should go and talk to the team lead or your software architect about this issue before you start force-pushing to a central repository. "They said to do so on Stack Overflow" doesn't sit well if everybody now have stale branches in the repository and you generate a ton of work to make sure everybody can continue working.
Comment: @LasseVågsætherKarlsen Good call, and thanks for the heads up; I won't go into it blindly. I'll see if there's a way to limit the author re-writes to a single branch / past a certain date first before I decide to press the big red button.


Should I consider switching to Silverlight from WPF?

Question: I have been using WPF for a new project which is far from done. It's a hobby project and a very useful one.
I'd like to have cross-platform compatibility (i.e. Linux + Mac + Windows), but Windows is the primary target. I'm pretty good with web languages and C# and Erlang, but C/C++ are not among them and I hate Java. So it was a natural move to choose WPF for me.
However, after reading numerous sources like http://www.mono-project.com/WPF:

At this point, we strongly suggest that users interested in WPF adopt
  Silverlight instead as it can now be used outside of the browser and
  offers a rich set of cross platform APIs and features.

I'm starting to wonder if I should port my app to Silverlight and use it instead.
A couple of facts:

My application is pure desktop application and meant to be so. It needs lower level access to system resources (but not that low that .NET wouldn't be enough).
I'd like to have the three platforms support, but Windows is the primary concern.
I'd prefer C# and .NET and something equivalent to WPF where the UI is declarative, separated from code in a clean way and allows for rich user interfaces.

I've heard Silverlight works in Mac already, and support for Linux is possible via Moonlight.
Should I consider switching to Silverlight from WPF and what problems may arise?
Comment: I'd follow the advice from mono project
Answer: To start i'd consider this answer.
The main point is that (actually) Silverlight is a sub set of WPF, so if your application user base are PC/Window user only, you might want to develope your app in WPF because function wise it's still much richer than Silverlight and because it's a desktop application so you have all the access to the local machine. If you want to develop an application that is Web based runs on browser, not only on PC but also on Mac, then you want to develop in Silverlight.
In my opinion for your requests WPF remains the best choice.
Answer: Well, from experience I can tell that some things won't work in Silverlight like they do in WPF. Some things I've encountered recently (although there are many more):

Bindings don't work exactly like you want. For instance, in WPF by default your bound property changes on keyUp on a text field. In Silverlight that's not the case: it will update on Blur. Frameworks like Caliburn.Micro fix this by adding this implicitly.
WPF has something called Adorners. These basically allow you to add small UI elements for things like resize, rotate, etc. Things you typically see in designers (drag to resize). You can make something like that in Silverlight, but it's a bit more complex.
I'm not sure about WPF, but in Silverlight a call to a webservice is eventually done on the UI thread. You can set it up wherever you want, but the actual call and callback is done on the mainthread. Something to keep in mind when dealing with a result from a web call which might take a while to execute (someone can correct me on this if I'm wrong).

I think the typical way you should work with a new application is start in Silverlight, and move to WPF if you really need to. Also, I've been told that it's slightly easier to port a Silverlight application to winRT/Metro, so that might be something you would want to check out.
Addition
Here's a link from MSDN describing various differences: http://msdn.microsoft.com/en-us/library/cc903925%28v=vs.95%29.aspx
Comment: Interesting key points. None of them seem a deal breaker to me.
Comment: @rFactor I added a link to MSDN with a good comparison between the two.


Como verificar se a extensão php_fileinfo.dll está ativa ou não via código php?

Question: Eu precisaria rodar esse código em outra máquina, caso a extensão:
extension=php_fileinfo.dll

Preciso dela pra utilização do mimetype, acaso esteja desativada eu utilizaria outro código sem ser utilizando mimetype para fazer a comparação de extensão.
Comment: Você quer verificar ou quer ativar?
Comment: @GuilhermeNascimento A princípio queria realizar a verificação, pois não sei é possível realizar a ativação via código, então poderia ser os dois.
Answer: Além do extension_loaded citado você pode usar function_exits pra verificar se a função esta disponível (seria como um "feature detection"), você pode fazer assim no script:
if (!function_exits('finfo_file')) {
   echo 'Extensão fileinfo não disponível, habilite no php.ini';
   exit;
}

Assim você checa se a função existe.
Note que usar $_FILES['nome']['type'] é pode causar problemas pois em algumas situações atípicas ele pode retornar resultados inesperados, por exemplo você tem um arquivo com a extensão .jpg, mas os dados são um .txt, quando faz o upload o [type] retorna algo como:
array(5) {
  ["name"]=>
  string(9) "teste.jpg"
  ["type"]=>
  string(10) "image/jpeg"
  ["tmp_name"]=>
  string(19) "Z:\.tmp\php4EA4.tmp"
  ["error"]=>
  int(0)
  ["size"]=>
  int(3)
}

Mas na verdade o teste.jpg possui apenas isto no conteudo a b c, então quando for usar coisas como imagecreatefromjpeg vai ter problemas, eu sei que parece improvavel ter um arquivo que não é imagem mas com a extensão .jpg, mas existem muitos casos aonde o arquivo é um webp ou png, mas o cliente baixou como jpeg, então se ele vier a fazer upload isso poderá confundir teu script, também existe a possibilidade do usuário baixar uma foto e ela vir truncada mas ele não se de conta e em seguida vai subir pro seu servidor.
Aplicações feitas em Flash também costuma enviar o type como application/octet-stream em requisições como citado pelo em Comparar extensão de arquivo:

... Eu já vi gente dizendo o contrário, e já vi casos em que o mime-type vem errado ou inútil (application/octet-stream, que pode ser qualquer coisa).

Nem sempre é possivel habiltiar a extensão, mas em alguns servidores é possivel usar uma função chamada dl();, mas ainda sim você pode tentar:
function carregarExtensao($nome)
{
    if (!extension_loaded($nome)) {
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            //Carrega em Windows
            return dl('php_' . $nome . '.dll');
        } else {
            //Carrega em unix-like
            return dl($nome . '.so');
        }
    }

    return true;
}

if (!carregarExtensao('fileinfo')) {
     echo 'Não foi possivel carregar a extensão';
     exit;
}

NOTA: Esta função foi removida na maioria dos SAPIs no PHP5.3.0 e foi removida no PHP-FPM na versão PHP7

Se não funcionar no seu servidor, então não é possível.
Comment: Caso extension=php_fileinfo.dll estivesse desabilitado eu queria executar outra comparação de extensão sem ser utilizando mimetype, mas com vc disse o servidor fica muito vulnerável a receber arqruivos indevidos. Melhor só realizar só a verificação mesmo e ativar manualmente. Mas vou testar a função que vc mandou ! Valeu pela disponibilidade de me ajudar !
Comment: Entendi Guilherme muita esclarecedora sua explicação, Mas existe a possibilidade de caso esteja desabilitado a extensao,meu código habilitar essa extensão para poder executar o mimetype tranquilamente ?
Comment: @Caleb por isso te perguntei se era verificar ou habilitar rs, então não tem como ativar em tempo de execução infelizmente. Existe até uma função vou editar a resposta e colocar um exemplo.
Comment: @Caleb muitas extensões vem desabilitadas nos servidores pra melhorar a perfomance, então habilitamos apenas o que necessitamos usar. Hoje é tão comum (ou melhor necessário) o uso de fileinfo, realmente seria interessante se já viesse habilitado, quem sabe no php7 =)
Answer: Verificando se a extensão foi carregada
if (!extension_loaded('fileinfo')) {
    // a extensão fileinfo não está carregada
} else {
    // a extensão fileinfo foi carregada
}

http://php.net/extension_loaded
A variável global $_FILES
Caso queria obter o mime type no momento de um upload, pode buscar a informação diretamente na variável global $_FILES.
Exemplo
$_FILES['nome_do_campo']['type']

Nesse caso não precisa de extensão específica como a Fileinfo e é mais seguro do que "apelar" para a extensão da nomenclatura do arquivo.
No entanto, não confie 100% num único parâmetro. A variável $_FILES resgata informações providas pelo cliente (browser por exemplo).
A função nativa getimagesize()
No PHP, existe a função nativa getimagesize() onde poderá obter informações sobre o arquivo.
$size = getimagesize($filename);
echo $size['mime'] // aqui o mime-type.

Sugestão de implementação
Um exemplo de como pode implementar uma rotina que lê o tipo do arquivo:
$path = '/local/do/arquivo.jpg';

if (!extension_loaded('fileinfo')) {
    /*
    Obtendo informação de getimagesize()
    */
    $size = getimagesize($path);
    $mime_type = $size['mime']; // aqui o mime-type.
    unset($size);
} else {
    /*
    Obtendo informação de Fileinfo
    */
    $mime_type = finfo_open(FILEINFO_MIME, $path);
}

'O tipo do arquivo é: '.$mime_type;


EF Codefirst AddOrUpdate with related entities as identifier

Question: I want to use AddorUpdate with setting an identifier expression using related entities.
My class:
Class Task
   property id as Integer
   property name as String
End Class

My relation class:
Class RelationTask
   property id as Integer
   property task as Task
   property parentTask as Task
End Class

now I want to add a relation like:
taskA = new Task with {.name = "A"}
taskB = new Task with {.name = "B"}
.... ' add tasks to context
context.RelationTasks.AddOrUpdate(function(r) r.task, new RelationTask with {.task = TaskB, .parentTask = TaskA})

This does not work (error "Unable to create a constant value of type 'DataModel.Task'. Only primitive types or enumeration types are supported in this context."), because I use an entity instead of a value...
How should I do this?
Also, a second question: how would I write the same but with multiple identifiers? I think something like function(r) {r.task, r.parentTask}
Thanks!
Answer: Since nobody answers, I tried to find a solution myself, but I can't believe that's the best way of doing it. Anyhow, I added the IDs of both related entities so I could use these as identifier:
Class Task
   property id as Integer
   property name as String
End Class

Class RelationTask
   property id as Integer
   property task as Task
   property taskId as Integer
   property parentTask as Task
   property parentTaskId as Integer
End Class

taskA = new Task with {.name = "A"}
taskB = new Task with {.name = "B"}
.... ' add tasks to context
context.RelationTasks.AddOrUpdate(function(r) New With {r.taskId, r.parentTaskId}, new RelationTask with {.task = TaskB, .parentTask = TaskA})

It is behaving as I want, but it doesn't feel good...


Encontrar uma letra em caixa alta no texto

Question: Estou fazendo umas verificações de texto para senha.
Já localizei para caractere especial mas não achei para letra em caixa alta.
Usei Regex. Por exemplo se o texto conter "teste" retorna falso e se conter "tesTE" retorna verdadeiro.
Alguém sabe me dizer? Se funciona com o Regex também?
Utilizei este para verificar se o meu campo senha tem um caractere especial
ExisteCaracterEspecial = Regex.IsMatch(txt_senha.Text, ("[\[\]\^\$\.\|\?\*\+\(\)\\~`\!@#%&\-_+={}'""<>:;, ]{1,}"));

Estou usando VB.NET
Comment: @rubStackOverflow Acho que se o AP colocou a tag `C#` é porque aceita resposta em qualquer uma das linguagens. Não teria porque remover a tag.
Comment: Entendido @jbueno
Comment: @rubStackOverflow Eu acho, né :p Vamos ver o que ele diz
Comment: Melhor passar do que faltar :)
Answer: É possível fazer isso usando o Any do LINQ também.
Em VB.NET

Com LINQ
Dim existeMaiuscula As Boolean = senha.Any(Function(c) Char.IsUpper(c))

Com Regex
Dim existeMaiuscula As Boolean = Regex.IsMatch(senha, "\p{Lu}")

 Em C#

Com LINQ
var existeMaiuscula = senha.Any(c => Char.IsUpper(c));

Com Regex
var existeMaiuscula = Regex.IsMatch(senha, @"\p{Lu}");

Comment: Funcionou perfeitamente @jbueno muito obrigado!


Given n tuples representing pairs, return a list with connected tuples

Question: Given n tuples, write a function that will return a list with connected values.
Example:
pairs = [(1,62),
    (1,192),
    (1,168),
    (64,449),
    (263,449),
    (192,289),
    (128,263),
    (128,345),
    (3,10),
    (10,11)
    ]

result:
[[1,62,192,168,289],
 [64,449,263,128,345,449],
 [3,10,11]]

I believe it could be solved using graphs or trees as data structure, creating nodes for each value and and edges for each pair with each tree or graph representing connected values, but I didn't find a solution yet.
What would be the best way to produce in python a result that yields a list of connected values for those pairs?
Comment: So they are all contained in the same set
Comment: What if there is a loop?
Comment: Are there always two elements per tuple?
Comment: @thefourtheye, if there is a loop the result would be [1,62,192,168,289, 64,449,263,128,345,449,3,10,11]
Comment: @BBrown, yes. always two elements per tuple
Comment: You're second component in the result contains `449` twice. Is that intended?
Comment: Possible duplicate of [How to aggregate matching pairs into "connected components" in Python](https://stackoverflow.com/questions/27967093/how-to-aggregate-matching-pairs-into-connected-components-in-python)
Answer: You can solve it with Disjoint Set (Union-Find) implementation.
Initialize the structure djs with all of the numbers. Then for each tuple (x,y), call djs.merge(x,y). Now for each number x, create a new set for it iff djs.sameSet(x,)==false for an arbitrary y from each existing set.
Maybe that could help you.
Comment: The second step can be to simply extract the disjoint sets as lists and convert them to tuples.
Answer: You also could use networkx as a dependency.
import networkx as nx

pairs = [(1,62),
        (1,192),
        (1,168),
        (64,449),
        (263,449),
        (192,289),
        (128,263),
        (128,345),
        (3,10),
        (10,11)]

G = nx.Graph()
G.add_edges_from(pairs)
list(nx.connected_components(G))

Answer: I didn't know this problem already had a name (thanks avim!), so I went ahead and solved it naively.
This solution is somewhat similar to Eli Rose's. I decided to post it though, because it is a bit more efficient for large lists of pairs, due to the fact that the lists_by_element dictionary keeps track of the list an element is in, allowing us to avoid iterating through all the lists and their items every time we need to add a new item.
Here's the code:
def connected_tuples(pairs):
    # for every element, we keep a reference to the list it belongs to
    lists_by_element = {}

    def make_new_list_for(x, y):
        lists_by_element[x] = lists_by_element[y] = [x, y]

    def add_element_to_list(lst, el):
        lst.append(el)
        lists_by_element[el] = lst

    def merge_lists(lst1, lst2):
        merged_list = lst1 + lst2
        for el in merged_list:
            lists_by_element[el] = merged_list

    for x, y in pairs:
        xList = lists_by_element.get(x)
        yList = lists_by_element.get(y)

        if not xList and not yList:
            make_new_list_for(x, y)

        if xList and not yList:
            add_element_to_list(xList, y)

        if yList and not xList:
            add_element_to_list(yList, x)

        if xList and yList and xList != yList:
            merge_lists(xList, yList)

    # return the unique lists present in the dictionary
    return set(tuple(l) for l in lists_by_element.values())

And here's how it works: http://ideone.com/tz9t7m
Answer: Another solution that is more compact than wOlf's but handles merge contrary to Eli's:
def connected_components(pairs):
    components = []
    for a, b in pairs:
        for component in components:
            if a in component:
                for i, other_component in enumerate(components):
                    if b in other_component and other_component != component: # a, and b are already in different components: merge
                        component.extend(other_component)
                        components[i:i+1] = []
                        break # we don't have to look for other components for b
                else: # b wasn't found in any other component
                    if b not in component:
                        component.append(b)
                break # we don't have to look for other components for a
            if b in component: # a wasn't in in the component
                component.append(a)
                break # we don't have to look further
        else: # neither a nor b were found
            components.append([a, b])
    return components

Notice that I rely on breaking out of loops when I find an element in a component so that I can use the else clause of the loop to handle the case where the elements are not yet in any component (the else is executed if the loop ended without break).
Answer: I came up with 2 different solutions:
The first one I prefer is about linking each record with a parent. And then of course navigate further in the hierarchy until an element is mapped to itself.

So the code would be:
def build_mapping(input_pairs):
    mapping = {}

    for pair in input_pairs:
        left = pair[0]
        right = pair[1]

        parent_left = None if left not in mapping else mapping[left]
        parent_right = None if right not in mapping else mapping[right]

        if parent_left is None and parent_right is None:
            mapping[left] = left
            mapping[right] = left

            continue

        if parent_left is not None and parent_right is not None:
            if parent_left == parent_right:
                continue

            top_left_parent = mapping[parent_left]
            top_right_parent = mapping[parent_right]
            while top_left_parent != mapping[top_left_parent]:
                mapping[left] = top_left_parent
                top_left_parent = mapping[top_left_parent]

            mapping[top_left_parent] = top_right_parent
            mapping[left] = top_right_parent

            continue

        if parent_left is None:
            mapping[left] = parent_right
        else:
            mapping[right] = parent_left

    return mapping

def get_groups(input_pairs):
    mapping = build_mapping(input_pairs)

    groups = {}
    for elt, parent in mapping.items():
        if parent not in groups:
            groups[parent] = set()

        groups[parent].add(elt)

    return list(groups.values())

So, with the following input:
groups = get_groups([('A', 'B'), ('A', 'C'), ('D', 'A'), ('E', 'F'),
                     ('F', 'C'), ('G', 'H'), ('I', 'J'), ('K', 'L'),
                     ('L', 'M'), ('M', 'N')])

We get:
[{'A', 'B', 'C', 'D', 'E', 'F'}, {'G', 'H'}, {'I', 'J'}, {'K', 'L', 'M', 'N'}]

The second maybe less efficient solution would be:
def get_groups_second_method(input_pairs):
    groups = []

    for pair in input_pairs:
        left = pair[0]
        right = pair[1]

        left_group = None
        right_group = None
        for i in range(0, len(groups)):
            group = groups[i]

            if left in group:
                left_group = (group, i)

            if right in group:
                right_group = (group, i)

        if left_group is not None and right_group is not None:
            merged = right_group[0].union(left_group[0])
            groups[right_group[1]] = merged
            groups.pop(left_group[1])
            continue

        if left_group is None and right_group is None:
            new_group = {left, right}
            groups.append(new_group)
            continue

        if left_group is None:
            right_group[0].add(left)
        else:
            left_group[0].add(right)

    return groups

Answer: It seems like you have a graph (in the form of a list of edges) that may not be all in one piece ("connected") and you want to divide it up into pieces ("components").
Once we think about it in the language of graphs, we're mostly done. We can keep a list of all the components we've found this far (these will be sets of nodes) and add a node to the set if its partner is already there. Otherwise, make a new component for this pair.
def graph_components(edges):
    """
    Given a graph as a list of edges, divide the nodes into components.

    Takes a list of pairs of nodes, where the nodes are integers.
    Returns a list of sets of nodes (the components).
    """

    # A list of sets.
    components = []

    for v1, v2 in edges:
        # See if either end of the edge has been seen yet.
        for component in components:
            if v1 in component or v2 in component:
                # Add both vertices -- duplicates will vanish.
                component.add(v1)
                component.add(v2)
                break
        else:
            # If neither vertex is already in a component.
            components.append({v1, v2})

    return components

I've used the weird for ... else construction for the sake of making this one function -- the else gets executed if a break statement was not reached during the for. The inner loop could just as well be a function returning True or False.

EDIT: As Francis Colas points out, this approach is too greedy. Here's a completely different approach (many thanks to Edward Mann for this beautiful DFS implementation).
This approach is based upon constructing a graph, then doing traversals on it until we run out of unvisited nodes. It should run in linear time (O(n) to construct the graph, O(n) to do all the traversals, and I believe O(n) just to do the set difference).
from collections import defaultdict

def dfs(start, graph):
    """
    Does depth-first search, returning a set of all nodes seen.
    Takes: a graph in node --> [neighbors] form.
    """
    visited, worklist = set(), [start]

    while worklist:
        node = worklist.pop()
        if node not in visited:
            visited.add(node)
            # Add all the neighbors to the worklist.
            worklist.extend(graph[node])

    return visited

def graph_components(edges):
    """
    Given a graph as a list of edges, divide the nodes into components.
    Takes a list of pairs of nodes, where the nodes are integers.
    """

    # Construct a graph (mapping node --> [neighbors]) from the edges.
    graph = defaultdict(list)
    nodes = set()

    for v1, v2 in edges:
        nodes.add(v1)
        nodes.add(v2)

        graph[v1].append(v2)
        graph[v2].append(v1)

    # Traverse the graph to find the components.
    components = []

    # We don't care what order we see the nodes in.
    while nodes:
        component = dfs(nodes.pop(), graph)
        components.append(component)

        # Remove this component from the nodes under consideration.
        nodes -= component

    return components

Comment: Well, it's nice and simple but it doesn't merge components (e.g. `[(1, 2), (3, 4), (2, 4)]` will return `[{1, 2, 4}, {3, 4, 2}]` instead of `[{1, 2, 3, 4}]`).
Comment: This is exactly the solution I was about to post, except that I didn't use `for..else` but rather a dull boolean flag to indicate whether a new set should be added to the list of sets. Good job!
Comment: That's a pretty nice and simple solution!
Comment: I've proposed a solution below using list and not sets (but it should be possible with either); it's more complex because we want to handle this case.
Comment: That's true. I did some additional tests and can happen that items appear in different components.


Connecting 2 classes in javafx

Question: I am making a project in javafx. My project has several classes and all classes are included in a package. What i need is to make a function of some other class working when a button from  another class is pressed. Below I include the code of my main class. All other classes in package has the same format as of the below code (that is, every class extends Application and start() method is used). My problem is that, when a button is pressed I don't know how to call the function of other class.
Comment: where is your main class? share it
Comment: @xxlali Can you tell me how to add code ?
Comment: @xxlali But the code is too large to comment. Is there a solution ?
Comment: don't to commet but to your question. you can edit your post, while editing copy yout code to your post
Comment: @xxlali When I tried to edit, some errors are coming. I don't know how to solve it.
Comment: @xxlali  Can you tell me how to add code without errors ?
Answer: I'm pretty sure you should only have one class that extends from Application and only the start method of this class should be called. For multiple windows try using different
Stages
Comment: Should look something like this:
http://java-buddy.blogspot.co.at/2012/12/open-new-window-in-javafx-2.html

Connecting 2 classes in javafx


Por quê a aplicação pára se deixo o campo vazio?

Question: public class VigMetBiapsb extends Activity {

int porctAlt, porctLarg;
double edtVaoNum;

EditText edtVao;
Button calcBiapsb;
TextView secaoBiapsb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.vigmet_biapsb);

    edtVao = (EditText) findViewById(R.id.vao);

    calcBiapsb = (Button) findViewById(R.id.calc_biapsb);

    porctAlt = 6;
    porctLarg = 60;

    calcBiapsb.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            edtVaoNum = Double.parseDouble(edtVao.getText().toString());
            if(edtVao.getText().toString().equals("")){
                secaoBiapsb = (TextView) findViewById(R.id.valorsec);
                secaoBiapsb.setText("Dado inválido!");
            }
            else {
                double alt = edtVaoNum * porctAlt;
                double larg = alt / 100 * porctLarg;

                secaoBiapsb = (TextView) findViewById(R.id.valorsec);
                secaoBiapsb.setText(String.valueOf(alt)+" x "+String.valueOf(larg));
             }
        }
    });

    } //fecha onCreate
}

Se preencho o edtVao, tudo é executado corretamente, mas se deixo o edtVao vazio, a aplicação fecha quando toco o botão calcBiapsb.
O trecho edtVao.getText().toString().equals("") dentro do if não deveria evitar isso? Como eu poderia checar se o campo está vazio ou não? (lembrando que o que é recebido do campo é passado para uma variável double)
Answer: O erro ocorre antes da checagem que você está fazendo.
Sua aplicação fecha porque ao clicar no botão o aplicativo tenta extrair um número de tipo double do texto contido em edtVao, que está vazio. Preste atenção nesta linha:
edtVaoNum = Double.parseDouble(edtVao.getText().toString());

O conteúdo de edtVao.getText().toString() é uma string vazia (""), ou seja, que não contém um número double válido. Desta forma, a execução é equivalente a Double.parseDouble(""), que gera uma exceção do tipo NumberFormatException.
Procure prestar atenção no log gerado pelo erro (logcat), nele é citada qual exceção ocorreu, uma descrição do erro, e em qual linha do código ele ocorreu.
Comment: Corrigi movendo esta linha para dentro do `else`. Obrigado!


Installed Boost module. How do you tell it is working on your site?

Question: I just installed the Boost module on Drupal 7 and activated everything properly. How do I even tell if its working properly?
Comment: Option 1: You can check the Drupal Status Report for your Boost installation in  Administer > Reports > Status report (admin/reports/status). Option 2:  Also, open your web page source code. Scroll down to the last line. It will show how long your page has been cached by boost module.
Answer: View the source code of the page as you're browsing as an anonymous user. Boost inserts some metadata about the cached page ("Page cached by...") as an HTML comment:
<code>  // Add note to bottom of content if possible.
  if ($_boost['matched_header_info']['comment_start'] && $_boost['matched_header_info']['comment_end']) {
    $expire = $_boost['matched_header_info']['lifetime_max'];
    $cached_at = date('Y-m-d H:i:s', REQUEST_TIME);
    $expires_at = date('Y-m-d H:i:s', REQUEST_TIME + $expire);
    $note = "\n" . $_boost['matched_header_info']['comment_start'] . 'Page cached by Boost @ ' . $cached_at . ', expires @ ' . $expires_at . ', lifetime ' . format_interval($expire) . $_boost['matched_header_info']['comment_end'];
    $data .= $note;
  }
</code>


Support vs smallest closed subset with probability $1$

Question: Let $(X,d)$ denote a metric space and $\mu$ be a Borel probability measure on $X$.
I thought that the support of $\mu$ was defined as the smallest closed subset $A$ such that $\mu(A)=1$. However, upon checking Wikipedia I see that the definition is more complicated and involves open subsets of $X$.
Is there a less general setting in which the support of $\mu$ coincides with the smallest closed subset $A$ such that $\mu(A)=1$ ?
Comment: Note in general there does not have to *exist* a smallest closed subset of measure 1.  Counterexamples include things like a [measurable cardinal](https://en.wikipedia.org/wiki/Measurable_cardinal) equipped with a discrete metric.  Every set is closed, and there are no point masses.  So given any closed set of measure 1, you can delete one point and have a smaller closed set of measure 1.  If you intersect all the closed sets of measure 1, you get $\emptyset$ whose measure is 0.
Comment: Why did you delete [this question](https://math.stackexchange.com/questions/4785169/minimize-sum-j-1n-p-j1-p-jq-2-under-the-constraint-sum-j-1n-p) recently? Anything wrong?
Comment: @RiverLi Yes, I made an important mistake with respect to my work: I need to maximize the objective (not minimize as stated in the question).
Comment: @Marloumarlou OK. Thanks. It is an interesting problem.
Answer: An assumption on $\mu$ where you can guarantee that $C$ exists is that if $O_{\alpha}, \alpha \in A$ are open sets and $\mu(O_{\alpha}) = 0$ for all $\alpha$, then $\mu(\bigcup_{\alpha \in A}O_{\alpha}) = 0$. In this setting, you let $C^c$ be the union of all open sets $O$ with $\mu(O) = 0$.
This assumption on $\mu$ holds if $(X, d)$ is second-countable (equivalent to separability).