Dismissing dialog with Escape key with nested navigator

Question: I'm writing a Flutter app targeted towards macOS and want to be able to show a modal dialog that allows navigation within that dialog (somewhat like a sequence of onboarding screens).
In order to facilitate the navigation within the dialog, I need to wrap my widgets in a navigator of some sort. See the following (simplified) code:
showDialog(
  context: context,
  builder: (context) => Dialog(
    child: SizedBox(
      width: 400,
      height: 400,
      child: Navigator(
        onGenerateRoute: (_) => MaterialPageRoute(
          builder: (_) => const Center(child: Text('hi there'))
        ),
      ),
    ),
  ),
);

Now this works perfectly - except for dismissal. I can dismiss the dialog by tapping in the barrier area (which is good), however, pressing ESC on the keyboard doesn't dismiss the dialog.
If I just embed the child directly (without the navigator), pressing ESC dismisses the dialog perfectly. But for some reason, it looks like Navigator is swallowing the ESC key. I've also tried using MaterialApp as the navigator and it also eats the ESC key.
Any theories on how I can get the navigator to let me dismiss the dialog using the ESC key? Thanks
Answer: You can use a RawKeyboardListener to listen to keypresses, and pop when an ESC event fired.
Old response that didn't work: Try wrapping the widget inside the page route (in this case, the Center) with a WillPopScope. You should be able to receive the ESC event on the onWillPop callback before the inner Navigator receives it, then you can call pop on the outer Navigator to dismiss the dialog.
Comment: That's a neat idea, but sadly `onWillPop()` doesn't get called (either when you press ESC or if the dialog gets dismissed by clicking on the barrier)
Comment: One other idea is to use a RawKeyboardListener to listen to keypresses, and pop when an ESC event fired.


Concatenate the values from two arrays where the same index is shared

Question: Here is an example...
I have the following code:
$a = array("a", "b", "c");
$b = array("1", "2", "3");

$c = array_merge($a, $b);

echo "
";
var_dump($c);
echo "
";

Gives me an output:
array(6) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "1"
  [4]=>
  string(1) "2"
  [5]=>
  string(1) "3"
}

How could I change the code so that it gives me this output instead:
array(3) {
  [0]=>
  string(5) "a','1"
  [1]=>
  string(5) "b','2"
  [2]=>
  string(5) "c','3"

Comment: What is the purpose ?
Comment: array_combine uses one array for keys and the other for values so wouldn't get the results the @Vytautas has asked for
Comment: yeah, array_combine is quite irrelevant to the asker question
Answer: $c = array_map(function ($a, $b) { return "$a','$b"; }, $a, $b);

For whatever that's good for...
Answer: Using SPL's MultipleIterator:
$a = array("a","b","c");
$b = array("1","2","3");

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($a));
$mi->attachIterator(new ArrayIterator($b));

$c = array();
foreach($mi as $row) {
    $c[] = $row[0] . "','" . $row[1];
}

var_dump($c);

Comment: Just having fun, playing a lot with SPL at the moment: you went simple, I've gone complex
Comment: @Vytautas - overkill for this trivial problem; but can do some clever stuff with it when arrays are unequal length, or mismatched keys, or associative/numeric indexes, or you're trying to iterate across a large number of arrays concurrently, etc - http://www.php.net/manual/en/multipleiterator.construct.php
Answer: If the keys to both arrays are always in parity, you could do something like
foreach ($a as $key => $value) {
    $newArray[] = "$value','{$b[$key]}";
}

var_dump($newArray);
// would output the below
array(3) {
[0]=>
  string(5) "a','1"
  [1]=>
  string(5) "b','2"
  [2]=>
  string(5) "c','3"

However, the result looks a little weird, are you sure this is what you are trying to achieve?
Answer: $a=array("a","b","c");
$b=array("1","2","3");

if(count($a) > count($b)){
  foreach($a as $key => $value)
      $c[$key] = isset($b[$key])? $value.",".$b[$key] : $value;
} else {
    foreach($b as $key => $value)
      $c[$key] = isset($a[$key])? $a[$key].",".$value : $value;
}

Use above code it will for your array.


(Re)named std::pair members

Question: Instead of writing town->first I would like to write town->name. Inline named accessors (Renaming first and second of a map iterator and Named std::pair members) are the best solutions I have found so far. My problem with named accessors is the loss of type safety:
pair<int,double> may refer to struct { int index; double value; } or to struct { int population; double avg_temp; }. Can anyone propose a simple approach, perhaps something similar to traits?
I often want to return a pair or a tuple from a function and it is quite tiring to introduce a new type like struct city { string name; int zipcode; } and its ctor every time. I am thrilled to learn about boost and C++0x but I need a pure C++03 solution without boost.
Update
Re andrewdski's question: yes, a (hypothetical) syntax like pair<int=index, double=value> which would create a distinct type from pair<int=population, double=avg_temp> would meet your requirement. I do not even mind having to implement a custom pair/tuple template class ONCE and just passing a 'name traits' template argument to it approprietly when I need a new type. I have no idea how that 'name traits' would look like. Maybe it's impossible.
Comment: How is this not a real question? Why the downvote?
Comment: @Bo Persson There is std::tuple / boost::tuple for larger objects.
Comment: @Bo Persson: you should read the question first before downvoting: **where did I mention inheritence?**
Comment: Maybe the problem is people aren't quite understanding what you are asking for.  You say you want to distinguish between `struct { int index; double value; }` and `struct { int population; double avg_temp; }`, but you want to do this simply by renaming pair members?  How in the world would that work?  It sure seems like you want a struct.  (And for the record, I did not downvote.)
Comment: So a (hypothetical) syntax like `pair` which would create a distinct type from `pair` would meet your requirement?
Comment: @Bo: Downvoting without comment is justified because someone doesn't understand something or has a misunderstanding? You must have downvoted every question, then. (Note he never said anything about inheritance anyway, so I'm not quite sure what your point is.)
Comment: @Bo Persson I agree – inheriting from std::pair or whatever is stupid. I just wanted to say why we do not need a std::triple and std::quad.
Comment: I would like to know that too.
Comment: @GMan - The downvote is for the thought that every object with two members should inherit from std::pair and rename the members. Do we need std::triple and std::quad for larger objects?!
Comment: @andrewdski: Yes, you see my problem correctly. I would like to reuse std::pair, and rename its members SOMEHOW. If I knew the answer how, I would not ask this question. :)
Comment: @Karl - But these are for types with unnamed members.
Comment: @Ali This could be a job for macros to create the structures you need, if you just want to save yourself a bit of typing each time
Comment: @Ali - How else would your types get at the members of a pair?
Comment: @GMan - I downvoted during the 30 minutes before he edited the question. It was just not comprehensible. How do you modify a class without inheriting from it?!
Comment: @Bo Persson: I have never mentioned inheritence, you can easily check the history. By traits, you can attach info to classes, without changing them. I do not know how that would work in this case, hence the question.
Comment: @andrewdski: Yes. I do not even mind having to implement a custom pair/tuple template class ONCE and just passing a 'name traits' to it approprietly at each case I need a new type. However, reusing std::pair is preferred.
Comment: @Ali - You can't change member names with traits, can you? And you can't modify a class' behavior without inheriting and override virtual functions.  I just found the initial question really silly because of this, but obviously people disagree.
Comment: @Bo Persson: in the original question, where did I write about changing behavior?
Comment: Hmmm it appears I missed the part where you said you didn't want to employ boost :) in that case @dalle's answer should be ok (other than the 'just use a struct' choir, that is right but boring)
Answer: I don't see how you can possibly do better than
struct city { string name; int zipcode; };

There's nothing non-essential there.  You need the types of the two members, your whole question is predicated around giving names to the two members, and you want it to be a unique type.
You do know about aggregate initialization syntax, right?  You don't need a constructor or destructor, the compiler-provided ones are just fine.
Example: http://ideone.com/IPCuw

Type safety requires that you introduce new types, otherwise pair<string, int> is ambiguous between (name, zipcode) and (population, temp).
In C++03, returning a new tuple requires either:
city retval = { "name", zipcode };
return retval;

or writing a convenience constructor:
city::city( std::string newName, int newZip ) : name(newName), zipcode(newZip) {}

to get
return city("name", zipcode);

With C++0x, however, you will be allowed to write
return { "name", zipcode };

and no user-defined constructor is necessary.
Comment: You beat me to it. I should add however that with `string` the aggregate initialization syntax will not work.
Comment: might be good to expand on aggregate initialization syntax for the general google audience
Comment: @Ben: I didn't know it worked with `std::string` inside. Gcc accepts it with `-ansi`. Please don't take my first comment into account then.
Comment: @Alexandre: It would be quite problematic if this wasn't allowed: array initialization uses the same *aggregate initializer*.
Comment: @Ben Voigt: Upvoted and thanks. Unfortunately extended initializer list is not available in C++03, you cannot write `return { "new york", 10001 };` at the end of a function. So you still have to write a ctor and write `return city("new york", 10001);`. I need a pure C++03 solution.
Comment: @Ali: What's wrong with `city retval = { "new york", 10001 }; return retval;` ?  After "Named Return Value Optimization", which pretty much all modern compilers do, it'll be the same.
Comment: @Ben Voigt: Partly my lack of knowledge. :) On the other hand, I would rather write a ctor once than write an extra line every time a city is returned. C++0x will solve this problem. Thanks!
Comment: @Ben Voigt: I would like to accept your answer but please add the followings to it. (1) You have to introduce new types otherwise you cannot have both `typedef pair city;` and `typedef pair building;` (2) In C++0x you will be able to write `return { "new york", 10001 };` (3) In the meantime you either write the ctor once or add an extra line `city retval = { "new york", 10001 }; return retval;` every time a city is returned. Thanks!
Comment: @BenVoigt The link for ideone is dead and not available on the internet archive - do you know of a replacement?
Comment: @bluefeet: No, it's unfortunate that ideone's ToS declare that it is a place to publish source code snippets "Forever", but in reality they destroy user-owned material and do not respond to inquiries.  I've basically stopped using it for that reason.
Comment: @BenVoigt Sorry for the late reply but have you had this issue with coliru at all?  That is what I primarily use for live examples.
Answer: I guess elaborating on
struct City : public std::pair<string, int> {
  string& name() { return first; }
  const string& name() const { return first; }
  int& zip() { return second; }
  int zip() const { return second; }
};

is the closest you get to what youre looking for, althrough struct City { string name; int zipcode; } seems perfectly fine.
Comment: quoting the question: _Inline named accessors ([1](http://stackoverflow.com/q/1500064/341970), [2](http://compgroups.net/comp.lang.c++.moderated/Named-std-pair-members)) are the best solutions I have found so far_
Answer: Although not perfect, it is possible to use tagged data:
template <typename tag_type, typename pair_type>
typename tag_type::type& get(pair_type& p);

typedef std::pair<std::string /*name*/, int /*zipcode*/> city;
struct name { typedef std::string type; };
struct zipcode { typedef int type; };

template <>
std::string& get<name, city>(city& city)
{
   return city.first;
}

template <>
int& get<zipcode, city>(city& city)
{
   return city.second;
}

int main()
{
   city c("new york", 10001);
   std::string n = get<name>(c);
   int z = get<zipcode>(c);
}

But as Ben Voigt says: struct city { string name; int zipcode; }; would pretty much always be better.
EDIT: Templates probably are an overkill, you could use free functions in a namespace instead. This still does not solve type safety issues, as any std::pair<T1, T2> are the same type as any other std::pair<T1, T2>:
namespace city
{
   typedef std::pair<std::string /*name*/, int /*zipcode*/> type;

   std::string& name(type& city)
   {
      return city.first;
   }

   int& zipcode(type& city)
   {
      return city.second;
   }
}

int main()
{
   city::type c("new york", 10001);
   std::string n = city::name(c);
   int z = city::zipcode(c);
}

Comment: Gonna have to upvote this... it is precisely what my suggestion (boost::bimaps) does
Comment: Thanks for your efforts to answer my question. However I still do not get it. Why do you have those typedefs in the structs? They seem to be unused. And the type safety issue is not solved, you cannot have another `typedef std::pair building;`. That was my problem with named accessors.
Comment: @Ali: All `std::pair` are the same type as any other `std::pair`. If you want type safety you need to use different types.
Comment: Yes, I know. I do not even mind having to implement a custom pair/tuple template class ONCE and just passing a 'name traits' template argument to it approprietly when I need a new type. I have no idea how that 'name traits' would look like. Maybe it's impossible. Do you see what I would like to have?
Comment: upvoted your answer and thanks. Maybe a plain `struct city { string name; int zipcode; };` is really the simplest solution, and with C++0x I will be able to use aggregate initialization.
Answer: Since std::pair is commonly used for storing entries in std::map containers, you might want to look at tagged elements in Boost Bimap.
Synopsis:
#include <boost/bimap/bimap.hpp>
#include <string>
#include <iostream>

struct name {}; // Tag for the default 'first' member
struct zipcode {}; // Tag for the default 'second' member

int main()
{
    using namespace boost::bimaps;
    typedef bimap <tagged<std::string, name>, tagged<int, zipcode> > Cities;
    typedef Cities::value_type registration;

    Cities cities;
    cities.insert(registration("Amsterdam", 20));
    cities.insert(registration("Rotterdam", 10));

    // ...
    std::string cityName;
    std::cin >> cityName;

    Cities::map_by<name>::const_iterator id_iter = cities.by<name>().find(cityName);
    if( id_iter != cities.by<name>().end() )
    {
        std::cout << "name: " << id_iter->get<name>() << std::endl
                  << "zip: " << id_iter->get<zipcode>()   << std::endl;
    }

    return 0;
}

Note that bimaps can transparently emulate std::map or other associative container types without performance cost; They just are more flexible. In this particular example, the definition would most likely best be changed into something like:
typedef bimap <tagged<std::string, name>, multiset_of<tagged<int, zipcode> > > Cities;
typedef Cities::value_type registration;

Cities cities;
cities.insert(registration("Amsterdam", 20));
cities.insert(registration("Rotterdam", 10));
cities.insert(registration("Rotterdam", 11));

I invite you to wander around the documentation for Boost Bimap to get the full picture
Comment: Thanks for your answer. I am happy to learn more about boost. Please see my comment sehe's answer, I have some problems understanding it.
Answer: You can use pointer-to-member operators. There are a few alternatives. Here is the most straightforward.
typedef std::map< zipcode_t, std::string > zipmap_t;
static zipcode_t const (zipmap_t::value_type::*const zipcode)
                                              = &zipmap_t::value_type::first;
static std::string (zipmap_t::value_type::*const zipname)
                                              = &zipmap_t::value_type::second;

// Usage
zipmap_t::value_type my_map_value;
std::string &name = my_map_value.*zipname;

You can put the accessors for one pseudo-type into a dedicated namespace to separate them from other things. Then it would look like my_map_value.*zip::name. But, unless you really need to use a pair, it's probably easier to just define a new struct.
Comment: Yes, I believe the code is the easiest to understand if one defines a new struct. If I have to use pairs, I will use inline accessors. Anyway, thanks for the answer, upvoted!
Answer: I came up with a Utility_pair macro that can be used like this:
Utility_pair(ValidityDateRange,
    time_t, startDay,
    time_t, endDay
);

Then, whenever you need to access the fields of ValidityDateRange, you can do it like this:
ValidityDateRange r = getTheRangeFromSomewhere();

auto start = r.startDay(); // get the start day
r.endDay() = aNewDay();    // set the end day
r.startDay(aNewDay1())     // set the start and end day in one go.
 .endDay(aNewDay2());

This is the implementation:
#include <utility>

#define Utility_pair_member_(pairName, ordinality, type, name)      \
    const type &name() const { return ordinality; }                 \
    type &name() { return ordinality; }                             \
    pairName &name(const type &m) { ordinality = m; return *this; } \
/***/

#define Utility_pair(pairName, firstMemberType, firstMemberName, secondMemberType, secondMemberName) \
    struct pairName: std::pair<firstMemberType, secondMemberType>  {                                 \
        Utility_pair_member_(pairName, first, firstMemberType, firstMemberName)                      \
        Utility_pair_member_(pairName, second, secondMemberType, secondMemberName)                   \
    }                                                                                \
/***/

Answer: Probably not worth the extra memory, but if you want to retain the advantage of std::pair or std::tuple/ maintain compatibility with an unchangeable API, you can inherit from them and then define references to their members.
Apart from the memory cost, this comes with the giant caveat that STL types generally don't have virtual destructors and can thus cause memory leaks if you attempt to de-allocate using a pointer to the base type:
#include <tuple>

struct PairShadow : public std::pair<int, double> {
    using std::pair<int, double>::pair;
    PairShadow & operator=(PairShadow const &) { /*call parent op here*/ }
    int & x = this->first;
    double & y = this->second;
};

struct TupleShadow: public std::tuple<int, double> {
    using std::tuple<int, double>::tuple;
    PairShadow & operator=(PairShadow const &) { /*call parent op here*/ }
    int & x = std::get<0>(*this);
    double & y = std::get<1>(*this);
};

auto main() -> int {
    auto twinShadow = PairShadow(1,3.0);
    auto tupleShadow = TupleShadow(1,3.0);
    return tupleShadow.y;
}

Alternatively, and perhaps preferrably as mentioned by @holyblackcat you could also just define an overload to std::get<int>(PairShadow) for your struct in many cases as long as you aren't trying to conform to an unchangable API which specifically requires a std::pair or std::tuple
Comment: This comes with memory (and probably performance) overhead, and makes the tuple non-assignable. IMHO a better option is to use a regular `struct`, like the accepted answer suggests, and possibly specialize `std::get` (and related functions) for it.
Comment: I very much agree that it's probably better to use the regular struct, and this has unnecessary memory cost, the assignment issue however can be resolved by defining the assignment operator though clearly with an annoying lose of concision. I'll add some more caveats.
Answer: Old question, but adding an update for C++17 where you can use Structured binding declaration for naming the members of std::pair and std::tuple. For example:
std::list<std::pair<std::string, long>> getCitiesAndPopulations();
. . .
for(const auto& [city, population] : getCitiesAndPopulations())
    std::cout << "City: " << city << ", population: " << population << std::endl;

Note: This doesn't address the type safety aspect.
Answer: I think you should really introduce new types here. I am totally on stl's side in terms of having a pair class, but this is the exact reason why java people argue they don't want to have a pair class and you should always introduce new types for your piar-like types.
The good thing about the stl solution is that you can use the gerneric class pair, but you can introduce new types / classes whenever you really want members to be named in a different way than first/second. On top of that introducing new classes gives you the freedom of easily adding a thrid member if it should ever become necessary.
Answer: perhaps you can inherit your own pair class from pair and set two references called name and zipcode in your constructor ( just be sure to implement all constructors you will use )
Comment: `std::pair` does not have a virtual destructor, so this could lead to accidental memory leaks.
Comment: That's not the problem. If *anything* gets added to the class that requires destruction, those destructors will not be called by anything that only takes an `std::pair` http://www.codersource.net/c/c-miscellaneous/c-virtual-destructors.aspx
Comment: Thanks. But if you introduce a new type, why not introduce struct city { string name; int zipcode; } in the first place?
Comment: @Travis: yes, you should declare your own destructors (which will call parent's destructors) as well as constructors @Ali: by inheriting from pair you can use all its functionality ( for example when a predefined function needs pair as it's argument, compiler will autocast your type to pair if you use your ownPair inherited from pair )

(Re)named std::pair members


Shadow mapping with a deferred rendering

Question: I am trying to implement a shadow mapping technique and I have some problems to make it works.
I have a camera in the light's position and this is the shadow map I get. All the vertex have been multiplied by each modelViewProjectionMatrix.

I also have a texture with the world positions of the vertex. It's a GL_RGBA32F texture because all the points have been multiplied by each ModelMatrix to have the points in world space.

And the shader:
layout(binding=5) uniform sampler2D shadowMap;
layout(binding=6) uniform sampler2D positionMap;

in vec2 texcoord;
uniform mat uViewProjectionMatrix;

out vec4 color;

void main() {

   vec4 pos = texture(positionMap, texcoord);

   vec4 ShadowCoord = uViewProjectionMatrix * pos;
   ShadowCoord.xy = ShadowCoord.xy * vec2(0.5,0.5) + vec2(0.5,0.5);

   float a = texture(shadowMap, ShadowCoord.xy).z;
   color = vec4(a, a, a, 1.0);
}

The output (the camera is almost in the same position of the light):

I am just trying to see if the projection of each vertex is right from the camera's position but looks like it's not.
The point of all this is to compare:
if ( texture(shadowMap, ShadowCoord.xy).z <  ( ShadowCoord.z-bias ) )

but it also doesn't work.
I would appreciate any help.
Thank you.
Answer: You are missing the perspective divide and you seem to be completely ignoring depth range.
The general idea here is to get ShadowCoord.xyz into the range [0,1] (for texture lookup and depth comparison). Your code operates under the assumption that uViewProjectionMatrix * pos (clip-space coordinates) is in the range [-1,1] but that is not really guaranteed unless you divide by w (NDC coordinates).
I would consider something like this instead:
void main() {
  vec4 pos = texture(positionMap, texcoord);

  vec4 ShadowCoord = uViewProjectionMatrix * pos;
  ShadowCoord /= ShadowCoord.w;

  ShadowCoord.xyz = ShadowCoord.xyz * vec3 (0.5f, 0.5f, 0.5f) + vec2 (0.5f, 0.5f, 0.5f);

  float a = texture(shadowMap, ShadowCoord.xy).z;
  color = vec4(a, a, a, 1.0);
}

After this, ShadowCoord.xy will be a texture coordinate to lookup in your shadow map, and ShadowCoord.z will be the current fragment's depth from your light's point of view. You can use ShadowCoord.z for comparison versus the sampled depth.
In fact, you might even consider using a sampler2DShadow to do this more efficiently. For an example of that, see this related question and answer
Comment: In case it was not clear in the answer, I also adjusted your code so that it scales and biases the clip-space `z` coordinate into the range [**0**,**1**] (from [**-1**,**1**]). The value fetched from the shadow map is going to be in [**0**,**1**] so you cannot ignore that step. You need to do it for `xyz`, not just `xy` like you were originally.
Comment: A 'gotcha' with sampler2DShadow is that is samples using nearest even if linear is used for the min/mag filters. This can be confusing if you were looking to reduce shadow acne by utilizing linear interpolation on the shadow map depth. See http://gamedev.stackexchange.com/questions/88187/c-opengl-shadowmap-issue-artifacts
Comment: @PaulRenton: Indeed, what it actually interpolates is the result of the 4 binary pass/fail depth tests for the 4 nearest neighbor depth samples. That's explained in the answer I linked to.
Comment: Wow! That was the problem. I have already tried to divide by w but I forgot to do the multiplication and the addition in the z component... so when i compared the depths... weird things happened.

Thank you very much for your time.


Finding all the solutions to a complex equation

Question: I am asked to find all the solutions to $z^{42}=-1$. I go a head and square root both sides to produce $z^{21}= i$. Then I can write $z^{21}= r^{21} (\cos(21\ θ) + i\sin(21\ θ)) = 0+i. $ Hence $\cos(21\ θ)= 0$ and $\sin(21\ θ)=1$, as $r^{21} $ can't be equal to $0$. Therefore $21θ $ = ${π \over 2} $ and $ θ = {π\over42}$. Then using $\sin(21\ θ)=1$,  I can write  $r^{21}=1 $ and produce that $r\pm1$ $\ $so my answer would be $z=\pm \cos({π\over42}) + i\sin({π\over42}). $
My answer doesn't produce the cleanest numbers so I'm a little worried but I do believe the process is correct.
Comment: This equation has 42 solutions.
Comment: Try expressing the solutions in polar coordinates.
Comment: hehe Thanks, worked from a too basic example question.
Comment: "I go ahead and square root both sides to produce $z^{21} = i$" - don't do this!
Comment: If $z^{42}=-1$ then $z^{21}=\pm i$
Answer: You could just come to my consulting hour tomorrow :-)  Hint: no need to square root. We did an example like this in class.
Answer: Hint: where $n$ is an integer,
$$z^{42}=-1$$$$(re^{i\theta})^{42}=1e^{i \pi }$$
$$r^{42}e^{i 42\theta}=1e^{i(\pi+ 2 \pi n)}$$
Note $r\ge 0$ (by definition), and that $e^{i2\pi n}=1$.


How to apply one AJAX to all form elements?

Question: #ajax is

used by: button, checkbox, checkboxes, image button, password, radio, radios, select, submit, tableselect, textarea, text_format, textfield

Sadly, form is not on the list. But on one form, I need to apply ajax to all form elements. With possible exception of submit button, but it will be hidden if javascript works, so it is not an issue, literally all elements is OK.
Is there any neat way to do it?
Currently I'm writing something like this:
$ajax_code = array(
  'callback' => 'poll_choice_js',
  'wrapper' => 'poll-results',
  'method' => 'replace',
  'effect' => 'fade',
);

And then in each element:
  '#ajax' => $ajax_code,

But it will be easy to forget to add this line to some elements in future, so I'm looking for a way less prone to errors.
Reason: My wrapper is actually outside a form and is used for preview, I need to update preview every time anything changes. Form will never need to be submitted. Ajax will never change form elements.
Comment: I don't that's a very common request, as you're adding the same ajax behavior to every element of the form I don't think there's anything that behaves that way in core or other modules I've seen.
Comment: `foreach (element_children($form) as $key) { $form[$key]['#ajax'] = array(...); }` in a recursive function is the only way, really. I've never seen anything built in for that
Comment: @Clive Boo, I believed there must be something and I'm just missing it :/
Answer: I don't believe there's anything 'built in' for that, but a small recursive function would handle it:
function _MYMODULE_apply_ajax(&$element, $ajax) {
  $element['#ajax'] = $ajax;
  foreach (element_children($element) as $key) {
    _MYMODULE_apply_ajax($element[$key], $ajax);
  }
}

Where you apply this kind of depends what you need. You could add it at the end of the form function itself, but if there's a chance your form could be altered it would be best in hook_form_alter(). Either way just call
_MYMODULE_apply_ajax($form, $ajax_array);

Comment: Thanks. At least now I know it's not the case of me missing something.


Slowing down a physics defying spring

Question: I am doing a tutorial for my physics class.
I made a program that should have a cart on a box that is moved by a spring and should slow down to a stop, however, when I run it, it appears the spring is accelerating the cart (no matter which things I negate.)
I have heard that it might be an issue with vPython rounding numbers resulting in the acceleration, if this is true, can I just make all the numbers 1000 times larger and would it fix it?
Thanks!
from visual import *
from visual.graph import *

length=1.0

track=box(pos=vector(0,-0.05,0),
          size=(length, 0.05, 0.10),
          material=materials.bricks,)

# creates the track which is "length"meters in the
# x direction, 0.05m tall, and 1m deep
start=-0.5*length+0.05

cart=box(pos=vector(start+0.01,0,0),
         size=(0.1,0.05,0.1),
         color=color.green)
k=-4
#spring constant

sprL=(start-0.05)-0.1

#sets position of left end of spring
spring=helix(pos=(sprL,0,0),
             axis=((cart.x-0.05)-sprL,0,0),
             radius=0.02,
             color=color.yellow)

cart.m=0.70
#mass of cart
cart.vel=vector(0,0,0)
#initial velocity of cart
cart.force = k*(cart.x)*vector(1,0,0)
#force of the spring
cart.accel=cart.force/cart.m
#acceleration of the cart taking into account the fan
t=0
deltat=0.01
end=0.5*length-0.05
#defining the end of the track
gdisplay(x=100,
         y=500,
         xtitle='time (sec)',
         ytitle='X (cyan), Px (red)')

xcurve = gcurve(color=color.cyan)
pcurve= gcurve (color=color.red)

while cart.x<end+0.01 and (cart.x>(start-0.01)):
    #we include -0.01 so the cart does not fail immediately upon start...
    cart.pos = cart.pos + cart.vel*deltat+(0.5)*(cart.accel)*deltat**2
    #x equals x naught plus v times delta t plus one half a delta t squared
    #note that ** means "to the power of"
    xcurve.plot(pos=(t,cart.x))
    pcurve.plot(pos=(t,cart.vel.x))
    cart.vel=cart.vel+cart.accel*deltat
    #new velocity is old velocity plus acceleration times time
    cart.force=k*(cart.x)*vector(1,0,0)
    cart.accel=cart.force/cart.m
    spring.axis=((cart.x-0.05)-sprL,0,0)
    t=t+deltat
    #increments time
    rate(100)
    #rate means no more than 100 loops per second

Comment: I don't understand, where in your code do you set a dissipative force?  The box will never lose energy without one.
Comment: I made the spring constant (k) negative so then cart.force is negative, resulting in cart.accel being negative, resulting in cart.pos decreasing (in the while loop) due to cat.acceleration being subtracted from it. Making the spring constant positive, results in the box going to the left for a small amount of time then the program stopping.
Comment: Are you looking for a [damped harmonic oscillator](http://en.wikipedia.org/wiki/Harmonic_oscillator#Damped_harmonic_oscillator)?
Answer: You don't have a dissipative force in your system (one that leaks energy out of it).  The equation F = -kx conserves energy (this is the equation that you have somewhat circuitously encoded and represents the force that a spring exerts on an object).  Note that the equation there doesn't mean that the force is always negative, it simply points in the opposite direction of cart.pos.  This is how you get the sinusoidal motion.
A dissipative force is needed for the object to actually slow down.  The quintessential example of this would be represented by F = -kx -bv for some constant b and v is the velocity of your object.  This represents your spring being slowed down by a fluid (air/water/whatever you like).
The minimal change to your code in this case would be inside your loop:
    cart.force=(k*(cart.x)-0.1*cart.vel.x)*vector(1,0,0)

This produces an underdamped system, to try out an overdamped system you can set the 0.1 to 10 instead.

Slowing down a physics defying spring


Order of integration can be swapped if limits are constants, right?

Question: The order of integration can be easily swapped if the limits are constants, right?
$$\int_{a}^{b}\int_{c}^{d}f(x,y)dydx=\int_{c}^{d}\int_{a}^{b}f(x,y)dxdy$$
It only gets computationally hard if the limits are functions of each other, right?
$$\int_{a}^{b}\int_{c(x)}^{d(x)}f(x,y)dydx \neq \int_{c(x)}^{d(x)}\int_{a}^{b}f(x,y)dxdy$$
Sorry for the potentially trivial answer. Just doing a reality check over here.
Comment: You are correct.
Comment: When the limits are not constant, it's not just hard, it's impossible to change the order of integration (without changing the variables, and even then it's not always possible).
Comment: The integrals in your second expression are not just different, they are different objects as well - the left one is a constant, the right one is a function of $x$
Comment: @YuriyS Im not a mathematician. Although the notation is obviously wrong. I believe it also conveys the intended idea fairly intuitively also (as opposed to a more rigorous but convoluted one)
Comment: @Alan, the notation is fine (expression on the right hand side makes sense, but good manners suggest that you use another variable for the limits, like $\int_{c(t)}^{d(t)}$). Not in your post, obviously, but in the general sense
Answer: This is true in a very general sense, by Fubini's theorem.
In $\mathbb{R}^2$, the conditions for Fubini's theorem boil down to:

The integral of the absolute value over the specified range must be finite, in any one of the three senses that:

we integrate with respect to $x$ and then $y$
we integrate with respect to $y$ and then $x$
we integrate simultaneously over the entire surface

If this holds, then the values of all three of the above integrals are equal.

This is usually true over a compact (i.e. bounded and closed) range, because we're usually integrating continuous functions over those ranges, and continuous functions on compact sets are necessarily bounded in modulus.
Comment: Yes, pretty much. Tonelli's theorem is very closely related; you might see my answer referred to as the Fubini-Tonelli theorem.
Comment: Quick side question, can it be said that Fubini's theorem is essentially the foundation upon which the common iterated integral is based?


Class invariant to ensure a particular data type on a field does not hold

Question: Given the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;

using System;

public class Program
{
    public int[] ints = new int[1000];

  [ContractInvariantMethod]
  private void ObjectInvariant ()
  {
    Contract.Invariant(ints.GetType() == typeof(int[]));
    Contract.Invariant(ints != null);
  }
}

Why is the invariant ints.GetType() == typeof(int[]) considered to cannot be proven? If I change the invariant to ints.GetType() == ints.GetType() it passes (without any surpise), but why does it fail for typeof(int[]).
Answer: Sadly, you can in fact store objects in an int[] that aren't actually an int[].  There are some valid conversions that you would hope wouldn't be valid, but that in fact are.  For example, someone could write:
ints = (int[])(object)new uint[5];

and now the type of ints is an unsigned int array, not an int array.  That this conversion is valid is unfortunate (that it's valid almost exclusively just causes bugs when it comes up); it's be great if what you posted could be an invariant, but sadly, Contract.Invariant is correct that it's not.
Comment: I couldn't believe this first, but you are right. Is this crazy language (or CLR?) feature somewhere documented?
Comment: @cristid9 um...you wrote the code to check it.  It just has to be a runtime check, not a compile time check.  Now you can get an item from the array and treat it as an `int`.  It might not behave the way you want (you'd be treating an unsigned int's bits as if it were a signed int, giving you a messed up value) but you can do it.
Comment: @cristid9 Sure sounds like a really poorly designed assignment to me (unless there's more to it than you've described).  Probably worth bringing up with your instructor.
Comment: Then what's the right way to check that elemnts of `ints` are actually of type `int`?
Comment: @KlausGütter Off hand, I believe that the conversion is invalid in the C# type system (hence why it won't compile without the cast to `object`), but valid in the CLR, so the compiler will try to prevent the conversion but the CLR will allow it.
Comment: Thank you. In the meanwhile I found https://stackoverflow.com/questions/593730/why-does-int-is-uint-true-in-c-sharp where Jon's answer confirms what you say.
Comment: @KlausGütter Of course you probably don't *want* to go around checking for this whenever you've got an int array.  You probably just want to assume the int array is an int array, and if someone does something evil like this you just blame them for using your type in an inappropriate way.  Garbage in garbage out and all that.
Comment: Got it working with this one `Contract.Invariant(ints[0] is int);`
Comment: And interestingly `ints[0].GetType()` is typeof(int) even if `ints.GetType()` is typeof(uint[]).
Comment: @cristid9 In that case the code has already converted the `uint` to an `int` when it was returned by the indexer (it just has a mangled value by that point).  Also, what if the array is empty?
Comment: Man, it is a homework, all they ask me is to write an invariant to "Write the object (class) invariants that ensure that arrays represent sets
of Integers." So I think all I need to do is to check if `ints` contains ints and there are no duplicates in the array.


Binding Itemscontrol item

Question: My XAML is as under. I have a main ViewModel which has a list of items and I want to display a property within this list
<ItemsControl ItemsSource="{Binding MyList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>

        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The problem is that MyName is always blank although my list has two items.
The main VM class has this property below and I add items in the constructor
public ObservableCollection<InnerViewModel> MyList { get; set; }

My inner VM has
public class InnerViewModel
{
    private string _MyName;
    public string MyName
    {
        get
        {
            return _MyName;
        }
        set
        {
            _MyName = value;
            OnPropertyChanged("MyName");
        }
    }

I do have OnPropertyChanged in place but I'm not pasting it here for simplicity. I think the problem is with the XAML but I'm not sure. How do I get the property MyName to be displayed in my list of items in the view?
Answer: Since you use MyList as the ItemsSource, the data source for the child elements will be MyList. So you do not need to use the RelativeSource.
In other words, this should work :
    <ItemsControl ItemsSource="{Binding MyList}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>

            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

Answer: Try and remove the relative source part of the binding.
<DataTemplate>

</DataTemplate>

Comment: That works. Thanks but please explain in two lines that why should RelativeSource not work?
Comment: Because of the context. When you are using data templates the context of the binding is an item of the list.

Binding Itemscontrol item


Grails: How to serve different responses to error 500 depending on format (JSON, HTML)?

Question: I'm trying to serve different responses in Grails when an error 500 happens depending on the format of the request.
I've created an ErrorController and I'm using it in the URLMappings but I'm not getting the right request format:
<code>def handle() {
    withFormat {
        html {
            response.status = 500
            render(view:'/errors/serverError')
        }
        json {
            response.setContentType "application/json; charset=utf-8"
            response.status = 500
            ApiResponse apiResponse = new ApiResponse(
                meta: new ApiMeta(
                    code: 500,
                    errorType: "Whatever",
                    msgs: ["${request.exception}"]
                )
            )
            render apiResponse as JSON
    }
    }
}
</code>
The response is always in html. Also tried with 'request.withFormat' with the same results.
What I'm missing here?
Comment: +1 I have been trying to figure this one out as well ;( Also I want to be able to theme 500 pages
Answer: I do not have enough info to verify if this is really the reason, but it could look like a MIME type issue. Is json configured correctly as MIME type in your Config.groovy? Does your client accept your MIME type. See this link for reference http://grails.org/doc/2.1.0/guide/single.html#contentNegotiation
Comment: JSON is included as MIME in Config.groovy (Grails 2.1.1):
    json: ['application/json','text/json'],
Also I've been able to detect format in other controller actions.
Comment: It was indeed related to the MIME type. I wasn't accepting format in the "Accept" header. I changed 'grails.mime.use.accept.header' to true in Config.groovy and it works.
Answer: I'm not sure if this can solve your problem...but try error handling in URLMapping as you can see in http://grails.org/doc/latest/guide/theWebLayer.html#mappingToResponseCodes
You could catch any exception from your actions and throws an exception as JSONException when format request is JSON.
<code>"500"(controller: "error", action: "handleJsonException", exception: JSONException)
"500"(controller: "error", action: "handleHtmlException")
</code>
Comment: I've tried this solution but it didn't work. Adding a handler for JSONException will work but only if the exception caught is of that type, for example a parsing error.
Thanks anyway :)


finding the remainder of a variable n where n is not an integer multiple of 4

Question: I started off by saying that $(n+1)$ must be a multiple of $4$ for $n(n+1)$ to be a multiple of 4. Hence $n$ when divided by $4$ would have a remainder of $3$
i.e $n = 4k+3$
$n(n+1)=(4k+3)(4k+3+1)
= 4(k^2+7k+3)$
Hence $n(n+1)$ is a multiple of 4
I'm not sure if this explanation is adequate and how to progress from here if it is not. Please advise, thanks!
Comment: I'd possibly elaborate more on why it must be $n=4k+3$
Comment: Why are you proving that $n(n+1)$ is multiple of $4$? That's part of the hypothesis! Try to understand the LOGIC of the problem first.
Comment: Please make the body of your MSE questions self-contained. Don't rely on the title to state your problem.As for the maths: your observation that $n + 1$ is a multiple of $4$ is correct, so $n + 1 = 4k$ for some $k$ so that $n = 4(k-1) + 3$, which tells you that the remainder is $3$.
Comment: How do you know $n+1$ is multiple of $4$? (That is correct, but you probably need to argue why)
Answer: Let $n$ be a positive integer such that $4\mid n(n+1)$ and $4\nmid n$.
Suppose $n$ even : then $n+1$ is odd and thus $4$ and $n+1$ are coprime. By Gauss theorem, we see that $4\mid n$, a contradiction.
As a consequence : $n$ is odd and the same argument shows that $4\mid n+1$. Hence the remainder of $n$ divided by $4$ is $3$.
Answer: "$n(n+1)$ is an integer multiple of 4"
We know we can write integers as prime factors, so $n(n+1)$ has 4 in its prime factors, and there are only two cases for this to happen:

Both $n$ and $(n+1)$ are even, which is a refused case, because two successive numbers can't both be even.
$n$ and $(n+1)$, one of them has to be odd while the other is a multiple of 4, and we know from the given that $n$ is not a multiple of 4, which leaves us with the case that $n$ is odd while $(n+1)$ is a multiple of 4.

For the second part of the proof, I'm going to represent $(n+1)$ as $4k$ such that $k \in \mathbb{Z}$, this means that $n=4k-1$, then we can do this:
$$n = 4k - 1 +4 - 4 \\ = (4k -4) + (4-1) \\ = 4(k-1) + 3$$
And according to closure property for addition on integers, $(k-1)$ is also an integer. Then we calculate the reminder:
$$\frac n 4 = \frac {4(k-1) +3} {4} = (k - 1) + \frac 3 4$$
Which means we are left with 3.
Comment: Adren wrote the same thing before me but more summarised, he posted his answer while I was already writing sooo... no misunderstandings please
Answer: We know that for a natural number $n$, $n$ and $n+1$ is odd-even pair. Which means that one of them is odd , the other is even.
So $n(n+1)$ is divisible by $4$ if and only if the even term is divisible by $4$. Now since $n$ is not the even term, $n+1$ must be. So, $n+1$=$4k$. Hence $n=4t+3$ where $t$ is any natural number.


JQuery .ajax timeout increase not working

Question: I have a webpage where the javascript calls the PHP server using a POST request through the .ajax() function. The PHP server in turn calls an external third party API to submit a text analysis job. Once the text analysis job is processed, my PHP server queries the results from the API. However, the third party REST API does not provide any way to query the status of the job. So after I submit a job I put my program to sleep for about a minute and then query the results. However, sometimes my results are incomplete. I tried setting the sleeping time to be large but setting it to be longer than a minute seems to make the initial POST request from the Javascript to the PHP time out. Setting the ajax timeout parameter to be high doesn't help. Does anyone have suggestions on how this can be worked out? Any help is really appreciated.
The ajax request looks like this:
function callServer(params, success) {
    var url = "ie.php";
    $.ajax({
       type: 'POST',
       url: url,
       data: params,
       timeout: 60000000, //time out parameter doesn't work
       dataType: "json",
       success: function(result, textStatus) {
                    console.log(JSON.stringify(result, null, '  '));
            if (success) success(result);
       },
       error: function(xhr, textStatus, errorThrown) {
                    var text = 'Ajax Request Error: ' + 'XMLHTTPRequestObject status: ('+xhr.status + ', ' + xhr.statusText+'), ' +
                                            'text status: ('+textStatus+'), error thrown: ('+errorThrown+')';
                    console.log('The AJAX request failed with the error: ' + text);
                    console.log(xhr.responseText);
                    console.log(xhr.getAllResponseHeaders());
       }
    });
}

The error looks like this:
The AJAX request failed with the error: Ajax Request Error: XMLHTTPRequestObject status: (0, error), text status: (error), error thrown: ()
Comment: Why do you think this is caused by your timeout not working? Sounds like ie.php is the one returning an error. What do your error logs say?
Comment: Everything works if I reduce the wait time to less than 60 seconds. I tried to change the php.ini so that the max_execution_time is longer but that didn't help either.
Comment: What do the web server errors logs say on the box that hosts `ie.php`?
Comment: if you run ie.php in browser, what is the error ?
Comment: there is no error in the server logs..
Answer: There are multiple places in the whole process with timeout settings:

Browser / Ajax call
PHP has its own: ini_set('max_execution_time', '1800'); or
  set_time_limit(1800);
Apache itself has a max run time: Timeout apache2.conf
Possibly your REST API - however you are calling it

The best case scenario in my opinion is to change from a blocking / synchronous strategy to an asynchronous strategy:

Use ajax to send request from client to your server
Run REST API from your server asynchronously (look up asynchronous curl or node.js)
Client uses ajax to periodically query your server for status (maybe every 10 secs)

This makes the whole process asynchronous and doesn't require you to wait or block while the processing takes place
Comment: I'd like to add another place this happens is in IIS itself.  If you're running IIS and PHP via FastCGI, go into the FastCGI settings and play with the Idle Timeout, Request Timeout, and Activity Timeout (what it was for me) settings too.
Answer: Can you do this?
function callServer(params, success) {
    var url = "ie.php";
    setTimeout(function(){
        $.ajax({
           type: 'POST',
           url: url,
           data: params,
           dataType: "json",
           success: function(result, textStatus) {
                        console.log(JSON.stringify(result, null, '  '));
                if (success) success(result);
           },
           error: function(xhr, textStatus, errorThrown) {
                        var text = 'Ajax Request Error: ' + 'XMLHTTPRequestObject status: ('+xhr.status + ', ' + xhr.statusText+'), ' +
                                                'text status: ('+textStatus+'), error thrown: ('+errorThrown+')';
                        console.log('The AJAX request failed with the error: ' + text);
                        console.log(xhr.responseText);
                        console.log(xhr.getAllResponseHeaders());
           }
        })
    }, 200);
}

Answer: To fix timeout errors like these you need to set the timeout length in 3 or 4 different places:

Jquery itself (it can be done with the timeout parameter like you did, or globally with the $.ajaxSetup function)
PHP by setting max_execution_time in php.ini
Your web server (different for Apache and IIS.  For example, in IIS, if you're running PHP via FastCGI, you have to set Idle Timeout, Request Timeout, and Activity Timeout in your FastCGI settings)
Possibly your browser itself, though in the past this has not been necessary for me

If you set a timeout in all these places, it should work.  For me, I had done all the other steps like you but the problem was not fixed until I set the Activity Timeout setting in my FastCGI settings.


$\sigma$-algebra of coin tosses until first head

Question: Suppose that a coin is tossed until a heads is obtained. For this situation, what would be the tripe $(\Omega,\mathcal F, P)$?
For the sample space, I suppose it would be
$$\Omega := \{H, TH, TTH, TTTH, ...\}$$
Now, to properly define a probability measure such that for $n$ tosses we have $P( TT...TH)= 1/2^n$. I suppose we need to define an algebra where this probability measure works, and then expand using Caratheodóry. Am I correct in assuming this? If so, what would be the algebra to which I'd expand in order to use Caratheodory? Or does the $\sigma$-algebra of the set of all combinations (i.e. $2^\Omega$) works as my $\mathcal F$?
Comment: I would take $\Omega$ as the set of infinite sequences of points in {0,1} such that 1 occupies the entry which corresponds to the appearence of the first head and all other entries would be zero. I can't explain why, but I feel this would help make things preciser later on..
Answer: Your probability measure should be a function from your $\sigma$-algebra to $[0,1]$. For instance, you could take $\mathcal{F} = 2^\Omega$.
If you can just define the probability measure and $\sigma$-algebra right off the bat, I wouldn't bother thinking about caratheodory and premeasure nonsense. Here, your life is a bit easier because $\Omega$ is countable.
Comment: For the general case I am not sure off the top of my head. For this case, any element of $A \in 2^\Omega$ is an at most countable collection of strings of the form $TTT\cdots TTH$. Each of the strings in your subset $A$ represents a disjoint event and your measure is defined on each one.
Comment: How does the fact that is countable helps?
Comment: It means you won't have to worry about sets which are not measurable in your power set, like you have in the case of the Lebesgue measure (see e.g. the Vitali set)
Comment: I see. But I mean, how does one prove this assertion? That indeed the use of the power set is non-problematic,
Answer: Another natural way I might suggest is to embed your situation inside the canonical coin toss space $\Omega = \{ H, T \}^{\mathbb{N}}$. Here the $\sigma$-algebra $\mathcal{F}$ is the one generated by the collection of cylinder sets of the sort $\mathcal{C}_x =\{ \omega \in \Omega : \omega_1 = x_1, \dots, \omega_n = x_n \}$ for each $n \geq 1$, where $x = (x_i)_{i = 1}^n$ with each $x_i \in \{ H, T \}$.
Then the classic argument is to build a probability measure on this space $(\Omega, \mathcal{F})$ using Carathéodory's extension theorem with $\mathbb{P}(\mathcal{C}_x) = 1/2^n$ for the same example given above. (Technically we have a "semi-algebra" here that can readily be extended to an algebra; but there is a version of Carathéodory's that works here too. I found a nice explanation in Section 6.5 of these notes on building the coin-tossing measure).
This way, you can still capture everything you need to know about the tosses until the first head (e.g. by the random variable $T$). For example, the event $\{ T = k \}$ corresponds exactly to the cylinder set $\{ \omega \in \Omega: \omega_1 = \dots = \omega_{k-1} = T, \, \omega_k = H \}$, which has probability $1/2^k$.


C# Invoke Method Console Write Demo

Question: The code snippet below is from an ASP.NET MVC application. It accepts all parameters from browser. I believe it's vulnerable.
I'm testing an application's security, it uses Invoke method, but accepts the Object type, method and parameters dynamically from user's input. I believe it is dangerous and I'm trying to prove it.
Do you think I can invoke Console.Write or execute some sort of arbitrary/dangerous code?
I want to try to use C# Invoke Method to write to console to prove the vulnerability. This is what I did:
static void Main(string[] args)
{
    Type magicType = Type.GetType("System");
    ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);
    object magicClassObject = magicConstructor.Invoke(new object[] { });

    MethodInfo magicMethod = magicType.GetMethod("Console.Write");
    object magicValue = magicMethod.Invoke(magicClassObject, new object[] { 100 });
}

But it doesn't work. It says Object is not initialized. What am I missing?
Comment: I removed the bad tag, I know Console.Write, I'm trying to figure out Invoke method and I will be using it for some other purpose (security testing of an app)
Comment: Anyone care to comment why downvotes? 2 downvotes just for a question? Maybe I shouldn't ask any questions here
Comment: Any reason you tagged this with the `asp.net-mvc` tag?
Comment: @YuvalItzchakov, That's a perfect reason for downvote! Yaaay!
Comment: How can I delete my question? Seems like no one liked it
Comment: @JohnMcKean you asked your question just under ten minutes ago. I think your question is unclear (what are you trying to accomplish? Why don't you just use `Console.Write`?), which is probably why it has a couple of downvotes. Tagging is important on SO, but not a reason people usually down-vote questions.
Comment: @JohnMcKean I actually didn't downvote your question, and even answered it. I was just wondering if that tag is necessary.
Comment: Updated the question with more explanation on why I want to do it this way. The reason I had ASP.NET tag was, because it was an ASP.NET application
Comment: @JohnMcKean I've augmented your question based on your comments. Please clean it up if it's nonsensical or not what you're actually asking. You should also specify where the code lives (in a controller, presumably?) in the question text.
Comment: @ashes999, perfectly done! This is exactly my question! Thank you!
Answer: System is not a type, it's a namespace. You're actually looking for System.Console, which is the console class. After that, you're looking for the WriteLine method with the proper overload, which takes an int, which is what you pass to Type.GetMethod. Only then, you can invoke the MethodInfo object using Invoke passing null as the object (as this is a static class) and the right parameter.
What you actually want is this:
Type magicType = Type.GetType("System.Console");
var method = magicType.GetMethod("WriteLine", new[] { typeof(int) });
method.Invoke(null, new object[] { 100 });

Comment: @JohnMcKean Your question completely valid. Even if this isn't a "conventional" way of invoking a method, no reason not to ask about it.
Comment: Why would someone do this over invoking `System.Console.WriteLine` directly?
Comment: I'm testing an application's security, it uses Invoke method, but accepts the Object type, method and parameters dynamically from user's input. I believe it is dangerous and I'm trying to prove it
Comment: @YuvalItzchakov, So the code snipped I posted is from a web application. It accepts all parameters from browser. I believe it's vulnerable. Do you think I can invoke Console.Write or something like that using the code I posted. You code doesn't have second and third line.
Comment: @JohnMcKean I believe you should have stated this in your question itself -- that you want to know if it is vulnerable if a web app runs code like this.
Comment: Generally, invoking methods based on parameters passed by a web request sounds like a terrible idea. You don't need all that code that you posted, you can use the snippet I provided.
Comment: @YuvalItzchakov, thanks for all the explanations. The code is already written like that and I'm testing it. I saw that snipped and I think it's terrible, but I have to provide a PoC (proof-of-concept), for example invoking Console.Write. Can we do that in the code I posted as-is just by replacing strings part which is in control of user?
Comment: It always crashes at third line with error: "Object reference not set to an instance of an object." when I do Console.Write
Comment: Where are you calling `Console.Write`?

C# Invoke Method Console Write Demo


Auto Relacionamento no EF

Question: Estou tendo o seguinte problema ao criar duas auto relações.
Ao rodar o Update-Database Aparece a seguinte mensagem de erro:

Unable to determine the principal end of an association between the
  types 'Autorelação.Franquia' and 'Autorelação.Franquia'. The principal
  end of this association must be explicitly configured using either the
  relationship fluent API or data annotations.

Minha Classe
public class Franquia
    {
        [Key]
        public int FranquiaId { get; set; }

        public int? FranquiaMasterId { get; set; }

        public int? FranquiaSeniorId { get; set; }

        [ForeignKey("FranquiaMasterId")]
        public virtual Franquia FranquiaMaster { get; set; }

        [ForeignKey("FranquiaSeniorId")]
        public virtual Franquia FranquiaSenior { get; set; }
    }

Detalhe, ao rodar apenas um auto relacionamento funciona perfeitamente, entretanto com os dois aparece o erro.
Answer: Seguindo sua linha de raciocínio, uma Franquia poderá ter uma lista de franquias, e é exatamente o que está faltando quando você utilizada DataAnnotations.
Para isso, você deve utilizar também a anotação InverseProperty para realizar o mapeamento adequado das propriedades de navegação.
Seu código ficará da seguinte forma:
public class Franquia
    {
        [Key]
        public int FranquiaId { get; set; }

        public int? FranquiaMasterId { get; set; }

        public int? FranquiaSeniorId { get; set; }

        [ForeignKey("FranquiaMasterId")]
        public virtual Franquia FranquiaMaster { get; set; }

        [ForeignKey("FranquiaSeniorId")]
        public virtual Franquia FranquiaSenior { get; set; }

        [InverseProperty("FranquiaMaster")]
        public ICollection<Franquia> FranquiasMasters { get; set; }

        [InverseProperty("FranquiaSenior")]
        public ICollection<Franquia> FranquiasSeniors { get; set; }
    }

Existe a possibilidade de fazer por Fluent API, que ficaria desta forma:
modelBuilder.Entity<Franquia>()
    .HasOptional(s => s.FranquiaMaster)
    .WithMany(s => s.FranquiasMasters)
    .HasForeignKey(s => s.FranquiaMasterId);

modelBuilder.Entity<Franquia>()
    .HasOptional(s => s.FranquiaSenior)
    .WithMany(s => s.FranquiasSeniors)
    .HasForeignKey(s => s.FranquiaSeniorId);

Se estiver utilizando Migrations e for a criação da tabela, e não alteração, a migration gerada terá esse código:
public partial class addFranquias : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.Franquias",
            c => new
                {
                    FranquiaId = c.Int(nullable: false, identity: true),
                    FranquiaMasterId = c.Int(),
                    FranquiaSeniorId = c.Int(),
                })
            .PrimaryKey(t => t.FranquiaId)
            .ForeignKey("dbo.Franquias", t => t.FranquiaMasterId)
            .ForeignKey("dbo.Franquias", t => t.FranquiaSeniorId)
            .Index(t => t.FranquiaMasterId)
            .Index(t => t.FranquiaSeniorId);

    }

    public override void Down()
    {
        DropForeignKey("dbo.Franquias", "FranquiaSeniorId", "dbo.Franquias");
        DropForeignKey("dbo.Franquias", "FranquiaMasterId", "dbo.Franquias");
        DropIndex("dbo.Franquias", new[] { "FranquiaSeniorId" });
        DropIndex("dbo.Franquias", new[] { "FranquiaMasterId" });
        DropTable("dbo.Franquias");
    }
}

E para completar, terá o seguinte SQL que será executado no banco:
CREATE TABLE [dbo].[Franquias] (
    [FranquiaId] [int] NOT NULL IDENTITY,
    [FranquiaMasterId] [int],
    [FranquiaSeniorId] [int],
    CONSTRAINT [PK_dbo.Franquias] PRIMARY KEY ([FranquiaId])
)
CREATE INDEX [IX_FranquiaMasterId] ON [dbo].[Franquias]([FranquiaMasterId])
CREATE INDEX [IX_FranquiaSeniorId] ON [dbo].[Franquias]([FranquiaSeniorId])
ALTER TABLE [dbo].[Franquias] ADD CONSTRAINT [FK_dbo.Franquias_dbo.Franquias_FranquiaMasterId] FOREIGN KEY ([FranquiaMasterId]) REFERENCES [dbo].[Franquias] ([FranquiaId])
ALTER TABLE [dbo].[Franquias] ADD CONSTRAINT [FK_dbo.Franquias_dbo.Franquias_FranquiaSeniorId] FOREIGN KEY ([FranquiaSeniorId]) REFERENCES [dbo].[Franquias] ([FranquiaId])

Comment: Deu certo @randrade  realmente estava faltando o `InverseProperty`! Obrigado

Auto Relacionamento no EF


How do you build a Dominant 7th chord?

Question: This is speaking in the key of E minor.
7th chords have always messed me up even when I think I have them right. For a dominant 7th you need 1, 3, 5, 7b, right? In E- I got E, G, B, C#. The 7b is supposed to be 1 note below 1 but I can't find where I went wrong.
Comment: On the right of this site you see *related questions* and  find *learn the basics with music musictheory.net*
Comment: I'm sorry but in pedagogy this answer might be misleading and confusing, not just because it is less common seen in practice as compared to a Bm7 or B7 resolving to a Em, and also students can't easily see and hear functionally the relationship in harmony.
Comment: So in dominant 7th chords you don't flatten the 7? I thought thats what it meant since it's supposed to be minor
Answer:
This is speaking in the key of E minor.

Reading this sentence I understand Em is the tonic.
In Em the V7 is B7 (b d# f# a).
Let's assume you're searching the V7 with the root E, which is the dominant7 of a-minor.
The term dominant 7 chord is implying that this is the major V7 of the tonic in any scale.
In your case (dom.7 =E7) the tonic (I) is A major and its parallel scale a-minor and the V7 is e g# b d.
The dominant7 chord is always a chord built of the   5th degree with the tones 1 - 3 - 5 - 7 with a major 3rd which is the leading tone to the tonic root.

In E- I got E, G, B, C#.

This chord is the Em6 as we have a minor 3rd (G) and c# is the 6th and not the 7th.

The 7b is supposed to be 1 note below 1 but I can't find where I went wrong.

Well, the 7b (1 note below 1) would be d and not c#.
You have to look up the scales, relative scale and parallel scale (natural and harmonic minor scales) and the triads to understand fully your problem. A good plan would be to notate the yourself as a ladder respecting the whole and half steps: first just as a scheme than notate in a staff system and drawing the pattern of a keyboard and guitar pattern and TAB. e.g. A and am (natural and harmonic scale) C and cm, E and em.
The best thing to start is to play some simple folksongs or spirituals with the chords.
Answer: Chord symbols are used to specify absolute intervals that are not related to any key or scale, and you can calculate the note pitches in semitones, regardless what "key" someone might be thinking about. E7 means: E - G# - B - D. In the key of C minor, E7 is E - G# - B - D, in the key of Bbbb, E7 is E - G# - B - D, in the key of Z semi-middle-sized, E7 is E - G# - B - D, etc. In any and every key, E7 is E - G# - B - D.
In semitones a dominant seventh chord (in root position) is:

0 (root)
4 semitones above root
7 semitones above root
10 semitones above root

in the key of E minor

Chord symbols are not in a key. E7 always has the exact same notes E - G# - B - D. This can be very nice, because you can accompany a song from chord symbols without knowing what keys or scales are being used by the melody or other players, as long as you stick to play only the notes that belong to the written chord symbol.
Comment: All very well, except the 'semitones' bit. That'll get the right *sound* notes, but not always tell their names. So E7 is E Ab Cb Ebb?!
Comment: I think talking about enharmonics just adds more confusion, because the point is to see that each chord symbol type specifies a very rigid interval structure where you don't have to care about the key or scale. The chord symbol E7 means E - G# - B - D, even if it's written on a staff with the key signature of F minor. Why complicate it any further? I might reconsider if the question is the other way, giving a chord symbol name for a group of dots.
Comment: @Tim, for enharmonics (same pitch, different name), you would always use the letter name that corresponds to the interval. In the key of C, you would always count two letters over to get the third (E or Eb), even though the same pitches could be identified as D## and D# or Fb and Fbb.
Comment: Exactly. Chords are defined by the semitones they occupy, not by the name those notes happen to have in a concrete key. Notes may have several names, and chords may have several names. But once you are told to play an F## (other name of the note G), you know exactly which note to play, and when you are told to play Cb7 chord, it's a simple matter of counting semitones to derive the exact notes, whatever their name (Cb-Ebb-Gb-Hbb, or just H-D-F#-A).
Answer: Strictly speaking, in any key, the dominant chord is that based on the V.
So, in key Em, the dominant chord will be B. Thus the dominant seventh will be B7.
Using the 'stacked thirds', as we do for a lot of chords, that gives us the notes B D♯ F♯ A. All of which are diatonic to the Em key and scale. Some people aren't too happy using 'diatonic' with relation to minors, but I think it works here.Bear in mind there are several different sets of notes that constitute minor keys.
If, however, you're talking about the 'dominant seventh' chord that usually takes things to the IV, that's different. Occasionally, it's used in key Em to arrive at IV (A/Am) and that has been covered in other answers. Although it's actually not what the question asks!
Comment: I think "dominant seventh" can be taken as meaning chord type only. The OP was confused thinking that you're supposed to take the seventh note of the scale, which in the case of E minor is D, and because it's a dominant seventh, "flatten" it, giving C# or something. It becomes clearer if you just forget about scales and keys and diatonic anything.
Comment: You do not need to start on V to build it, it occurs naturally in the Maj scale on the V.  The formula is degree invariant, and that is its value.
Comment: @ggcg - that's the point. There is only one 'dominant seventh' chord that *can* be built diatonically - that rooted on V. Of course it could be rooted anywhere, but that produces V/V, V/vi etc, and has to use a chromatic.
Comment: It seems incongruent with the OPs question.
Answer: If you're building a E dominant 7th chord (notated as E7), the notes involved are E-G#-B-D.
Notice how are the 'alphabets' above are one note apart? That's because chords are typically built by stacking in 3rds. The 7th of the E7 chord is by adding a 3rd above the 5th of the chord (ie. the B), it won't be a C# or C anything, since a C is just a 2nd above B. And "D" is one whole tone below E.
However, if you are talking about constructing a diatonic dominant 7th chord in the key of E minor, that should be a B7 which consist of B-D#-F#-A. Notice again that "A" is one whole tone below B.
Hope this helps. :)
Update:
I guess I should mention a couple of things more:
"Dominant" refers to a couple of things.

First, it refers to the 5th degree of the scale. In the case of E minor, it refers to the B.
Second, it refers to the function of the chord built on the 5th degree of the scale that resolves (pulls you) back to the tonic of the key. It's commonly represented by the Roman numeral V7.
Third, when we refer to a dominant 7th chord (or any related extensions), we refer to a specific chord type that must have a major 3rd and a b7, and be default a perfect 5th (which might be subjected to omission or alteration), ie 1-3-5-b7.

In minor key, the leading tone (ie. the 7th degree of the scale) is often raised when the chord is in dominant function.

eg in E minor key, the notes are actually E F# G A B C D E
a 5th degree 7th chord will be a Bm7 chord, which is B-D-F#-A.... you can use this chord, but......
However, in practice, the D is very commonly raised in a dominant function chord when the V7 wants to resolve back to the I, ie instead of Bm7 you would raise the D  to D# and have B7 (B-D#-F#-A) instead. This key gives a stronger pull toward the Em which composers often prefers.
The D is however only raised in this case and not other functions, eg. when you want to build a chord from the 3rd degree "G", the chord is a G major (G-B-D), D is not raised here.
Comment: You should probably mention that you're not using the natural minor here.
Comment: Or rather, I should say that in minor key, the leading tone (the 7th degree note in the scale) is commonly raised in dominant function harmony, but not elsewhere.
Comment: Still not exactly accurate! Using the notes from E harmonic minor (or E melodic minor) there's a leading note of D# already there. tha's one reason why those two scales exist.
Answer: There are a couple possible issues that lead to confusion when applying the algorithm for constructing chords in key.
The first is proper name convention for the notes.  In equal tempered tuning (standard fretted guitar, piano, etc) the C# and the Db are enharmonic.  They are the exact same frequency and played the same way.  For all intents and purposes they are the same.  In just tuning they may not be.  The letter names and degrees of the major scale for any key are related by a 1-to-1 correspondence.  The letter names ALWAYS follow the sequence of the "musical alphabet" {A, B, C, D, E, F, G} repeat forever.  For example to get the proper letter names for the E maj scale you simply take the sequence
{E, F, G, A, B, C, D, E}
Now these are just the proper "letter names".  To make the maj scale you need to include the accidentals required to get the pattern of steps {W, W, H, W, W, W, H} between the notes (W = whole, H = half).  This gives you,
{E, F#, G#, A, B, C#, D#, E}
Consider the 6th degree of the E maj scale.  This is C# and NOT Db.  Not simply because this key has sharps and not flats but because the letter name in the 6th position of the sequence is C.  If you want to make an augmented 6th in the key of E you need to write Cx or C##.  On an equal tempered instrument you will be playing D natural but you'd get points off a music theory test if you said that D natural is the aug 6th of E maj.
The second thing is the application of the formula for chords.  As we build chords we always reference the formula to the major scale starting on the "One" or root of the chord.  Even if you are in the key of C maj, when you build an A min chord you apply the formula to the A maj scale.  The formulas are key independent, a few examples are provided below. X = any note,
X (or X maj) = {1, 3, 5}
X- (or X min) = {1, b3, 5}
X7 = {1, 3, 5, b7}
X-7(b5) = {1, b3, b5, b7}
You see the pattern.  This formula may seem confusing if you know your modes.  Some players may want to build a D-7 in the key of C and just say "why not use Dorian as the mode and say the formula is {1, 3, 5 ,7} of the Dorian mode".  Well this would lead to a lot of ambiguity when it comes to describing the structure of chords independently of key or mode as you have the same construction in the Phrygian and Aeolian modes.  And this brings us to the third possible point...
Third, there is a natural relationship between 7th chords in ANY key.  In other words one can build a 7th chord on each note of the maj scale just as one can build one of the 7 diatonic modes starting at each of the 7 degrees of the maj scale.  These are,
I maj7
ii -7
iii -7
IV maj7
V7
vi -7
vii -7(b5)
All these chords are in the same key, no accidentals required.  This sequence is used to harmonize melodies in key and naturally contains features like resolution (V7-->I, contains the movement 7-->8, and 4-->3).
In general one is free to put any chord any where, which may violate the key you are in.  For example, it is common in Jazz progressions for the vii chord to be a dom7 rather than a min7 (as would be "natural" in any key).
So when you say you are applying the formula for a chord in the key of Emin you have to ask yourself whether you are (1) trying to build a dom7 chord on the "tonic" of the key of Emin, or (2) trying to find the seventh chord that naturally occurs on the tonic of Emin, or (3) trying to find the V7 chord of Emin (as many have interpreted your question).  If you are trying option 1 then the chord formula is independent of key (actually it always is).  If you are trying option (3) then you walk up to the 5th note of the Emin scale and simply find what 7th chord is contained in the minor scale.  By the way this would NOT be a dom7 chord if you use the natural minor scale it would be a -7 chord.
Now this brings us to the fourth point.  There is no V7 chord in the minor scale.  To create the feeling of a resolution in a minor key we alter the scale to create either harmonic minor (which has the natural or major 7th in it) or melodic minor (which has a maj 6 and 7 in the ascending pattern and min 6 and 7 in the descending pattern).  Using these modes changes the 7th chords that are embedded in the minor key and creates the classic V7 --> I feel in that key (which may be expressed as V7-->i treating the "One" as the first note of the minor key).
It seems to me that you were trying to build a dom7 chord in E minor starting on E and applying the formula {1, 3, 5, b7} to the degrees of the minor key and this is simply not how the formula works.  Applying this to a minor scale without respecting the relative intervals indicated in the formula would give {1, b3, 5, bb7}.  Again, the formula for chords that you seem to be using is key and mode independent and is referenced to a Maj scale starting on the root.
Answer: Let's keep it simple:
An E dominant 7th (E7) chord is E G# B D.
In all cases, a dominant 7 chord consists of 1, Major 3, 5, and minor 7 relative to the root of the chord, regardless of what key the song is in.
Dominant also means the 5th note of the scale, and in most western music before jazz came along, that's where that kind of 7th chord was usually played, which is why it is called a dominant 7th. So for a song in E (major or minor), you would expect to play a dominant 7 chord starting on B, which would be B D# F# C.
Comment: Hey @LeithMcCombs! Welcome to the site! I believe you meant "B D# F# A" for your B7 chord :)

How do you build a Dominant 7th chord?


Como ordenar um array dinamicamente com Angular JS?

Question: Tenho uma lista de tasks. A lista inicia com as tasks não concluídas (task.done == false) por primeiro seguido das tasks concluídas. Entretanto quando seleciono uma task e seto a mesma como concluída (task.done==true), gostaria que a lista se ordenasse dinamicamente e esta task fosse para o final da lista. Abaixo o exemplo do meu controller da view.
app.controller ('crtl', function ($scope) {

 $scope.tasks = [
     { "task":"task1", "done": false},
     { "task":"task2", "done": true},
     { "task":"task3", "done": false}
 ];

 $scope.tasks.sort(order);

 function order (x, y) {
    return (x.done === y.done)? 0 : x? 1 : -1;
 };

 $scope.setDone = function (task) {
  task.done = true;

  //Como ordernar a lista dinamicamente ao alterar o booleano?
  //Esta maneira não funciona
  $scope.tasks.sort(order);

 };

});

Answer: Se se tratar de uma array/lista, você pode usar o filter. Exemplo:
$scope.tasks.filter(function(){
    return  //sua condição
})

Documentação
Answer: Existe um shorthand para o $FilterProvider que você pode utilizar:
$scope.variavel = $filter('orderBy')([colecao], '[propriedade]');

Aplicando ao seu caso:
$scope.tasks = $filter('orderBy')($scope.tasks, 'done');

Bonus - Caso você queira filtrar apenas os casos onde done=true;
$scope.doneTasks = $filter('filter')($scope.tasks,{'done': true});

Exemplo funcional a seguir:

function SampleController($scope, $filter) {
  $scope.tasks = [
    { "task":"task1", "done": false},
    { "task":"task2", "done": true},
    { "task":"task3", "done": false}
  ];

  $scope.orderedTasks = $filter('orderBy')($scope.tasks, 'done', true);

  $scope.doneTasks = $filter('filter')($scope.tasks,{'done': true});

}

      Ordered tasks:

          Task
          Done

          {{i.task}}
          {{i.done}}

      Done tasks:

          Task
          Done

          {{i.task}}
          {{i.done}}

Answer: Em angularjs: {{ orderBy_expression | orderBy : expression : reverse}}
Em javascript: $filter('orderBy')(array, expression, reverse)
Segue link da documentação escrita em inglês mas com ajuda do google translator será de fácil entendimento.
https://docs.angularjs.org/api/ng/filter/orderBy
Exemplo
http://plnkr.co/edit/TfDeOZF4YjezIbJlG0uF?p=preview
Answer: Use o filtro do Angular JS orderBY :
No controle, crie um filtro de ordem:
$scope.sortTasks = function(elem)
{
   switch (elem.done) {
     case false: return 1; break;
     case true:  return 2; break;
   }
}

E na view, use-o no orderBy:

          {{val.task}}
          {{val.done}}

Se fizer questão de ordenar dentro do controller, pode fazer assim. Porém é preciso mudar o filtro para | orderBy:order e ao fazer o ng-repeat, use o objeto taskOrdered:
$scope.taskOrdered = [];

 for (var i in $scope.tasks) {
      $scope.tasks[i].order = $scope.sortTasks($scope.tasks[i]);
      $scope.taskOrdered.push($scope.tasks[i]);
 }

Clique aqui para obter mais informações do filtro de ordenação:


FindBy com objeto aninhado - Spring Data JPA

Question: Estou com uma dúvida ao criar um findBy usando jpa com atríbuto de um objeto aninhado, as classes são:
public class Livro {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String titulo;
    @ManyToOne
    private Usuario usuario;

e
public class Usuario {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String nome;
    private String email;

Preciso retornar os livros de um determinado usuário, fornecendo o email dele.
Testei usando esses métodos no repository mas não funcionou:
List<Livro> findByLivro_Usuario_Email(String email);
List<Livro> findByLivroUsuario_Email(String email);
Vocês tem alguma sugestão do que pode ser?
Comment: acredito que o que você esteja procurando é um findByUsuarioEmail , mas no livros repository
Comment: Você tem razão, fiz a correção aqui e deu certo, ficou assim:
```
@Repository
public interface LivroRepository extends JpaRepository {
    List findByUsuarioEmail(String email);
}
```
Muito obrigado
Answer: Corrigida utilizando:
@Repository
public interface LivroRepository extends JpaRepository<Livro, Long> {
    List<Livro> findByUsuarioEmail(String email);
}


Is there an official/recommended way to organize CSS files for a responsive theme?

Question: While creating a responsive theme (eg. a bootstrap based sub-theme) is there an official/recommended way to organize CSS files for different media queries? In general I put everything into one CSS file.
1. All In One
mytheme.info:
...
stylesheets[all][] = css/style.css
...

style.css:
body { ... }

p { ... }

...

@media (max-width: 767px) {
...
}

@media (min-width: 1024px) {
...
}

2. Separated CSS Files
mytheme.info:
stylesheets[all][] = css/style.css
stylesheets[all][] = css/480.css
stylesheets[all][] = css/720.css
stylesheets[all][] = css/960.css

style.css, 480.css, 720.css ...

3. Separate CSS Files for Each Media Query Defined in .info File
mytheme.info:
stylesheets[all][] = css/style.css
stylesheets[all and (min-width: 480px)][] = css/480.css
stylesheets[all and (min-width: 720px)][] = css/720.css
stylesheets[all and (min-width: 960px)][] = css/960.css

style.css, 480.css, 720.css ...

4. Other?
I wonder what is the recommended way for this or it doesn't matter (structural, performance wise etc).
Comment: Since you mention you are using Bootstrap, you could use LESS or Sass to separate your code in different files, and then on compilation they will become a single file (even compressed if you want to), thus reducing the problem of multiple http requests.
Comment: I don't think there's any difference. And if there is, it will be so small it won't make any difference.
Comment: Using LESS I prefer store custom less code in separate file and other possible changes make in variables.less
Answer: This is possibly hard to answer. But all the way are acceptable.
Mostly people don't like reading through a single HUGE CSS file, and maintaining it is very difficult. On the other hand, splitting it out causes extra http requests which could potentially slow things down.
My opinion would be one of two things:

If you know that your CSS will NEVER change once you've built it, I'd build multiple CSS files in the development stage (for readability), and then manually combine them before going live (to reduce http requests).
If you know that you're going to change your CSS once in a while, and need to keep it readable, I would build separate files and use code (providing you're using some sort of programming language) to combine them at build time (runtime minification/combination is a resource pig).

With either option I would highly recommend caching on the client side in order to further reduce http requests.
I also found another question related to this https://stackoverflow.com/questions/16657159/when-using-media-queries-does-a-phone-load-non-relevent-queries-and-images . This will further clear your concept about this.
Comment: Which is not relelvant to drupal at all. I'm speaking in relation to Drupal. Point 1 is not relevant at all, because when you turn on CSS aggregation, drupal will group your CSS files and reduce the HTTP requests.
Comment: Waqar Ali, I believe it is a recommended practice in Stackexchange to provide some details about what the links you put in your answers talk about. This is useful in case these links would disappear, and it makes your answer more useful and clear at first reading... Thank you.
Comment: ok, thanks for good suggestion. I will keep it in my mind next time
Comment: If you turn on CSS aggregation, point 1's performance gains for multi-https requests becomes obsolete. On point 2 I guess you're suggesting SASS/LESS? Runtime minification can be resource hog only if you're not caching it effectively.
Comment: it's described in the link i provided.
Comment: check out link it will help you.


border-radius for specific element not rendered in Chrome

Question: Here is my site:
http://splash.inting.org/wp/
On the right sidebar, I have two elements, the reg form on top and the small slider at the bottom. Both have the same border-radius styles implemented but the one in the bottom does not have the curved borders rendered in Chrome. I already applied overflow: hidden.
Things to take note:

both elements (registration and slider) have same border-radius styles
applied but in chrome, only the registration is rendered with correct border styles
the border-radius renders correctly in firefox and even in IE

Any ideas? Thanks!
CHROME:

FIREFOX:
Answer: Apply the border radius directly to the image.
<code>.meteor-slides .mslide img
{
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
}
</code>
Comment: I'm trying to avoid that since not all sidebar elements will have images. But if that's the only work around I will try it. I'll give some feedback once I get it done. Thanks @MLM!
Comment: @AnimaSola If it is other kind of content then the border-radius on the parent should take care of it. So they will work in conjunction.


Erro no ionic-lab

Question: Estou fazendo um app, porem quando rodo ionic serve -l ou tendo acessar o ionic-lab pelo navegador ele exive um mensagem de erro e para o servidor, já procurei bastante pela internet e não achei reposta, anexo print do erro
Answer: problema resolvido após reinstalar o cordova e o ionic(ultimas versoes)

Erro no ionic-lab


Flex/Flash: capture 'trace' in code?

Question: In Flash/Flex, is it possible to capture the result of 'trace' in code?
So, for example, if one part of the code calls trace("foo"), I'd like to automatically capture the string "foo" and pass it to some other function.
Edit: I'm not interested in trying to use trace instead of a proper logging framework… I want to write a plugin for FlexUnit, so when a test fails it can say something like: "Test blah failed. Here is the output: ... traced text ...".
Edit 2: I only want to capture the results of trace. Or, in other words, even though my code uses a proper logging framework, I want to handle gracefully code that's still using trace for logging.
Answer: As far as I know it's impossible to do it externally, google brings up no results. Have you considered creating a variable for the output and then adding that to the log, eg:
var outputtext = "text";

trace(outputtext);

// log outputtext here

Disregard if it isn't feasible, but I can't think of any other way.
However you can do it internally, if it's just for development purposes: http://broadcast.artificialcolors.com/index.php?c=1&more=1&pb=1&tb=1&title=logging_flash_trace_output_to_a_text_fil
Comment: That is, of course, a possibility (I've actually got my logger setup so, when I'm developing, it just 'trace's the text)… But I'd like to capture *all* trace'd text - especially the "stupid debugging stuff" that someone left in there by mistake.
Answer: If you want to write traces to a log, you can just use the Debug version of Flash Player and tell it to log traces.
Comment: Unfortunately that only logs to a file… Which isn't quite what I want. I actually want to capture the logged messages in ActionScript.
Answer: I would suggest looking through the source for the swiz framework.  They use the flex internal logLogger app-wide and use best practices in a good majority of their code.
Comment: I'm not sure how that relates to my question…
Comment: David, it addresses your question to a tee.  The logger framework for flex is a very powerful and dynamic tool (to not only use in test / locally as many here are proposing) but to monitor server calls, errors, faults, internal app failures, and how your users are generally using your application.

Here's a simple post for you:
http://www.colettas.org/?p=153

I mentioned swiz because it is the only public example of logger use that I know of 'off the top'.  We use it extensively at my place of employment, but that code is very private and government regulated.
Comment: Funny... I just started reading that post.  It pretty much says exactly what you're asking in the 2nd paragraph:

"The Flex logging framework is a much more powerful way to log what's going on in your application, like the trace() statement but much more. "
Comment: and, if you're hip to using the debugger of flash player as most here are proposing:    http://www.flexafterdark.com/docs/Flex-Logging    Best of luck.
Answer: I have a Debug.write method that sends the passed messages over a LocalConnection which I use that instead of trace. My requirement is to be able to capture the debug statements even when the SWF is running out of the authoring environment, but you can use this method to capture the trace messages.
Comment: I can see how you could use `Debug.write(...)` to capture messages… But how does that relate to capturing messages written with `trace(...)`?
Comment: You are gonna have to replace `trace` with `Debug.write`. The only way to capture trace messages is to use a debug player and edit your mm.cfg file (in your OS's user directory) - that is not really what you are after, you need to do it in your swf itself. So, you are gonna have to replace your traces
Answer: As far as I understood you don't want to use logging, which is of course the right way to do it.
So, you can simply create a Static class with method trace, and call this method from anywhere in the application, that's how you will get all traces to one place, then could do what ever you want with the trace string before printing it to console.
Another way is to create bubbling trace event and dispatch it whenever you want to trace message, then add listener to STAGE for it and catch all events...
Hope its help
Comment: I realize that there are a bunch of different ways to get debug messages out of an application… But, for the moment, I'm only interested in getting `trace`'d messages. I'm writing test code (specifically, a FlexUnit Listener), and I'd like it if it would plug in nicely to *any* code (even code which uses `trace`).

Flex/Flash: capture 'trace' in code?


start with lyrics or harmony?

Question: I want to compose a song. I have composed some music harmony and lines. I need to write some lyrics but I have a question:
When creating songs, generally we write the lyrics and then compose a suitable harmony and music or do we have a harmony and music and try to write suitable lyrics for it ?
Answer: That depends on you. Just write first what comes natural to you. If you grab your guitar/play piano and you see that you can work your way in a harmony you like, start with that.
If you are thinking some lyrics without having any harmony, write them down.
There isn't any specific order in which to do that. Usually when I write a song, I first write the melody and then the harmony, but I have written songs the other way around.
So, just do things the way they come to you. You can do the other part after you've finished the first one and it'll be fine.
Αlso, another thing I have noticed, is that when I write the second part, I usually make changes to the first part I have written.
Answer: @Shevliaskovic is correct. It's really up to what works best for you. Whenever you have an idea for lyrics, you should write them down. Whenever you find a harmony, melody or chord progression that sounds cool to you, write that down too.
You can try to write harmony to match the words you have or write words to match the music you have. If you've written down a lot of both, you can try combining them to see what sounds best to you.
If you get really stuck and can't find a progression that appeals to you from fiddling around, don't be afraid to steal! This is what artists do (though it's not always conscious or intentional). Pick your favorite song, figure out the chord progression and write your song based on it. Make sure you make it your own though. mess with the tempo, the melody, and the words. If you make it your own, its not really stealing, it's drawing inspiration. Nothing comes from nowhere. Good luck writing and post what you make!
Answer: There's no correct answer here. Different songwriters have different processes and many songwriters within their own body of work chop and change what comes first.
Take whatever inspiration you get and run with it, and don't worry about the order in which things manifest.

start with lyrics or harmony?


Congruence equation with power solving method

Question: How can the equation like
$$
x^{118}\equiv 113\;\; (mod\; 1001)
$$
if I know the Fermat's little theorem, Chinese remainder theorem, Euler's theorem and basic operations on congruence?
My approach:
By Euler's theorem we know that if $x\perp 1001 $ then
$x^{720}\equiv 1 \;\; (mod\; 1001)$
but cannot combine this with my equation.
Comment: 1001 = 7 * 11 * 13
Comment: I used $x^6\equiv1(mod7),$ $x^{10}\equiv1(mod11)$ and $x^{12}\equiv1(mod13).$
Comment: Prove that $x^{60}\equiv1(\mod1001).$
Comment: @MichaelRozenberg How did you came out with this idea? Is there so schemma in such problems?
Answer: Since $1001=7\cdot11\cdot13$ and $(113,1001)=1,$ we obtain
$$x^6\equiv1(mod7),$$
$$x^{10}\equiv1(mod11)$$ and
$$x^{12}\equiv1(mod13),$$ which since $[6,12,10]=60$, gives
$$x^{60}\equiv1(mod1001)$$ and we need to solve
$$x^{-2}\equiv113(mod1001).$$
Now, by the euclidean algorithm we can get that
$$7\cdot1001=62\cdot113+1,$$ which gives
$$62x^{-2}\equiv62\cdot113(mod1001)$$ or
$$62x^{-2}\equiv-1(mod1001)$$ or
$$x^2\equiv-62(mod1001)$$ or
$$x^2\equiv18\cdot1001-62(mod1001)$$ or
$$x^2\equiv134^2(mod1001).$$
Can you end it now?
You can get all eight solutions by the chinese remainder theorem.
We have the following system:
$$x^2\equiv-62(mod7),$$ $$x^2\equiv-62(mod11)$$ and $$x^2=-62(mod13)$$ or
$$x^2\equiv1(mod7),$$ $$x^2\equiv4(mod11)$$ and $$x^2=16(mod13)$$ or
$$x\equiv\pm1(mod7),$$ $$x\equiv\pm2(mod11)$$ and $$x\equiv\pm4(mod13).$$
We got eight systems and it's enough to solve four of them with $x\equiv1(mod7)$ for example.
We have first of these four systems:
$$x\equiv1(mod7),$$ $$x\equiv2(mod11)$$ and $$x\equiv4(mod13).$$
Now, let
$$143a\equiv1(mod7),$$ $$91b\equiv2(mod11)$$ and $$77c\equiv4(mod13).$$
It gives
$$a\equiv5(mod7),$$ $$b\equiv8(mod11)$$ and $$c\equiv9(mod13).$$
Id est,
$$x\equiv5\cdot143+8\cdot91+9\cdot77(mod1001)\equiv134(mod1001).$$
By the same way you can get other six solutions.
Comment: mod 11 not not 10.
Comment: @Roddy MacPhee It was typo. Thank you!
Comment: How did you find $18$ for $18\cdot1001-62=134^2$? Trial and error? This gives $2$ solutions ($134$ and $867$). There are $6$ more.
Comment: I don't understand why you get that $x^{60}\equiv 1 \;\;(mod\;1001)$? and after using the euclidean algorithm you get that $ 7\cdot1001-62\cdot113=1$ how is it related to that $x^2\equiv -62\;\;(mod\;1001)?$
Comment: @akozer: $-62\cdot113\equiv1\pmod{1001}$ and $x^{-2}\equiv113\pmod{1001}$ means $x^2\equiv-62\pmod{1001}$. Think reciprocals mod $1001$.
Comment: @akozer I added something. See now.
Comment: @robjohn How did you find out that there are 8 solution to given equation?
Comment: @akozer Solve $x^2\equiv-62(mod7),$  $x^2\equiv-62(mod11)$ and  $x^2\equiv-62(mod13).$ After this you'll get $2^3$ valid solutions and use  the Chinese remainder theorem.
Comment: @MichaelRozenberg But how did you find out that they are different solutions? Did you find them all or they always have to be different ones?
Comment: @akozer I added something. See again.


nmap-python won't install properly on Raspberry Pi

Question: I am trying to scan my network for connected mac addresses and found that nmap could do the trick. Since I want to monitor connections over time, I want to use my Raspberry Pi which has no use until now to do the task on its own in an interval I don't know yet.
I obviously chose Python (which I am new to) to do the tasks I mentioned above.
My Problem begins with installing nmap. I installed it for the Terminal via sudo apt-get install nmap which didn't work well, because it's not a Python module, duh.
I then installed nmap-python via sudo apt-get install nmap-python and tried to import it in Python (at first via the shell) with import nmap
which gave me:
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import nmap
ImportError: No module named nmap

(same thing for the import via a .py-script)
If I list all my Modules via help('modules'), it shows several modules and one of them is nmap
...what's the problem now? I don't get it. Did I miss something?
Answer: It may come from the version of Python. It's possible that the module nmap-python you installed is for Python 2 and you are using the pyshell for Python 3, or the inverse.
Comment: that was the problem...oh my god - too easy I guess. Thank you very much!