Angular.JS directive not updating

Question: I am updating a scope array called $scope.arrangement using a click function, but this is not causing my directive to update and update the DOM.
/******************************************
  Sort function
******************************************/

  $scope.sort = function() {
        $scope.arrangement.sort(function(a, b){
            var keyA = a.created,
        keyB = b.created
        // Compare the 2 dates
        if(keyA < keyB) return -1;
        if(keyA > keyB) return 1;
        return 0;
        })
        for (b=0;b<$scope.arrangement.length;b++) {
            if($scope.arrangement[b].ord !== b) {
                console.log('order was '+$scope.arrangement[b].ord + " now " + b)
                $scope.arrangement[b].ord=b;
            }
        }
    }
})

/******************************************
  Directives
******************************************/

app.directive('item', function() {
  return {
    restrict: 'A',
    scope: {
      count: "=",
      arrangement: "="
    },
    link: function(scope,element,attrs) {
      console.log('updated')
      for (a=0;a<scope.arrangement.length;a++) {
        if (scope.arrangement[a].ord === scope.count) {
          element.html("Item "+scope.arrangement[a].id + " Created: " + scope.arrangement[a].created)
        }
      }
    }
  }
})

Here's a plunker: http://plnkr.co/edit/hT0HQ85yaPkQj2JcASrY
By clicking 'sort', I am expecting the $scope.sort function to run and this in turn to refresh my directive. What actually happens is the $scope.sort function runs but the directive does not update.
Note that I deliberately not using an ng-repeat here.
Comment: You seem to have the arrangement and counts set up as 2 way scope bound properties. However, you specify them as attributes. did you mean to use the `'@'` scope binding?
Comment: I thought that by binding them they would update the parent scope and therefore trigger the directive to update? Could you show me what you would change in plunker please?
Answer: The link function only runs one time.  elem.html does not use data bindings, so this will just set up the HTML of the element initially when the directive is linked.  You can set up a watch yourself:
scope.$watchCollection('arrangement', function () {
  for (a=0;a<scope.arrangement.length;a++) {
    if (scope.arrangement[a].ord === scope.count) {
      element.html("Item "+scope.arrangement[a].id + " Created: " + scope.arrangement[a].created)
    }
  }
});

Seems like it would be much easier to use built in directives, though:

  Item {{arr.id}} Created: {{arr.created}}

Angular.JS directive not updating


Is there an easy way to have an image in a radio button label?

Question: I have a dynamic list of images, that I want to have a user select via associated radio button in a form. Is there an a way I can do this with the base form api, or is this the kind of thing I'd need to create a custom theme for?
Answer: You can do this using CSS.
Add appropriated class from $form then use CSS to add images as background-image.
For example:
$form['example'] = array(
  '#type' => 'radios',
  '#title' => t('example'),
  '#default_value' => 1,
  '#options' => array(0 => ('Value 0'), 1 => ('Value 1')),
);

CSS
.form-item-example > labela[for=edit-example-0]{
      background-image: url('/path/to/image-0.png');
}

Comment: I can see how that would work normally, but the images are dynamic - I don't know what they are until runtime, so I can't put them in ahead of time in the css.
Answer: Okay, the approach that worked with my dynamic list of images
$end_options = [];

foreach ($dynamic_list_of_items as $item)
{
  $end_options[$item['option_key']] = $item['title'].'
';
}

$form['items'] = [
  '#type' => 'radios',
  '#title' => $this->t('Select Item'),
  '#description' => $this->t('Choose which item you'd like to use.'),
  '#options' => $end_options,
];

IE, you can put rendered html into the '#options' property of a radio button and it will work. Simpler than I thought.


Listing choices in optparse help output

Question: When you generate help for an option with Python's optparse module, you can use the %defualt placeholder to insert the default value for the option into the help. It there anyway of doing the same thing for the valid choices when the type is choice?
E.g something like:
import optparse
parser=optparse.OptionParser()
parser.add_option("-m","--method",
                  type = "choice", choices = ("method1","method2","method3"),
                  help = "Method to use. Valid choices are %choices. Default: %default")

Comment: Optparse is considered to be deprecated. You should use [argparse](https://docs.python.org/3.4/library/argparse.html).
Comment: @msvalkon: do you have a solution for this using argparse?
Comment: @JohnZwinck There we go, added one after all.
Comment: Unfortunately, i'm working within a framework that uses optparse and don't have the option to switch to using argparse until upstream does.
Answer: I assume your problem is that you don't want to repeat the list of choices.  Fortunately variables are universal if sometimes ugly solution to this kind of problem.  So the ugly-but-pragmatic answer is:
import optparse

choices_m = ("method1","method2","method3")
default_m = "method_1"

parser=optparse.OptionParser()
parser.add_option("-m","--method",
                  type = "choice", choices = choices_m,
                  default = defult_m,
                  help = "Method to use. Valid choices are %s. Default: %s"\
                         % (choices_m, default_m)

And of course this kind of thing can be done using argparse too.
Comment: The problem is to ensure that any future changes to the list of valid options is automatically reflected in the help message. This should work as long as a future maintainer twigs as to what is going on.
Answer: As @msvalkon commented, optparse is deprecated - use argparse instead.
You can specify %(choices)s placeholder in the help argument:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-m",
                    "--method",
                    type=str,
                    choices=("method1", "method2", "method3"),
                    help = "Method to use. Valid choices are %(choices)s. Default: %(default)s",
                    default="method1")

parser.parse_args()

Here's what on the console:
$ python test.py --help
usage: test.py [-h] [-m {method1,method2,method3}]

optional arguments:
  -h, --help            show this help message and exit
  -m {method1,method2,method3}, --method {method1,method2,method3}
                        Method to use. Valid choices are method1, method2,
                        method3. Default: method1

Comment: Maybe add the `default='method_n'`?
Answer: argparse prints the choices by default, as you can see in the demo below. One way to print the defaults automatically is to use the ArgumentsDefaultHelpFormatter.
import argparse

parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-m","--method", type=str, choices=("method1","method2","method3"),
              default="method1", help = "Method to use.")

parser.parse_args()

DEMO:
msvalkon@Lunkwill:/tmp$ python test.py -h
usage: test.py [-h] [-m {method1,method2,method3}]

optional arguments:
  -h, --help            show this help message and exit
  -m {method1,method2,method3}, --method {method1,method2,method3}
                        Method to use. (default: method1)

Listing choices in optparse help output


Javascript "tuple" notation: what is its point?

Question: At wtfjs, I found that the following is legal javascript.
",,," == Array((null,'cool',false,NaN,4)); // true

The argument (null,'cool',false,NaN,4) looks like a tuple to me, but javascript does not have tuples!
Some quick tests in my javascript console yields the following.
var t = (null,'cool',false,NaN,4); // t = 4
(null,'cool',false,NaN,4) === 4; // true
(alert('hello'), 42); // shows the alert and returns 42

It appears to behave exactly like a semicolon ; separated list of statements, simply returning the value of the last statement.
Is there a reference somewhere that describes this syntax and its semantics? Why does it exist, i.e. when should it be used?
Comment: The comma operator can also be (ab)used to run a series of functions inside of a ternary branch, as it will return the result of the last statement anyway: `var a = isTrue ? (b=f(c), g(b)) : (b=g(c), f(b))`. Rarely wise, but sometimes useful if very concise code is preferred over readability, or for quick debugging purposes.
Comment: It is the comma operator: http://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/
Comment: This is called an 'expression' in JavaScript, this is not simply an effect of the comma operator though it plays a small part; This expression is resolved because of the comma operator. You can set a value to any mutable variable of any evaluated expression. Even if that expression is undefined.
Answer: You are seeing the effect of the comma operator.

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

The resultant value when a,b,c,...,n is evaluated will always be the value of the rightmost expression, however all expressions in the chain are still evaluated (from left to right).
Comment: Thanks, the term 'comma operator' is what I was looking for.
Answer: As already explained this behaviour is caused by , operator. Due to this the expression (null,'cool',false,NaN,4) will always evaluate to 4. So we have
",,," == Array(4)

Array(4) - creates new array with allocated 4 elements. At the time of comparison with the string this array is converted to string like it would be with Array(4).toString(). For arrays toString acts like join(',') method called on this array. So for the empty array of 4 elements join will produce the string ",,,".
Answer: Try this alert((null,'cool',false,NaN,4)) and then you can see.
demo
The reason is because the comma operator evaluates all the statements and return the last one.
Think of this line: a = 1, b = 2, c = 3; it will run each expression so in essence it will set the variables to what you want and return the last value (in this case 3)


Como sobrepor uma div no rodapé de outra div

Question: Como sobrepor uma div no rodapé de outra div igual as chamadas de conteúdo do WikiHow.
Olhando o código do CSS percebi que é aplicado position: absolute para a div2 posicionada no rodapé, mas não vi como ela fica posicionada de forma fixa no rodapé da div1.
Como a div2 está posicionada de acordo com a div1 e não com a página inteira?
Segue o código atual:

.publi{
    max-width: 230px;
    max-height: 300px;
    overflow: hidden;
}
.limt-img{
    width: 100%;
    height: 100%;
}
.img-publi{
    width: 100%;
    height: 100%;
}
.position-title{
    background-color: #292929CC;
    color: white;
    position: absolute;
    max-width: 230px;
    max-height: 300px;
    width: 100%;
}

        Titulo

Answer: Basta você definir o bottom da div que vai ficar por cima, e coloca a div pai com position relative.

.publi{
    max-width: 230px;
    max-height: 300px;
    overflow: hidden;
    position: relative;
}
.limt-img{
    width: 100%;
    height: 100%;
}
.img-publi{
    width: 100%;
    height: 100%;
}
.position-title{
    background-color: #292929;
    color: white;
    position: absolute;
    max-width: 230px;
    max-height: 300px;
    width: 100%;
    text-align:center;
    bottom: 5px;
}

                        Titulo


Let $A,B,C$ be events. Find an expression for the event "at least one of B and C occur, but A does not"

Question: Let $A,B,C$ be events. The event "$A$ and $B$ occur but $C$ does not" may be expressed as $A \cap B \cap C^c$.
(a)  Find an expression for the event "at least one of B and C occur, but A does not"
(b)  Show that the probability of event in (a) is equal to
$\mathbb{P}(B)+\mathbb{P}(C)-\mathbb{P}(B\cap C)-\mathbb{P}(A\cap C)+\mathbb{P}(A\cap B \cap C)$

I claim that the answer to (a) is $(B \cup C)\cap A^c$. Can someone confirm or deny?
I have no idea how to proceed from here. From previous work, I have proven the following results:
$\mathbb{P}(A\setminus B)=\mathbb{P}(A)-\mathbb{P}(A \cap B)$
$\mathbb{P}(A\cup B)=\mathbb{P}(A)+\mathbb{P}(B)-\mathbb{P}(A\cap B)$
My main concern about (a) is what exactly they mean by "at least one" and the use of the operator "and".
Answer:
My main concern about (a) is what exactly they mean by "at least one" and the use of the operator "and".

"At least one of" a series of events means you have an inclusive union.  $A\cup B$ means the event of $A$ happening, or $B$ happening, or both happening.
"and" means the intersection.  $A\cap B$ means the event of $A$ and $B$ both happening.
So your answer is confirmed, $(B\cup C)\cap A^c$ and as a hint this is equal to $(B\cup C)\setminus A$.  Now apply your rules.
Answer: your answer to (a) is correct. "at least one of" means "either of, and possibly both". the "and" in "one of A and B" is not a logical operator, but is used as a list-former,e.g. "at least one of A,B,C and D"
the probability expression quoted seems to lack a term so i will insert it. we now have two main groups (parenthesized):
$$
(\mathbb{P}(B)+\mathbb{P}(C)-\mathbb{P}(B\cap C))-(\mathbb{P}(A\cap B)+\mathbb{P}(A\cap C)-\mathbb{P}(A\cap B \cap C))
$$
parses as (1): probability of at least one of B and C
$$
\mathbb{P}(B)+\mathbb{P}(C) -\mathbb{P}(B\cap C)
$$
the intersection is subtracted as otherwise it would be counted twice in the $\mathbb{P}(B)+\mathbb{P}(C) $ terms.
(2) removing the probability of A occurring
this mirrors the previous situation in (1), except that everything is intersected with A. in this case the $\mathbb{P}(A \cap B \cap C)$ is removed to correct for double counting. however, because this entire second component is being removed from the event, without the external parentheses this will occur with a positive sign, viz:
$$
\mathbb{P}(B)+\mathbb{P}(C)-\mathbb{P}(B\cap C)-\mathbb{P}(A\cap B)-\mathbb{P}(A\cap C)+\mathbb{P}(A\cap B \cap C)
$$


CDialog not main frame descendant

Question: Is there a way to make a dialog (CDialog) not descendant of the main frame?
If I don't specify a parent window at creation time the parent window is the main application window. I have tried to use SetOwner and SetParent with a NULL parameter but didn't work.
So is there any way to make a dialog not child of the main window or any other window that ultimately is a child of the main window??
Answer: Every window is a child of another window. You can't make a window which doesn't have a Parent. Best you can do is to set the parent to DesktopWindow. You can get desktop window through GetDesktopWindow().

CDialog not main frame descendant


The structure of maximal tori in finite simple groups

Question: Let $\mathbf{G}$ be a linear algebraic group over an algebraic closed field of characteristic $p$ and $F$ a proper frobenius map on it with fixed point group $\mathbf{G}^f=G$ such that $\overline{G}=G/Z(G)$ be a finite simple group of Lie type. We know that a maximal torus of $\overline{G}$ is defined to be $\overline{T}$ where $T=\mathbf{T}^F$ and $\mathbf{T}$ is a $F$-stable torus of $\mathbf{G}$.
Is it true that a maximal abelian subgroup $\overline{H}\subseteq\overline{G}$ where $gcd(|\overline{H}|,p)=1$ is a maximal torus of $\overline{G}$?
Answer: I may be saying something silly, but isn't for instance the subgroup $\mathbb{F}_p\simeq \begin{bmatrix}1 &t\\ 0 & 1\end{bmatrix}\hookrightarrow \textrm{SL}(2,\mathbb{F}_p)$ (for some $p>3$) a unipotent maximal abelian subgroup of that group that is not the reduction of a torus because it is not reductive?  Please correct me if this is not maximal abelian.
Comment: you are right. I changed the question to wast the unipotent subgroup.
Comment: OK, now it seems to exclude unipotent groups, at least those isomporphic to $\mathbb{F}_p$-vector-spaces.


Why do I get 500 error when I use .htaccess file

Question: My website runs fine on server, but when I add following codes to .htaccess file, then it shows 500 server misconfiguration error.
RewriteEngine on
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_input_time 500
php_value max_execution_time 500

My website is created with Codeigniter. How could I get rid of this problem.
Comment: You will have to contact your hosters -- some don't allow you to change values in php.ini
Comment: Check your Apache error.log and see what error shows up there.
Comment: how could I check for Apache error.log on server
Answer: Always check whether require modules are enabled or not
<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteCond $1 !^(index.php|resources|robots.txt)
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</IfModule>

<IfModule mod_php5.c>
 php_value upload_max_filesize 20M
 php_value post_max_size 20M
 php_value max_input_time 500
 php_value max_execution_time 500
</IfModule>


Transfer call from Twilio auto pilot to Taskrouter?

Question: I am creating Autopilot which greets the user when a Twilio number is called.
Then Autopilot will ask the user if he wants to connect with the agent according to the answer of the user. If user say yes then Autopilot will transfer the call to task router. By seeing Twilio example i Have reached to handoff the call to task router.
The problem is that I cannot specify Matching Task. In a Taskrouter workflow, I have 2 to 3 filter I want to pass matching task so that A particular filter is run of the workflow
Currently, I am using the below command For handoff.
<code>"handoff": {
            "channel": "voice",
            "uri": "taskrouter://workflowid",
}

</code>
Here I need to able to pass matching task (An addition parameter) something like selected_agent === 'lorem' which will tell the workflow which Particular task(Filter) to run
Answer: From the documentation (the Dialogue Payload is a task attribute):

When handing off an Autopilot voice session to Task Router or Flex,
you need to provide the destination the Task Router workflow Sid. When
the Hand-off is executed the Autopilot session is terminated, the call
is enqueued with the Dialogue Payload as a task attribute.
Comment: Can you point the handoff to an Ngrok url and then use the :4040 localhost debug to inspect the POSTed parameters? You can then see the payload you have to work with to better understand the structure.. Documentation says this is sent as TR attributes. Also, TR may have logs of the Task and its attributes.
Comment: it would be good if you can provide an example of how I can provide the Dialogue payload.


What is the difference between the speaker in a bass amp and sub?

Question: I have a 12 inch 100 watt speaker in my bass amp and no subwoofer. The subwoofer I am looking to buy is also 12 inches 100 watts.
Is there a difference between the actual speakers found in a bass amp and a subwoofer?
Answer: Yes, there can be a difference.  The difference will depend on manufacture and quality however, and in some cases there may be no discernible difference.
A speaker designed for a sub-woofer is made to have clarity at the lower frequency response spectrum, going as low as around 20 hz. Since the speakers are designed to support just the low frequency range with the expectation that other speakers will be taking the higher frequencies, you generally get a response built around the 20 - 200 hz range with little production above that.
Bass amp speakers generally start their response range around 40 hz, and support frequencies up to the higher ranges to support upper octave playing as well as instrument overtones. Usually the upper frequencies start to drop off in the 1000 hz range, although I've seen ranges from 800hz all the way up to 5k.
In short, the sub woofer speaker response range is limited in frequency range, and the bass amp speaker has a wider range.
Comment: "instrument overtones": this is important.  People tend to assume that since the most-used bass guitar frets (roughly E1-B2) are tuned to rougly 40-120Hz, that those are the most important frequencies to reproduce.  But the overtones are just as (or more) important parts of the sounds of those notes.  And your brain is quite capable of recognizing those notes even without any fundamental at all.
Comment: yes, with two basses that have the same pickups and strings, you can tell the difference between a mahogany body with a bolt on neck, and a solid maple neck-through-body.  The overtones they reinforce are different.
Answer: When you ask if there's a difference in the "actual speakers" I assume you are talking about what, in speaker design parlance, are called the drivers, as opposed to the enclosure or cabinet. Drivers are the transducers with the familiar cone, magnet and coil.
Drivers can be very different or very similar. It's impossible to tell without knowing what manufacturer and model they are. Different drivers are designed with different uses in mind.
That said, the same drivers can be made to sound very different according to the enclosure they are in. Most instrument speaker cabinets are either of the open back design or a fully enclosed design. (Usually open back is used for combos.This is advantageous for weight and cooling purposes. Also gives you a convenient place to put cords and such.) Fully enclosing the cabinet usually gives a better low end response. The larger the volume inside the more pronounced this is.

Image source
A subwoofer design is specifically designed to work in conjunction with other speakers which reproduce the mids and highs. Since they don't need to produce the higher frequencies they will contain a crossover to filter those frequencies out. A good subwoofer will usually be in a different cabinet style. Most will be a ported design. Ported cabinets will have a hole, or port which is tuned to the driver to improve bass response. If you put an ear to it you find that the lowest frequencies actually come from the port and not the driver.

Image source
When I was building my sound reinforcement rig I started with an Electrovoice cabinet with a 15" woofer and a 1" horn. This sounded great, but was lacking for large rooms. So I built a ported subwoofer cabinet designed by EV for their driver - the exact same type of driver as was in the other cabinet. Using a crossover, the lowest frequencies were separated to the sub which used a separate amp.
This allowed me to do venues such as night cubs. When we started doing outdoor or theater-sized venues it was still not enough bass. I built a different cabinet that was a folded horn design. They were enormous cabinets but they allowed the same drivers used in the ported subs to fill the theater.

Image source
The point here being that the enclosure design has a much bigger effect on the sound of bass speakers than the drivers themselves.
Comment: My bass amp does have ports, is this normal?
Comment: Yes. Ports will make the speaker more efficient on the low end. And if they're tuned properly to the driver they will provide a more even frequency response. I'm sure ported designs are common in speakers designed for bass than those designed for guitars. A subwoofer can still add some low end, if that's what you're looking for, due to the crossover.
Comment: So for playing in fairly small venues I could use my bass amp with a crossover instead of buying a subwoofer to get a similar result?
Comment: No, the crossover splits frequencies between two or more speakers. The reason the sub would add low end is because it will only be handling frequencies below a certain point, making it more efficient. Many subs are powered, meaning they have their own amplifier inside. This is even more helpful because that amp will also only have to handle the lowest frequencies.


Password protect Laravel subfolder with htaccess

Question: It seems I can't simply override Laravel's routing when trying to password protect a subfolder in views with htaccess. I put it and an .htpasswd file together in the folder that I wanted to create authentication for but with no effect.
The reason for this is I want to have "client's eyes only" folders for work in progress projects, e.g. "example.com/clients/my-client/". These folders will only contain static content.
I tried adding a folder tree in public but that doesn't seem to work either (I guess public content needs to be declared to avoid being routed?). I'd rather stick with having these client pages as views.
Ideas?
Running Laravel 4.2 on Apache.
Comment: You can use Auth without hooking up to a database, but you'll have to write [your own Auth provider](http://laravel.com/docs/4.2/extending#authentication) that will just lookup a file or config array key. Or, if you don't use a database elsewhere in the site (and thus don't want to have to hook up to one), you could use the SQLite database driver, which stores the database in an easily-accessible file.
Comment: It doesnt work that way at all. If you want to block access, use the Auth class
Comment: It's not possible to override the routing in views? I guess I can use the Auth class but that would require me to hook up a database, right?
Comment: @StaffanEstberg no problem - I've written our comments up as an answer if you wanted to accept it for others finding the question.
Comment: Great, thanks once again.
Answer: Because of the way Laravel does routing, all URIs are actually virtual URIs, so you can't put .htaccess files within any directories, as they're not really there.
However, you can use Laravel's Auth system to protect your routes (either using basic auth or a more traditional login form system).
If you don't want to have to hook Laravel up to a database just to protect some directories there are a couple of solutions:

You can write your own Auth provider that will just lookup the details in a file or config array key. It's not super-difficult to do this, though it may seem a little over the top just for the purposes you have.
You could use the SQLite database driver, which stores the database in an easily-accessible file (in app/database/) so the database is at least kept alongside your code.


Azure Function running in AKS throws 500 on query string parameter for http trigger function

Question: I have an azure function app that I have containerized and running in AKS. One of my http endpoints has a query string parameter of code=. When I call that endpoint I immediately get a 500 response. To rule out anything in the code I only return a 400 just to validate that I am executing the code. The strange thing is that if I change the query string parameter to anything other that code, for example codeg, I get back the proper 400 response.
I've enabled debug logging and I am getting a route match so I know the call is getting to the function app. However I am getting no other logs to indicate what might be failing.
Answer: It may be throwing an error because it's expecting the function key to be in the code query parameter.
I'm assuming you have a function key securing the endpoint?
Try sending the function key in the header x-functions-key which should free up the code query parameter for your use.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=csharp#api-key-authorization
Comment: Brilliant find thank you. Even though this is an anonymous function I didn't think about that. What threw me was that it works locally using localhost in the container running the same image that we deployed to the cluster

Given that it is anonymous how can we work around that? This endpoint is used for authentication callback and I don't know how much control we have over those parameters.
Comment: Still don't know the ultimate reason why an anonymous function should care about those parameters but I found it had to do with a permissions issue on the Secrets directory. Details and a work-around can be found here
https://stackoverflow.com/questions/68411649/why-does-an-anonymous-httptrigger-azure-function-throw-a-500-internal-server-err/68469479#68469479


Install R 3.2.3 package igraph on CentOS 5.11

Question: ** Instead of downvoting maybe express how the post could be improved. Thanks!
I'm trying to install igraph for R (3.2.3) which is installed on a CentOS 5.11 system. The tail of the error looks like:
foreign-graphml.c:65: warning: excess elements in struct initializer
foreign-graphml.c:65: warning: (near initialization for 'blankEntityStruct')
foreign-graphml.c: In function 'igraph_read_graph_graphml':
foreign-graphml.c:1330: error: 'XML_PARSE_HUGE' undeclared (first use in this function)
foreign-graphml.c:1330: error: (Each undeclared identifier is reported only once
foreign-graphml.c:1330: error: for each function it appears in.)
make: *** [foreign-graphml.o] Error 1
ERROR: compilation failed for package 'igraph'
* removing '/usr/lib64/R/library/igraph'

The downloaded source packages are in
    '/tmp/RtmpBDaixr/downloaded_packages'
Updating HTML index of packages in '.Library'
Making 'packages.html' ... done
Warning message:
In install.packages("igraph") :
  installation of package 'igraph' had non-zero exit status

XML_PARSE_HUGE stuck out at me. Quick Google uncovered that it does not show up until libxml2 2.7.3 (https://lists.nongnu.org/archive/html/igraph-help/2015-10/msg00022.html). Looks like I need to build a newer version for the machine which has been encountered on this site before at the link below.
Install libxml2 2.7.X on CentOS 5.X
When I run the install for it with
yum localinstall --nogpgcheck /usr/src/redhat/RPMS/x86_64/libxml2-2.7.8-1.x86_64.rpm

I get this on the tail
Error: Missing Dependency: libxml2.so.2 is needed by package eel2-2.16.1-1.el5.i386 (installed)
Error: Missing Dependency: libxml2.so.2 is needed by package evolution-data-server-1.12.3-18.el5.i386 (installed)
Error: Missing Dependency: libxml2.so.2 is needed by package 1:gnome-utils-2.16.0-5.el5.i386 (installed)
Error: Missing Dependency: libxml2.so.2 is needed by package libxslt-1.1.17-4.el5_8.3.i386 (installed)
Error: Missing Dependency: libxml2.so.2 is needed by package 7:kdenetwork-3.5.4-13.el5_6.1.i386 (installed)
Error: Missing Dependency: libxml2.so.2 is needed by package gnome-media-2.16.1-3.el5.i386 (installed)
Error: Missing Dependency: libxml2.so.2 is needed by package gnome-pilot-2.0.13-16.i386 (installed)
Error: Missing Dependency: libxml2.so.2 is needed by package 1:control-center-2.16.0-16.el5.i386 (installed)
You could try using --skip-broken to work around the problem
You could try running: package-cleanup --problems
                    package-cleanup --dupes
                    rpm -Va --nofiles --nodigest

I thought maybe it wants a 32-bit package instead
rpmbuild --target i386 -ba /usr/src/redhat/SPECS/libxml2.spec
yum localinstall --nogpgcheck /usr/src/redhat/RPMS/i386/libxml2-2.7.8-1.i386.rpm

Which tails
Error: Missing Dependency: libxml2.so.2()(64bit) is needed by package gtkhtml2-2.11.0-3.x86_64 (installed)
Error: Missing Dependency: libxml2.so.2()(64bit) is needed by package nautilus-2.16.2-10.el5.x86_64 (installed)
Error: Missing Dependency: libxml2.so.2()(64bit) is needed by package libgnome-java-2.12.4-3.fc6.x86_64 (installed)
Error: Missing Dependency: libxml2.so.2()(64bit) is needed by package nautilus-cd-burner-2.16.0-7.el5.x86_64 (installed)
Error: Missing Dependency: libxml2.so.2()(64bit) is needed by package gnome-spell-1.0.7-3.1.x86_64 (installed)
Error: Missing Dependency: libxml2.so.2()(64bit) is needed by package 1:gnome-utils-2.16.0-5.el5.x86_64 (installed)
Error: Missing Dependency: libxml2.so.2()(64bit) is needed by package gok-1.2.0-2.el5.x86_64 (installed)
Error: Missing Dependency: libxml2.so.2()(64bit) is needed by package libglade-java-2.12.5-3.fc6.x86_64 (installed)
Error: Missing Dependency: libxml2.so.2()(64bit) is needed by package evolution-webcal-2.7.1-6.x86_64 (installed)
You could try using --skip-broken to work around the problem
You could try running: package-cleanup --problems
                    package-cleanup --dupes
                    rpm -Va --nofiles --nodigest

I'm a little nervous to try using --skip-broken and package-cleanup as I need to have a solid migration patch to/from the changes (it is on a production machine) and I am not as versed in all of this as I should be. I may have to spin up a VM to beat on. Ultimately, all I am looking for is the R igraph package running on the system. Anyone out there have any ideas?
Comment: It is an image provided by a vendor for coursework that they sell. I've had to put in quite a bit of work just to turn it into a workable solution. I would like to be working with a current OS but sadly it is not an option.
Comment: Is moving to a newer OS not an option? Red Hat 5 is like 9 years old and you'll basically be rebuilding a new system trying to stack all of the dependencies together.
Answer: The solution was derived from a post by Radek Simko:
wget ftp://xxmlsoft.org/libxml2/libxml2-2.7.8.tar.gz
tar -xvf libxml2-2.7.8.tar.gz
cd libxml2-2.7.8
./configure
make
sudo make install

It was a simple as compiling from source for an install. I could then:
install.packages("igraph")

In R successfully.
Comment: `libxml2` is unfortunately one of the more problematic things to update, and this is a fine workaround. You may need to install other software the same way. When you do install software from scratch, make sure it's installed to `/usr/local/*` and doesn't replace software the system binaries under `/usr`, `/etc`, etc.
Comment: Thank you for the tips. I did not think about the install location. I'm sure the it would have bit me in the future.
Comment: `/usr/local` should be the default location, but you might want to doublecheck.


redirect wildcard subdomains to https (nginx)

Question: I've got a wildcard ssl certification and I'm trying to redirect all non-ssl traffic to ssl. Currently I'm using the following for redirection the non-subdomainded url which is working fine.
server {
listen      80;
server_name mydomain.com;

#Rewrite all nonssl requests to ssl.
rewrite     ^ https://$server_name$request_uri? permanent;
}

when I do the same thing for *.mydomain.com it logically redirects to
https://%2A.mydomain.com/

How do you redirect all subdomains to their https equivalent?
Comment: Instead of $server_name, why not $host?
Answer: That's all...
server {
    listen      80;
    server_name *.mydomain.com;

     #Rewrite all nonssl requests to ssl.
     return 301 https://$host$request_uri;
}

Comment: A bit more explanation might make this a better answer.
Comment: @dave-m, that there needs to be explained? `$host` variable? `$request_uri`?
Comment: It doesn't work, still got https://%2A.handy.travel/
Comment: I can confirm that this solution works
Comment: @DamonYuan This might be a bit late, but just in case someone else comes across this, you can't visit a website "*.handy.travel". The wildcard character will forward everything on that subdomain, but that isn't a website itself. You've either typed the wildcard character in a browser/cURL, or you've mistakenly put it on line 6 (of the answer).
Answer: The NGINX official documentation encourages to use the return directive instead of using rewrite directive for effecting redirection. This is so, as the request being rewritten is not meant for that server, but it still gets processed in that server block. So redirects are correctly done with a return directive instead, as all processing is stopped and a response is sent immediately. NGINX discourages rewrite for redirection here: http://nginx.org/en/docs/http/converting_rewrite_rules.html
The syntax for return directive is: return code URL;
As you were originally doing a permanent rewrite, so accordingly you can use 301 as the code to respond with, indicating it is a permanent redirect. Your https address will be passed in the url section. Reference: http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#return
So your correct configuration would be
server {
listen      80;
server_name *.mydomain.com;

#Redirect all nonssl requests to ssl.
return 301 https://$server_name$request_uri;
}

This would probably let you redirect correctly to your ssl domain, with a wildcard server block. You can also try the underscore generic server name '_' or $host as suggested in the comment above. Let us know!
Comment: Should be `return 301 https://$host$request_uri;`
Comment: While using `return` is generally better, suggested configuration isn't correct as it still uses $server_name for redirection, which will be "*.mydomain.com". Correct fix was already outlined by @cjc in the comment above - `$host` should be used instead of `$server_name`.
Comment: Yes agreed. Ah seems my attention spans are a fadin'!
Comment: In lieu of the detraction above, allow me to offer you a tip with your ssl configuration which should significantly improve performance. The most efficient way to set up SSL if you are using wildcard certificate is to set up 'ssl stapling' This allows you to set up SSL once on your default server for all sub domains, and saves separate ssl authentication for each sub domain.

     ssl_stapling on;
     resolver 220.127.116.11;
     ssl_stapling_file /ssl_keys/example.com_staple;
     ssl_stapling_verify on;

Refference- https://calomel.org/nginx.html
Comment: I'm listening for ports 80, 8080 AND 8181 `return 301 https://$server_name$request_uri;` to get them to use https on port 443. The problem is that the redirected url still has the original port number. 80 isn't a problem, but 8080 comes out as `https://example.com:8080`
Answer: Try something like this:
server {
  listen 80;
  server_name ~^(.*)\.mydomain\.com$;
  set $servername $1;
  rewrite ^(.*)$ https://$servername.mydomain.com/$1;
}

The catch is to define wildcard server and do redirects based on its name.
Comment: Overly permissive regex group.


How to write an HTML file that displays an HttpResponse object passed to it using Django

Question: I am new to Django and HTML and I am trying to display a list of data derived from a form on the HttpResponseRedirect page. I have been reading Django APIs but I am still unsure of how to use HttpResponse() and HttpResponseRedirect().
As of now I understand that response = HttpResponse() makes an HttpResponse object of  and HttpResponseRedirect('results') redirects the browser to a new html template page.
What I dont know is how to write results.html to display  on my browser.
I need help on how to write the HTML page.
I also need help on how to pass a list of data to that html page.
I would also be ok with displaying the list on the same html page the form is in instead of loading a new page.
Current code:
    def contact(request):
if request.method == 'POST': # If the form has been submitted...
    form = ContactForm(request.POST) # A form bound to the POST data
    chosen = []
    if form.is_valid():
        strt = time.time()
        form = form.cleaned_data
        parameters = organize(form)
        print 'input organized'
        chosen, companies = multiple(parameters)
        end = time.time()
        pp.pprint(companies)
        print 'companies matching search filters: ' , len(companies)

        print 'total time: ' , str(end-strt)

    response = HttpResponse(chosen)
    return HttpResponseRedirect('results') # Redirect after POST

Answer: I think what you want is Django's render_to_response shortcut.  The first argument is an html template to use, and the second is a dictionary of values to pass to that template.
At the top of your views.py file, include:
from django.shortcuts import render_to_response

and modify your code to read:
if request.method == 'POST': # If the form has been submitted...
    form = ContactForm(request.POST) # A form bound to the POST data
    chosen = []
    if form.is_valid():
        strt = time.time()
        form = form.cleaned_data
        parameters = organize(form)
        print 'input organized'
        chosen, companies = multiple(parameters)
        end = time.time()
        pp.pprint(companies)
        print 'companies matching search filters: ' , len(companies)
        print 'total time: ' , str(end-strt)
    return render_to_response('results.html', {'chosen':chosen,'companies':companies,'start':start,'end':end}) # Redirect after POST

Note that the second argument is a dictionary of values you'd like to pass to your template.  The way I've written it, you're passing 4 values (chosen, companies, start, end) but you can include as many as you'd like.
Then create a file named results.html in your Templates directory (which is specified in the TEMPLATE_DIRS variable in your settings.py file).  It could look something like this:
<!DOCTYPE html>

Results

Chosen: {{chosen}}

Companies: {{companies}}

Start: {{start}}

End: {{end}}

Django template syntax uses double curly braces {{}} to display variables passed to the template.
Note that this approach will not change the URL.  If you need to do this, try looking at this.


Javascript: Ocultar botão depois do evento "subscribe"

Question: Gente neste script do google tem um comenterio escrito "Add code to handle subscribe event." traduzindo "Adicionar código para lidar com evento de assinatura.".
Eu quero saber se tem como eu colocar um codigo nesse lugar para que quando ocorre a ação "subcribe" o botão suma. Se tiver como e você souber o código, pode me passa-lo?

Comment: Se voce puder editar o codigo/div do botao coloca um `id` nele e esconde no if do subscribe. Se o botao estiver sendo gerado automaticamente é um pouco diferente. E qual é essa api que esta usando?
Comment: Google developers
Comment: https://developers.google.com/youtube/youtube_subscribe_button?hl=pt-br
Comment: esta usando jquery tambem?
Comment: Não, apenas html e js
Answer: Isso já resolve, se estiver usando jquery, nao vai ser diferente, ao inves de remover o botao poderia somente esconder adiv tambem, ai depende do que precisa.

inscrever-se

Comment: Esconder a div é até melhor porque eu palenejo colocar um bloqueador que só debloqueio o botão de download pra quem se inscrever, por isso quero que o botão suma caso a pessoa seja inscrita, o que fez me ajudou a entender, mas preciso fazer com o botão inscrever-se do youtube que vou colocar no site.
Comment: Obrigado pela sua ajuda man :-D


Problem regarding finitely generated group

Question: which of the following statement are  necessarily true ?
$1.$ There exist a finitely generated group containing some element of infinite order
$2.$There exist an infinite group  which is not  finitely generated  but all whose element  have finite order
$3.$ There exist a finitely generated infinite group  no element  of which have infinite order
My atempt : For $1$ , I could not able to find the counterexample
I think $ 2,3$ are true
For $2$. take  $\mathbb{Q}$
For $3$. take $\mathbb{Z}$
Comment: When you say $\mathbb Z$, presumably you mean the additive group?  But then, what is the order of $1$?
Comment: There is only one element of finite order in $\Bbb Q$, and that is $0$.
Comment: Should say:  $\#3$ is a terribly difficult problem.  For years it was thought that there was no such group, but a non-trivial example was found.  This is known as the [Burnside Problem](https://en.wikipedia.org/wiki/Burnside_problem).
Comment: Every element, except $0$, has infinite order in $\mathbb Z$.  So...that settles $\#1$!
Comment: @lulu order of $1$ will be $2$ since $1^2=1$
Comment: u mean it is a research problem for $3$ @lulu  actually this question asked in our quiz test
Comment: No...as you are speaking of the additive group of integers, $1+1=2\neq 0$.
Comment: I doubt anybody gave you $\#3$ as a quiz problem. If so, they made a mistake.  It's a famously hard problem.  But are you sure they didn't add "abelian" or something?
Comment: oh sorry @lulu  i think order $1$ will be infinite  in additive group of integer
Comment: ya,they didn't add abelian @lulu
Comment: Finding a counter-example to a "there exists" statement.... Good luck!
Answer: For the first quest, You can look at $(\Bbb Z, +)$ it is finitely generated but every element is of infinite order.
For the second quest, consider $\overline{\Bbb Z _{p}}$, which is the algebraic closure of $\Bbb Z_p$. each element in this group is of finite order but it is not a finitely generated group.
For the third quest, consider the group $\Bbb Z^{2}$ which finitely generated, the answer is that there finitely generated infinite $p$-groups. which every element is of order of some power of $p$.


Probability to win.

Question: Two players $A$ and $B$ are playing the final of chess championship which contains a series of matches.
The probability that $A$ wins is ${2\over 3}$.
The probability that $B$ wins is ${1\over 3}$.
The winner will be the one who is
ahead by 2 games as compared to the
other and wins at least 6 games.
If the player $B$ wins the first 4 matches,
find the probability that $A$ wins the championship.
My attempt:
We should find the following probabilities:
$A$ wins 6 matches given $B$ has won the first 4.
$A$ wins 7 matches given $B$ has won the
first 4 and wins one out of the next 8.
But I am not getting any patterns.
Comment: Realize that this championship can last "forever" because A and B can keep on winning alternatively after B has won first 4. This looks to me like a Markov chain with 2 attractors: A wins or B wins. You need a sketch with all possible "states" for this structure
Comment: Yes I think we should get an infinite GP but that's not happening.
Comment: do you know how to do this if it is 0-0 and the 6 win caveat does not apply?  Eventually the match has to boil down to a 0-0, 1-0 or 0-1 situation
Comment: The number of possibilities is more than it seems like. I worked it out partially, but my classes are coming up now. In theory, this problem falls typically within the scope of Absorbing Markov chains and once that matrix has ben set up, it becomes straight forward. But in your problem, too many states to consider.
Comment: A on 4 is a critical point, - the routes to 4-4 or 4-5 can be simplified - if B wins, then A has to win until he is on 5, or he lost, if A wins a game, then B winning a game creates a similar situation as before- if it gets to 4-4, then it is effectively 0-0 - so we can only have 5 games before A is on 4, or B won
Comment: you need the probability that the A-B score becomes 4-4 or 4-5 (with otherwise B won) then for each of these you need the probability of winning where the A-B score is 0-1 and 0-0 - once A has 4, the 6 win rule has become irrelevant, and it is only the lead of 2 that both seek
Comment: I reread the question and I have another doubt, don't you think B already won? Or do the given conditions apply after B has one the first 4 matches
Comment: But then A should win 3 matches and B 1 with n number of matches won by both of them.
Comment: Why aren't draws considered here? They are allowed and pretty common in chess.
Comment: @tmm - the text of the question simply precludes draws, they don't need to be considered - one way of fitting the question to the real world is to say that draws are ignored, they are classed as 0-0 - we are only counting wins - it would be better to have made a question with no draws, e.g. Badminton
Comment: @amit - in the next 5 games, A has to win 4 or 5 of the games - that guarantees he is still in the match - if A does not win either 4 or 5 of the next 5 games, then it has to be that he lost 2  games, and at some point was trailing to 6 points, and did not have 5 wins himself - those two cases include all posibilities that lead to either A loses, 5-4 or 4-5
Answer: Go ahead and play another $6$ games, even if the ultimate winner is decided before all six games have been played.  If player A wins all six of these games, which happens with probability $(2/3)^6$, he is the champion at that point (having won two more games than player B's four wins).  If player A wins five of the six, which happens with probability $6(2/3)^5(1/3)$, the contest at this point is a tie, to which we'll return.  Finally, if player A wins four or fewer of the next six games, then player B is the champion (because she will have won at least two games, bringer her to six wins, which will be at least two more than player A).
So let's see what player A's chances become when starting from a tie.  Call this $p$.  We know we have to play at least two more games.  Either player A wins them both, which happens with probability $(2/3)^2$, or they split wins, leaving them tied again, which happens with probability $2(2/3)(1/3)$, or else A loses.  Thus
$$p=\left(2\over3\right)^2+2\left(2\over3\right)\left(1\over3\right)p={4\over9}(1+p)$$
from which we find $p=4/5$.  In total, the probability that player A wins the championship is
$$\left(2\over3\right)^6+6\left(2\over3\right)^5\left(1\over3\right)\left(4\over5\right)=\left(2\over3\right)^5{34\over15}={1088\over3645}\approx0.2985$$
Remark:  A key point to understand in this approach is that allowing "meaningless" games to be played does not affect the answer, but simplifies some of the analysis.
Comment: Thank you! I understand it now.
Comment: Go ahead and play another 6 games, even if the ultimate winner is decided before all six games have been played.Can you explain about this statement?
Answer: You can make a Markov chain with states $0-4,1-4,2-4,3-4,0-5,1-5,2-5,3-5,0,-1,+1$ where $0$ represents a tie in the number of games with each having won at least $4$ so two wins will win the match.  $+1$ is the case that B has won one more game and has won at least $5$ and $-1$ is the case that A has won one more game and has won at least $5$.  You can start to find B's chance to win from $0,-1,+1$ by the usual technique, then work backwards for the other cases.
Comment: But I don't know about Markov chains.
Comment: I would like to understand this method too could you explain?
Comment: Each state is a possible state of the match.  With each one you associate the chance B wins from that state.  Barry Cipra has dealt with $0$.  From $+1$ you have B winning the next game and winning the match with probability $1/3$ and going to $0$ with probability $2/3$, so B's chance from $+1$ is $\frac 13 \cdot 1 + \frac 23 \cdot (1-p)$.  You can keep going to get the chance B wins from $0-4$.
Answer: First consider the next 5 games, for B to fail to win, A must win 4 or more of the next 5 games, leaving the A-B score at 5-4 or 4-5
ok, so you should be able to work out the probability of after 5 games
1) A wins all to lead 5-4
2) A wins 4 of 5 to trail 4-5
3) the compliment of 1 & 2 is that neither of those happened, i.e. P3  = 1 - P1 - P2 and in that case B won - but you don't need all the combinations, 1 & 2 are easier to calculate
can you calculate 1 & 2?
so then the 6 win rule ceases to matter, let's say A is winning 5-4, we might as well call that +1
let's say what are the chances of A winning at -1, 0 and +1
P(-1) = (2/3)P(0) + 0 = (2/3)P(0)
A has a 2/3 chance of getting to a situation 0, and a 1/3 chance of losing completely
P(0) = (2/3)P(1) + (1/3)P(-1)
P(1) = 2/3 + (1/3)P(0)
so then you can change this all into terms of P(0) by substitutiong into the middle expression - you can then get P(0), P(-1) and P(1)
you can then multiply P(-1) and P(1) by the probabilities we worked out for the lead of 1 or -1 after 5 games

Probability to win.


How to add [] as elements to a list of lists in Python?

Question: a = [["GE", "US", "UK", ....], [12, 11, 29, ...]]

now I want to add other 5 variables and make the results like:
a = [["GE", "US", "UK", ....], [12, 11, 29, ...], ["a", "b", "c", ...], [...], [...], ...]

Comment: SO is not a homework resolver place ! you need to add your code !
Answer: You can append every list that you want to add by:
a.append(["a", "b", "c"])

Answer: You can just use the + operator to concatenate lists
>>> a = [["GE", "US", "UK"], [12, 11, 29]]
>>> a += [['a','b','c'], [],[],[]]
>>> a
[['GE', 'US', 'UK'], [12, 11, 29], ['a', 'b', 'c'], [], [], []]


AWS IAM Policy condition statement logical OR operator

Question: I have a simple IAM policy with two conditions:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowPush",
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com",
        "AWS": "arn:aws:iam::123456789:root"
      },
      "Action": [
        "ecr:*"
      ],
      "Condition": {
        "StringEquals": {
          "aws:username": [
            "user01",
            "marketing"
          ]
        },
        "StringLike": {
          "aws:sourceArn": [
            "arn:aws:lambda:eu-west-1:987654321:function:*",
            "arn:aws:lambda:eu-west-1:481275139:function:*",
            "arn:aws:lambda:eu-west-1:428385139:function:*"
          ]
        }
      }
    }
  ]
}

I would like to grant an entity permissions ecr:* if ONE of the two conditions are met, either their are user01 / marketing or a lambda function from another account is requesting the grant.
I have tried the policy before but it seems like the two conditions must be met at the same time in order to work.
Note: This policy is attached to an ECR repository.
Answer: Your policy statement has multiple condition operators, so the condition operators are evaluated using a logical AND.
Your aws:username context key has multiple values, so those values are evaluated using a logical OR. Ditto for the aws:sourceArn context key.
Here is a visualization of IAM policy evaluation of conditions.

If you want either condition (OR) rather than both conditions (AND) use two statements, like so:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowPushUser",
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com",
        "AWS": "arn:aws:iam::123456789:root"
      },
      "Action": [
        "ecr:*"
      ],
      "Condition": {
        "StringEquals": {
          "aws:username": [
            "user01",
            "marketing"
          ]
        }
      }
    },
    {
      "Sid": "AllowPushLambda",
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com",
        "AWS": "arn:aws:iam::123456789:root"
      },
      "Action": [
        "ecr:*"
      ],
      "Condition": {
        "StringLike": {
          "aws:sourceArn": [
            "arn:aws:lambda:eu-west-1:987654321:function:*",
            "arn:aws:lambda:eu-west-1:481275139:function:*",
            "arn:aws:lambda:eu-west-1:428385139:function:*"
          ]
        }
      }
    }
  ]
}


Checking Boundary Conditions for Candidate Solutions to PDE

Question: Consider the one-dimensional heat equation $ u_{xx}=u_t$ with the boundary data
$$u(x, 0)=f(x), \quad u(0, t)=u(L, t)=0.$$
The standard method of solving this equation is by finding a candidate family of solutions, by means of separation of variables, and then checking that the candidate $u(x, t)$ indeed satisfies both the equation and the boundary data. Regarding showing that the expected solution has the asserted boundary values , Knapp in his Advanced real analysis book writes "This amounts to interchanging infinite sums with passages to the limit as certain variables tend to the boundary, and the following result can often handle that."
Proposition. Let $X$ be a set, let $Y$ be a metric space, let $A_n (x)$ be a
sequence of complex-valued functions on $X$ such that  $\sum_{n=1}^\infty|A_n (x)|$ converges uniformly, and let $B_n (y)$ be a sequence of complex-valued functions on $Y$ such
that $|B_n (y)| \le1$ for all n and y and such that $\lim_{y\to y_0} B_n (y) = B_n (y_0 )$ for all $n$.
Then
$$\lim_{y\to y_0}\sum_{n=1}^\infty A_n(x)B_n(y)=\sum_{n=1}^\infty A_n(x)B_n(y_0)
$$
and the convergence is uniform in $x$ if, in addition to the above hypotheses, each $A_n (x)$ is bounded.
My question is why do we need to check, for instance, $\lim_{t\to 0}u(x, t)=f(x)$, rather than $u(x, 0)=f(x)$ by simply plugging in $t=0$.
Edit: I suspect that this is because Knapp wants the function $u$ be continuous over its domain of definition. (See the comments below). However Knapp writes "The conditions $u(0, t)=u(L, t)=0$ may be verified in the same way" by the above proposition which literally means that he uses the proposition in evaluation of $u$ at boundary points which to me doesn't sound right.
Comment: Are the function $A_n$ and $B_n$ continous? Do you know that the solution is continuous? The differential equation is usually only assumed to hold inside an open domain, i.e. on $(0,L)\times (0,T)=\Omega_T$ but then the function $$u(x,t)=\begin{cases}1 &(x,t)\in\Omega_T\\ f(x) & t=0\\ 0 &x\in\{0,L\} \end{cases}$$ solves the equation but obviously it is not a "good" solution. Does this help? In particular note that such fourier series may oscillate and thus it may fail that $u$ attains the boundary/initial data
Comment: @Quickbeam2k1 Regarding your first question, the functions $A_n$ and $B_n$ need not be  continuous. Indeed, it doesn't make sense to talk about continuity of $A_n$ a priori as $X$ is a *set*. As for the second question, Knapp, just like many other authors, is not explicit about the continuity of the solutions. My understanding is also that in order to rule out uninteresting solutions such as the ones as you have mentioned, we need to impose extra conditions. But in this case, why don't we write the boundary conditions in the *limit* form from the beginning?
Comment: have you read the examples in the book? I think the problem could  be that $u(x,0)$ is not defined, note the sign $\tilde$ for the fourier series in particular, this can be a problem in the corners (x,t)=(0,0). What if $f$ is not continuous what should $f(x)$ be in a jump point? But I don't see any comments on this there, sorry :)
Comment: $u(x,0)$ is defined in all examples in the book since $u$ is obtained from the method of separation of variables. Sorry, I don't understand your comment about the relation between the discontinuity of $f$ and the requirement for checking $\lim_{t\to 0}u(x,t)=f(x)$.
Comment: @Quickbeam2k1 you should make your comment an answer. As far as I am concerned, your answer is spot on, in the form of rhetorical questions.
Comment: what seems to be missing in Knapp's explanations is how the comparison with $f$ is performed. Usually, one needs to expand $f$ into a Fourier series to compare the solution with the initial data.
Answer: Are the functions An and Bn continous? Do you know that the solution is continuous? The differential equation is usually only assumed to hold inside an open domain, i.e. on $(0,L)\times(0,T)=\Omega_T$ but then the function
$$u(x,t)=\begin{cases}1& (x,t)\in \Omega_T,\\ f(x)& t=0,\\ 0& x\in\{0,L\}\end{cases},$$
solves the equation but obviously it is not a "good" solution. Does this help? In particular note that such fourier series may oscillate and thus it may fail that u attains the boundary/initial data


Isn't the cricket toss just an illusion of control?

Question: The cricket toss gives each team a 50% chance of being able to choose whether they bat or bowl first. I think this is an illusion of control, and there's no advantage to winning it. I'll try and explain why.
Let's say we change the toss so that it's a simple "Heads = home team bats first, Tails = away team bats first". Let's say the home team wants to bat first. Then they have a 50% chance of getting what they want. This is equivalent to them winning the toss and electing to bat.
These two situations result in the same probability that a given team will start with what they want - so why do we use the (slightly) more convoluted method of giving the toss winner the option to choose? If we did a simple "H = home team bats, T = away team bats", then the overall outcome would be the same, and it would remove all this debate around what kind of advantage winning the toss gives (because there is no "winning" the toss, you either get what you want or you don't).
Is there something wrong with my analysis?
Answer: Pretty much, yes - although this is illusion of control isn't really unique to cricket; there are plenty of other sports where there is no real choice for the team losing the toss, or one of the two possibilities given is clearly stronger than the other so is always chosen.
One minor scenario your idea of "heads home team bats" doesn't cover is the situation where the captains would make opposite choices when winning the toss - e.g. the home team would choose to bat if winning the toss, while the away team would choose to field (or vice versa), but that could be worked around by seeing if the captains agree beforehand and not bothering with the toss at all in that case.
Comment: @IAlreadyHaveAKey There still is an advantage of *winning* the toss, it's just that *calling it* has no effect whosoever on whether you win that advantage or not. Whether or not the flip is called or pre-specified, a team has a 50% chance of getting the advantageous position (assuming both teams agree there is one).
Comment: Oh that's true. Currently at least one team will get what they want but if it's just "heads home team bats" then it's possible for both teams to be unhappy. Thanks for the response - seems funny to be that there is so much debate over the advantage of winning the toss when there isn't really one at all.
Comment: Getting the preferred result from the toss is definitely important, and at the moment that occurs via winning the toss so I'd say winning the toss _is_ important because of how the Laws are structured. Your proposal just changes that to a "non-confrontational" system instead, but it would still be important to get the preferred result from your system as well.
Answer: Overall, I agree with your analysis (Practically, It is only Illusionary) and the corner case by Philip Kendall (Both teams may be unhappy) but the Purpose of Coin Toss is a little more than that here, in terms of Psychology, Audience Attraction and Communication.
(1) All televised Sports are entertainment for audiences, where "winning" is Important, Psychologically. It may be winning the toss, winning the Decision review or winning the Purple Cap.
Supporting Material:
https://www.crictracker.com/stats-is-virat-kohli-the-unluckiest-captain-ever-in-terms-of-winning-the-toss/
https://www.dnaindia.com/cricket/report-netizens-spark-meme-feast-after-virat-kohli-toss-loss-yet-again-in-wtc-final-2896207
(2) When audiences join to watch on TV, it gives 5 more minutes of match build up, advertisements and commentary before the game actually starts.
Supporting Material:
https://www.espncricinfo.com/story/to-toss-or-not-to-toss-icc-may-scrap-tradition-1146844

Numerous others, including Ricky Ponting, Michael Holding, Ian Botham, Shane Warne and Steve Waugh, have also endorsed the idea. "The concerned authorities must look at what Ricky Ponting suggested - no more tosses," Holding wrote for Wisden India in 2015. "The minor setback there in my opinion, is that tosses are big for television. It makes for good tension, everyone is focused on that coin when it's in the air and the winning captain's decision and so on."

(3) In Audience Communication, it sounds better to say with Excitement "Team X has WON the coin toss and has OPTED to bat" rather than "Team X has been randomly selected to bat" which lacks Excitement.
Supporting Material:
TBI


Erro StaticInjectorError ao usar Typeahead(ngx-bootstrap)

Question: Preciso usar o typeahead em um component, vamos chamar de component1.
O typeahead também ta sendo importado em outro component(vamos chamar de component2) que é usado dentro dentro deste mesmo component1 como um modal, mas são de modules diferentes.
Quando importo o module do typeahead no component1 e mantenho no component2 ele me da esse erro
Component1.module:

@NgModule({
    imports: [
        CommonModule,
        FullCalendarModule,
        EventoModule,
        BloquearAgendaModalModule,
        ListaBloqueiosModalModule,
        RouterModule.forChild(agendaState),
        TypeaheadModule.forRoot()
    ],
    declarations: [AgendaComponent],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]

Component2.module:

@NgModule({
    imports: [CommonModule, FormsModule, ReactiveFormsModule, EnderecoModule, TypeaheadModule.forRoot()],
    declarations: [EventoComponent],
    exports: [EventoComponent],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class EventoModule {}

ERROR Error: Uncaught (in promise): Error: StaticInjectorError(CoraPrevineAppModule)[TypeaheadDirective -> NgControl]:
  StaticInjectorError(Platform: core)[TypeaheadDirective -> NgControl]:
    NullInjectorError: No provider for NgControl!
Error: StaticInjectorError(CoraPrevineAppModule)[TypeaheadDirective -> NgControl]:
  StaticInjectorError(Platform: core)[TypeaheadDirective -> NgControl]:
    NullInjectorError: No provider for NgControl!
    at NullInjector.get (core.js?09c9:8894)
    at resolveToken (core.js?09c9:9139)
    at tryResolveToken (core.js?09c9:9083)
    at StaticInjector.get (core.js?09c9:8980)
    at resolveToken (core.js?09c9:9139)
    at tryResolveToken (core.js?09c9:9083)
    at StaticInjector.get (core.js?09c9:8980)
    at resolveNgModuleDep (core.js?09c9:21119)
    at NgModuleRef_.get (core.js?09c9:21808)
    at resolveNgModuleDep (core.js?09c9:21119)
    at resolvePromise (zone.js?d135:831)
    at resolvePromise (zone.js?d135:788)
    at eval (zone.js?d135:892)
    at ZoneDelegate.invokeTask (zone.js?d135:423)
    at Object.onInvokeTask (core.js?09c9:17279)
    at ZoneDelegate.invokeTask (zone.js?d135:422)
    at Zone.runTask (zone.js?d135:195)
    at drainMicroTaskQueue (zone.js?d135:601)
Answer: Fui investigando, investigando e vi que o que causava o problema era a falta do import do FormsModule que é necessário pro typeahead ter o funcionamento do bind.


Como atualizar o "personal access token" do github nos projetos antigos?

Question: Fala galera! Blz?
Estou com um problema ao tentar realizar o git push de alguns projetos antigos na minha máquina, pois o meu token de autenticação antigo do github expirou e eu criei um novo há duas semanas. Então, quando fui subir as modificações em um projeto antigo apareceu a seguinte mensagem:
remote: Permission to fulanoDeTal/game-air-rescue.git denied to fuladoDeTal.
fatal: não foi possível acessar 'https://github.com/fulanoDeTal/game-air-rescue.git/': The requested URL returned error: 403
Então fui no site do github e pesquisei o meu token e lá tinha uma mensagem assim:
If you've lost or forgotten this token, you can regenerate it, but be aware that any scripts or applications using this token will need to be updated.
Não sei como fazer isso para todos os projetos. Tenho que dar um git pull em todos os projetos antigos?
Observação: estou utilizando o Linux
Answer: Tenta gerar outro token:
Caminho para gerar um novo token -> Settings/Developer settings/Personal access tokens/ Generate New Token
Após basta adicionar o mesmo ao seu (Terminal git/linux) ou (Nomes de Usuário e Senhas Armazenados -  Windows)
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Alterando cor do titulo da minha aplicação

Question: Já tentei variooooos códigos para alterar a cor do titulo que fica na actionbar da aplicação, mas nada, creio que seja simples, mas não to conseguindo saber como. uso o "Theme.AppCompat.Light", tema criado pelo Action Bar Style Generator.
Answer: Resolvido :)
<code><style name="MeuAppActionBarTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="actionBarStyle">@style/MeuAppActionBar</item>
    </style>

    <style name="MeuAppActionBar" parent="@style/Widget.AppCompat.ActionBar">
        <item name="titleTextStyle">@style/MeuApp.TitleTextStyle</item>
        <item name="subtitleTextStyle">@style/MeuApp.SubTitleTextStyle</item>
        <item name="background">@color/azul_escuro</item>
    </style>

    <style name="MeuApp.TitleTextStyle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
        <item name="android:textColor">@color/branco</item>
        <item name="android:textStyle">normal</item>
    </style>

    <style name="MeuApp.SubTitleTextStyle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Subtitle">
        <item name="android:textColor">@color/branco</item>
        <item name="android:textStyle">normal</item>
    </style>
</code>


Corrigir um Erro - JavaScript

Question: Estou fazendo um curso de Programação JavaScript e não consigo resolver uma questão.
Segue o Enunciado.
Declarar uma função chamada "mover", que recebe dois arrays, remove o último elemento do primeiro e adiciona-o ao segundo.
Exemplo:
var umArray = [1, 2, 3];

var outroArray = [4, 5];

mover(umArray, outroArray);

umArray //deveria ser [1, 2]

outroArray //deveria ser [4, 5, 3]

Minha Resposta
function mover (umArray,outroArray){

var umArray = [1, 2,3];

var outroArray = [4,5];

umArray.pop()

outroArray.push(2)

}

Erros:
A função mover([1,2],[3,4]) deve modificar a primeira matriz para que seu valor seja [1] e modifique a segunda para que seu valor seja [3,4,2]
Comment: Obrigado Luiz. (:
Answer: Tem alguns erros em sua função:

Você redeclarou os parâmetros umArray e outroArray com valores fixos dentro da função:

    var umArray = [1, 2,3];
    var outroArray = [4,5];

Isso está incorreto, você recebe esses valores por parâmetro, portanto pode apagar isso.

Você utilizou os métodos push e pop, correto, mas quando o método pop é utilizado, ele remove e retorna o valor, e esse valor que deveria ser utilizado como parâmetro no push, porém você não utilizou o retorno do pop e fixou o valor enviado ao push:

outroArray.push(2)

Veja um exemplo do seu código com as correções sugeridas:

function mover (umArray,outroArray){
  const valor = umArray.pop();
  outroArray.push(valor);
}

var umArray = [1, 2, 3];
var outroArray = [4, 5];

mover(umArray, outroArray);

console.log(umArray); //deveria ser [1, 2]
console.log(outroArray); //deveria ser [4, 5, 3]

Como o método pop retorna o valor e é o valor que será enviado ao método push, você consegue fazer todo esse processo em apenas uma linha, utilizando o retorno do método pop como parâmetro no método push:

function mover (umArray,outroArray){
  outroArray.push(umArray.pop());
}

var umArray = [1, 2, 3];
var outroArray = [4, 5];

mover(umArray, outroArray);

console.log(umArray); //deveria ser [1, 2]
console.log(outroArray); //deveria ser [4, 5, 3]

Documentações:
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/pop
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/push
Comment: Daniel, Muito obrigado, sua resposta me ajudou muito. Obrigado mesmo pela força.
Comment: Boa Noite Augusto, sou novo no Stackoverflow, não localizei o local para marcar a resolução que me foi apresentada pelo Daniel. Poderia me mostra o caminho por favor?
Comment: @AugustoVasques, obrigado

Corrigir um Erro - JavaScript


Handlebars: Access has been denied to resolve the property "titulo" because it is not an "own property" of its parent

Question: Estou tendo um problema com a exibição dos dados do mysql pelo handlebars:
Executing (default): SELECT `id`, `titulo`, `conteudo`, `createdAt`, `updatedAt` FROM `postagens` AS `postagens`;
Handlebars: Access has been denied to resolve the property "titulo" because it is not an "own property" of its parent.
You can add a runtime option to disable the check or this warning:
See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details
Handlebars: Access has been denied to resolve the property "conteudo" because it is not an "own property" of its parent.You can add a runtime option to disable the check or this warning:
See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details
Es

Answer: Nas configurações da engine do handlebars, tente utilizar a opção runtimeOptions com as propriedades allowProtoPropertiesByDefault e allowProtoMethodsByDefault com valor true.
Ficando dessa forma:
    app.engine('handlebars', handlebars({
        defaultLayout: 'main',
        runtimeOptions: {
            allowProtoPropertiesByDefault: true,
            allowProtoMethodsByDefault: true,
        },
    }))

Fonte: http://www.prowebguru.com/2020/08/nodejs-express-handlebars-access-denied-resolve-property-solution/#.X595fFDQ9hE
Answer: Estava tendo este problema quando estava a fazer as consulta com o mongoose.
Inicialmente a linha de código era :

  Model.find().sort({date:'desc'})

Então a adicionei o método lean() do Mongoose, e o problema ficou resolvido com esta linha de código:
  Model.find().lean().sort({date:'desc'})

Mais detalhes: https://mongoosejs.com/docs/tutorials/lean.html
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Answer:

app.engine('handlebars', handlebars({
        defaultLayout: 'main',
        runtimeOptions: {
            allowProtoPropertiesByDefault: true,
            allowProtoMethodsByDefault: true,
        },
}))

AVISO: As pessoas podem travar seu sistema ao fabricar modelos especiais. Não use o código acima.

app.get('/pagamento', function (req, res) {
    Kitten.findAll().then(pagamentos => {
        res.render('pagamento', {
            pagamentos: pagamentos.map(pagamento => pagamento.toJSON())
        })
    })
});

Adapte seu código neste exemplo acima.
Comment: muito obrigado!
Comment: Obrigado. sua solução funcionou perfeitamente.
Answer: Pra você que não está conseguindo exibir as postagens, é só inserir a linha: query:{raw:true} na criação do database, no arquivo db.js, fica:
const sequelize = new Sequelize('nome_do_banco', 'usuario', 'senha', {
    host: 'localhost',
    dialect: 'mysql',
    query:{raw:true}
});

Outro erro comum que acontece são as pessoas chamarem somente a função all(), porém entrou em desuso, agora o correto é findAll():
Substitua o método Post.All() por Post.findAll() na criação da rota. fica assim:
app.get('/', (req, res) => {
        Post.findAll().then(function(posts) {
            res.render('home', {posts: posts})
        })
    })


Let $f:I\to\mathbb{R}$ be diferentiable $n$ times in $x_0$ s.t. $f'(x_0)=\dots=f^{(n-1)}(x_0)=0$ and $f^{(n)}(x_0)\neq 0$. Show that.

Question:
(a) If $n$ is even and $f^{(n)}(x_0)>0$, then $x_0$ is a local maximum
  point of $f$.
(b) If $n$ is odd, then $x_0$ is not an extreme value of $f$.

I'm trying this:
If $f^{(n-1)}(x_0)=0$ and $f^{(n)}(x_0)>0$, then $x_0$ is a maximum point of $f^{(n-2)}$. Can I say that if $f^{(n-3)}(x_0)=0$ and $x_0$ is a maximum of $f^{(n-2)}$, then $x_0$ is a maximum of $f^{(n-4)}$?
Comment: Is (b) correctly stated? or is this problem actually "Show one of these", not show both? I ask because (b) is false, and you will note directly contradicts (a).
Comment: I guess you meant "(b) if $n$ is odd, then $x_0$ is neither a maximum nor a minimum of $f$"
Answer: First we'll need a previous result.
Let $f$ be a real-valued function. Let $P_{n,x_0}$ denote the $n$-th degree Taylor polynomial of $f$ at $x_0$, meaning
$$P_{n,x_0}(x)=a_0+a_1(x-x_0)+\ldots+a_n(x-a)^n$$ where $\displaystyle a_k=\frac{f^{(k)}(x_0)}{k!}$

Lemma: If $f:I\rightarrow\mathbb{R}$ is $n$ times diferentiable in $x_0$, then
  $$\lim_{x\rightarrow x_0} \frac{f(x)-P_{n,x_0}(x)}{(x-x_0)^n}=0$$

Rewriting the expressions:
$$\frac{f(x) - P_{n,x_0}}{(x-x_0)^n}=\frac{f(x)-\sum_{i=0}^{n-1}\frac{f^{(i)}(x_0)}{i!}(x-x_0)^i}{(x-a)^n}-\frac{f^{(n)}(x_0)}{n!}$$
Consider $Q(x)=\sum_{i=0}^{n-1}\frac{f^{(i)}(x_0)}{i!}(x-x_0)^i$ and $g(x) =(x-x_0)^n$, so we must show that
$$\lim_{x\rightarrow x_0}\frac{f(x)-Q(x)}{g(x)}=\frac{f^{(n)}(x_0)}{n!}$$
Notice that $Q^{(i)}(x_0)=f^{(i)}(x_0)$ for $i\leq n-1$ and that $g^{(i)}(x) =n!\frac{(x-x_0)^{n-i}}{(n-i)!} $ so we can use $n-1$ times L'Hôpital rule:
$$\lim_{x\rightarrow x_0}\frac{f(x)-Q(x)}{(x-x_0)^n}=lim_{x\rightarrow x_0}\frac{f^(n-1)(x)-Q^(n-1)(x)}{n!(x-x_0)}=\frac1{n!}lim_{x\rightarrow x_0}\frac{f^(n-1)(x)-Q^(n-1)(x)}{(x-x_0)}=\frac{f^{(n)}(x_0)}{n!}$$
(In the last equality we simply use the definition of derivative) QED
Now let's suppose $f$ $n$ times diferentiable such that $f^{(i)}(x_0)=0$ for $i=1,\ldots,n-1$. Without loss of generality, let's suppose $f(x_0)=0$ as well (otherwise we can work with $g = f -f(x_0)$.) So we have from the previous lemma:
$$0=\lim_{x\rightarrow x_0} \frac{f(x)-P_{n,x_0}(x)}{(x-x_0)^n}=\lim_{x\rightarrow x_0}\left[\frac{f(x)}{(x-a)^n}-\frac{f^{(n)}(x_0)}{n!}\right]$$
Hence by continuity, if $x$ is close enough to $x_0$, then both $\frac{f(x)}{(x-a)^n}$ and $\frac{f^{(n)}(x_0)}{n!}$ have the same sign.
Then if $n$ is even, $(x-x_0)^n>0$ for every $x\neq x_0$ so for $x$ close enough,   $f(x)$ and $f^{(n)}(x_0)$ have the same sign. If $f^{(n)} (x_0)>0 $, then $f(x)>0=f(x_0)$ and $x_0$ is a local minimum. With an analogous argument we can see that if $f^{(n)}(x_0)<0$ then $f(x_0)$ is a local maximum.
Now let's suppose $n$ is odd. Then $(x-x_0)^n >0$ when $x>x_0$ and $(x-x_0)^n<0$ when $x<x_0$. But $\frac{f(x)}{(x-x_0)^n}$ has always the same sign. Hence $f(x)$ has diferent signs for $x<x_0$ and  $x >x_0$, so $f(x_0)$ is neither a maximum nor a minimum.
Answer: The statement you ask about is not true in general. I suggest you consider the function $g(x) = \frac{f(x)}{x^n}$. And it might be best to work inductively.


'drush field-create' with type INTEGER from command line? drupal (ver 7.22) | drush (ver 6)

Question: tried to manage fields of tpye 'int' with drush (batch), without success!
working:
drush field-create user streetname,text,text_textfield --entity_type=user
not working:
drush field-create user streetnumber,integer,text_textfield --entity_type=user
workaround:
drush field-create streetnumber --entity_type=user
-> offers interactive dialog only
Field name: ...
Choose a field type ...
Choose a widget ...
--> '_http://default//fields/streetnumber'
Maybe there's another way to provide data, like

drush field-create user streetnumber < inputfile ??
drush field-create user streetnumber < 'fieldname_XYZ','6','1' ??

any ideas?
Answer: for an integer field type, try this :
drush field-create user streetnumber, number_integer, number_textfield

Or :
drush field-create user streetnumber, number_integer

(because you can ommit the widget type and the default one will be used).
If you are looking for the name of another field type, create the field in the admin panel, then look in your database, in table field_config, you will find it in the type column.
Comment: here is a complete list of fields: https://www.drupal.org/docs/7/api/field-api/field-types-and-settings


DropDownList not getting selected - MVC4

Question: I have the DropDownList in view as below,
@Html.DropDownListFor(model => model.RoleID, (IEnumerable<SelectListItem>)ViewBag.RoleID, new { @class = "dropdownlistCustom" })
@Html.DropDownList("RoleID", (IEnumerable<SelectListItem>)ViewBag.RoleID, new { @class = "dropdownlistCustom" })
@Html.ValidationMessageFor(model => model.RoleID)

Tried both DropDownList and DropDownListFor, both are not getting the correct SelectedValue.
From Controller, I am setting the selectedValue param (see Last parameter of SelectList()) .
public ActionResult Edit(int id = 0)
{
    UserDetail userDetail=db.UserDetails.Find(id);
    if(userDetail!=null)
    {
       ViewBag.RoleID = new SelectList(db.Roles.Where(r => r.RoleStatus == "A"), "RoleID", "RoleName", userdetail.RoleID);
       return View(userdetail);
    }
}

Model :
[Display(Name = "Name Of the Role")]
public int RoleID { get; set; }
[ForeignKey("RoleID")]
public virtual Role Roles { get; set; }

Comment: in controller, are you fetching userdetail from db or creating a new object?
Comment: I am doing the editing (`[GET]` request to `Edit`)... ie. I am fetching the data. I done most debugging, and I am getting the correct value in `userdetail.RoleID`
Answer: First of all I would encourage you not to use ViewBag, but view models to pass your select list (or data for select list) along from controllers to views.
Second of all, I would encourage you to look at this example or this example (preferably both) of DropDownListFor usage. I think you over-complicating SelectList. Less simple it is, less confused you will be as to why is it not working as expected. Just take existing example and change variable names to yours.
Another big tip why not to use ViewBag is that when you build your view model you can build a select list right there in the controller where you fetch your data from wherever. Then in the view you will only need to use pre-built view model property where SelectList argument is provided - cleaner and nicer. View should do least manipulations with data, but only to present it in the right format in the right way in the right place.
Just look at those examples I provided, I am sure you smart enough to figure it out how to use DropDownListFor properly, its very very easy, you just need to provide right parameters at the right places, see what others do and do the same.
Hope this helps, please keep me posted about your progress.
Comment: You can, its bad practice. Its like global variables in old days. It is easy to setup and start with, it bytes you back when you need to return to your code, from readability, maintainability perspective. Also not less improtant - its not strongly typed, which is another source of possible bugs. With View Model you have strongly typed properties that can be used for rendering select list, string[] or List for example, but can be anything. Hope it clarifies.
Answer: That's because you're not using DropDownListFor correctly. The function definition you're after is:
DropDownListFor(lambda, selectList, *selectedItem*, htmlAttributes)

RoleId should be passed as the selectedItem parameter, so you're missing the selectList parameter. MVC doesn't create that for you automatically with DropDownListFor, you have to tell it what select list to use by either creating it inline, passing it into ViewBag or setting it on your model and specifying which property to use.
EDIT
Sorry. That's my bad. It's still early here and we lost an hour (daylight savings), so my brain is not all there yet. I mixed DropDownListFor and DropDownList. With DropDownListFor, the selected item comes from the set value on the model, but you still need to provide a proper SelectList. It appears you're trying to specify the selected item where you should be telling it what SelectList to use.
If you were to use DropDownList, then you would need to specify both the SelectList to use and the selected value.
Comment: but I can't find a overload which takes `selectedItem` param
Comment: I am setting the `SelectList` from the controller, you can see that in my Question, that Edit Action. Also I am setting the SelectedValue as correct value from there (last param)... when I am debugging I can see the correct value is set as selected, but unfortunatly I am not getting that in the View (I also debugged in View rendering area also)
Comment: It's probably because you're casting your `SelectList` into an `IEnumerable`. That'll carry your items over, but not the selected value. Cast it as a true-blue `SelectList` and see if that doesn't fix it.


pygame player shakes and flies after adding collision

Question: The jumping part looks fine, but the player shakes while walking around and as I had different rects for walking and standing, when player walks into a wall it nicely stopped moving but as I stopped pressing moving button it would flash to the top of that wall, also while in the air, whenever player collide with tiles on x-axis it either flash to the top or bottom of that tile, I was expecting it to just slide on the wall.
Here's my code for player
<code>class Player():
    def __init__(self,x,y):
        self.img_stand = pygame.image.load('D:\ThingThing\inthething\H stand.png')
        self.img_standL = pygame.image.load('D:\ThingThing\inthething\H standL.png')
        #walk animation
        self.images_right = []
        self.images_left = []
        self.index = 0
        self.counter = 0
        self.direction = 0

        for num in range(1,17):
            img_right = pygame.image.load(f'D:\ThingThing\inthething\H walk{num}.png')
            self.images_right.append(img_right)

        for num in range(1,17):
            img_left = pygame.image.load(f'D:\ThingThing\inthething\H walkL{num}.png')
            self.images_left.append(img_left)

        self.image = self.img_stand
        self.rect = self.image.get_rect()
        print(self.rect)

        self.rect.x = x
        self.rect.y = y
        self.width = self.image.get_width()
        self.height = self.image.get_height()

        self.vel_y = 0
        self.jumped = False
    def update(self):
        dx = 0
        dy = 0
        walk_cooldown = 8

        #get key
        key = pygame.key.get_pressed()
        if key[pygame.K_LEFT]:
            dx -= 1
            self.counter += 1
            self.image = self.images_left[self.index]
            self.tempx = self.rect.centerx
            self.tempy = self.rect.bottom
            self.rect = self.image.get_rect()
            self.rect.centerx = self.tempx
            self.rect.bottom = self.tempy

            self.direction = -1
        if key[pygame.K_RIGHT]:
            dx += 1
            self.counter += 1
            self.image = self.images_right[self.index]
            self.direction = 1
            self.tempx = self.rect.centerx
            self.tempy = self.rect.bottom
            self.rect = self.image.get_rect()
            self.rect.centerx = self.tempx
            self.rect.bottom = self.tempy

        if key[pygame.K_SPACE] and self.jumped == False:
            self.vel_y = -8
            self.jumped = True

        if key[pygame.K_SPACE] == False:
            self.jumped = False
        if (key[pygame.K_LEFT] == False and key[pygame.K_RIGHT] == False) or (key[pygame.K_LEFT] == True and key[pygame.K_RIGHT] == True):
            self.counter = 0
            self.index = 0
            if self.direction == 1:
                self.image = self.img_stand

            if self.direction == -1:
                self.image = self.img_standL
            self.tempx = self.rect.centerx
            self.tempy = self.rect.bottom
            self.rect = self.image.get_rect()
            self.rect.centerx = self.tempx
            self.rect.bottom = self.tempy

        if self.counter > walk_cooldown:
            self.counter = 0
            self.index += 1
            if self.direction == 1:
                if self.index >= len(self.images_right):
                    self.index = 0
                self.image = self.images_right[self.index]
            if self.direction == -1:
                if self.index >= len(self.images_left):
                    self.index = 0
                self.image = self.images_left[self.index]

        #jump + gravity
        self.vel_y += 0.3
        if self.vel_y > 10:
            self.vel_y = 10
        dy += self.vel_y

        #collision
        for tile in world.tile_list:
            #x
            if tile[1].colliderect(self.rect.x + dx, self.rect.y, self.width, self.height) and dx > 0:
                dx = 0

            #y
            if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height):
                #check if below the ground
                if self.vel_y < 0:
                    dy = tile[1].bottom - self.rect.top
                    self.vel_y = 0
                elif self.vel_y > 0:
                    dy = tile[1].top - self.rect.bottom
                    self.vel_y = 0

        #move

        self.rect.centerx += dx
        self.rect.bottom += dy

        if self.rect.bottom > 540:
            self.rect.bottom = 540
            dy = 0

        #onto screen
        screen.blit(self.image,self.rect)
        pygame.draw.rect(screen,(255,255,255),self.rect,2)
</code>
I think the problem is about different rects. Should I just use the same rect for walking and standing?
Answer:
whenever player collide with tiles on x-axis it either flash to the top or bottom of that tile [...]

This problem is obvious. When moving the player near an obstacle, the collision detection prevents the player from overlapping the obstacle, but positioned to touch the obstacle.
However, when you stop moving, the player's image changes and the player's bounding box may change in size. Now the player and the obstacle suddenly collide and the collision detection algorithm places the player at the top or bottom of the obstacle.
I suggest using a constant size hitbox for collision detection, or at least a larger hitbox when the player walks so that they come to a stop far enough away from the obstacle.


Converter SQL para Eloquent do Laraval 5

Question: Estou tentando transformar esse SQL do postgres abaixo para o eloquent no laraval alguem tem uma ideia de como ficaria?
select
  g.id as group_id,
  max(g.name) as name,
  max(g.created_at) as created_at,
  count(ag.asset_id) as veichele
from "groups" g left join assets_groups ag on g.id = ag.group_id
group by g.id;

Answer: Se o seu model eloquent for com o nome Groups é basicamente:
$select = 'groups.id as group_id, max(groups.name) as name,';
$select .= 'max(groups.created_at) as created_at,';
$select .= 'count(assets_groups.asset_id) as veichele';

$result = Groups::groupBy('groups.id')
      ->leftJoin('assets_groups', 'assets_groups.group_id', '=', 'groups.id')
      ->selectRaw($select);

essa seria a construção da Query Builder.


VPN on cloud - IP cameras

Question: Is it possible to have VPN for example on OceanCloud or AWS and make it work as local VPN?
I have 3 security cameras on 3 different lacations which doesn't have public IP adresses and one NAS server on different location too, client is somewhere else also. Is there a possible way to connect all of these to "LAN"?
It would be easy if the camera was on LAN with VPN but i have no idea how would this behave on cloud.
Thank you for answers.
EDIT : I added diagram, for better understanding, how I imagine it to work. https://i.stack.imgur.com/Uw4pD.jpg
Answer: It would require a vpn-client at each site, which acts as (vpn) router. Maybe if your IP-camera supports VPN' (don't know any which do). Otherwise you'd need a server/router on each site (a Raspberry Pi is more than sufficient).
Learn how networking works. And read the OpenVPN Howto, which is nicely written in my opinion. First try to 'tun' each location. Afterwards add routing to the LAN segments. Use route .. (in the openvpn server.conf) to make OpenVPN accept the traffic, and push "route .." so the client knows where to find each camera.
I don't want to depend inward (NAT) routing, so my VPN-servers are located in the Cloud. I'm using 4 servers (VPS') at different datacenters. Each client has 4 VPN's (and bird), which gives me ECMP routing between all clients.
On my LAN segment sit a few devices, none of them serves services on the LAN and they only accept traffic from the VPN. It might be a bit overkill, but this way I don't depend static IP's (can very easily switch from ISP).

VPN on cloud - IP cameras


Ordenação de itens com angular

Question: Estou trabalhando em um sistema que requer paginação dos dados, mas antes eu gostaria de ordenar o json que recebo na ordem dos nomes dos usuários.
O JSON está no formato:
[["22","Aiolinhos","23","firstname.lastname@example.com","Administradores","SIM"],["20","Aiorinhos","21","email@example.com","Administradores","SIM"],["6","Aldebas","7","firstname.lastname@example.com","Administradores","SIM"],["12","Caminhus","13","firstname.lastname@example.com","Administradores","SIM"],["18","Ditinho","19","email@example.com","Administradores","SIM"],["3","Dohkinho","3","firstname.lastname@example.com","Administradores","SIM"],["8","Kanonzinho","9","email@example.com","Administradores","SIM"],["14","Milinho","15","firstname.lastname@example.com","Administradores","SIM"],["4","Muzinho","4","firstname.lastname@example.com","Administradores","SIM"],["2","Saguinha","2","email@example.com","Administradores","SIM"],["1","Shakinha","1","email@example.com","Administradores","SIM"],["16","Shionzinho","17","firstname.lastname@example.com","Administradores","SIM"],["10","Shurinha","11","firstname.lastname@example.com","Administradores","SIM"]]

E os trechos em html+angular que criei para mostrar esses dados para o usuário são:

        <button type="button" class="btn btn-secondary" ng-click="create()">Novo</button>

          {{header}}
          Editar / Remover

        {{cell}}
        <button type="button" class="btn btn-secondary glyphicon glyphicon-pencil" ng-click="edit(row)"></button>
          <button type="button" class="btn btn-danger glyphicon glyphicon-trash" ng-click="delete(row)"></button>

 controller:function($scope,$routeParams,$location,crudservice){
      $scope.headers = [];
      $scope.rows = [[]];
      $scope.modelPath = $routeParams.model;
      $scope.order = 0;
      crudservice.model = {};

      crudservice.listModel($routeParams.model).then(function(response){
        if(response.data.status == 1){
          var data = response.data;
          console.log(JSON.parse(data.headers));
          console.log(JSON.parse(data.rows));
          $scope.headers = JSON.parse(data.headers);
          $scope.rows = JSON.parse(data.rows);
        }
      });

Mas ocorre que a tabela não mostra algumas linhas, além das células Nome, E-mail, Grupo, Ativos e Editar/Remover estarem em locais que não deveriam:

Alguma suposição do porquê isso estar acontecendo?
Answer: Todos os itens que não estão aparecendo possuem os valores da primeira e da terceira coluna iguais:
["3","Dohkinho","3","email@example.com","Administradores","SIM"],
["4","Muzinho","4","email@example.com","Administradores","SIM"],
["2","Saguinha","2","email@example.com","Administradores","SIM"],
["1","Shakinha","1","firstname.lastname@example.com","Administradores","SIM"]

Entretanto seu código deveria ser funcional, como demonstrado no exemplo (funcional) a seguir:

angular.module('myApp', [])
.controller('myController', function($scope){

$scope.rows = [["22","Aiolinhos","23","email@example.com","Administradores","SIM"],["20","Aiorinhos","21","firstname.lastname@example.com","Administradores","SIM"],["6","Aldebas","7","firstname.lastname@example.com","Administradores","SIM"],["12","Caminhus","13","firstname.lastname@example.com","Administradores","SIM"],["18","Ditinho","19","firstname.lastname@example.com","Administradores","SIM"],["3","Dohkinho","3","email@example.com","Administradores","SIM"],["8","Kanonzinho","9","firstname.lastname@example.com","Administradores","SIM"],["14","Milinho","15","firstname.lastname@example.com","Administradores","SIM"],["4","Muzinho","4","email@example.com","Administradores","SIM"],["2","Saguinha","2","email@example.com","Administradores","SIM"],["1","Shakinha","1","firstname.lastname@example.com","Administradores","SIM"],["16","Shionzinho","17","firstname.lastname@example.com","Administradores","SIM"],["10","Shurinha","11","email@example.com","Administradores","SIM"]];

});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                        {{cell}}

                            <button type="button" class="btn btn-secondary glyphicon glyphicon-pencil" ng-click="edit(row)"></button>
                            <button type="button" class="btn btn-danger glyphicon glyphicon-trash" ng-click="delete(row)"></button>

A minha suspeita é que a sua fonte esteja de alguma forma manipulando o array de arrays, criando um map inválido.
Comment: obrigada por responder. Então, eu achei o ponto em que estava errando. Na minha classe UsuarioRestController em que eu manipulava o dado da view, estava mapeando o header do json com um campo a mais, sendo que a view estava "esperando" um campo a mais. Creio que tenha sido isso que você citou, uma manipulação de map errada.
Comment: Ah, sim - em um segundo momento, dá pra notar esse efeito no screenshot que você postou. Que bom que você encontrou o problema, @Alessandra!
Answer: Resolvido! \o/
Modifiquei meu usuarioRestController:
@RequestMapping(value = "/usuario/list", method = RequestMethod.GET)
public String listar() {
    Gson gson = new Gson();
    Map<String, String> response = new HashMap<String, String>();

    String[] headers = {"ID" ,"Nome", "Login", "E-mail", "Grupo", "Ativo" };
    List<String> usuario = new ArrayList<String>();
    try {
        this.usuarioList = usuarioService.listarUsuarios(this.pesquisa);
        String[][] usuarios = new String[usuarioList.size()][];
        response.put("status", "1");
        response.put("headers", gson.toJson(headers));
        for (int i = 0; i < usuarioList.size(); i++) {
            usuario = new ArrayList<String>();
            usuario.add(usuarioList.get(i).getId().toString());
            usuario.add(usuarioList.get(i).getNome());

            usuario.add(usuarioList.get(i).getLogin());
            usuario.add(usuarioList.get(i).getEmail());
            usuario.add(usuarioList.get(i).getGrupo().getNome());
            usuario.add(usuarioList.get(i).getAtivo().name());
            usuarios[i] = usuario.toArray(new String[usuario.size()]);

        }

        response.put("rows", gson.toJson(usuarios));

    } catch (Exception e) {
        response.put("status", "0");
        e.printStackTrace();
    }
    return gson.toJson(response);
}

Adicionei a String "ID" ao array de headers, para que a view pudesse "casar" com o que vinha da base de dados. Agora está ordenando e fazendo o CRUD de dados.
Obs.: não sei se essa é uma boa forma de resolver esse problema, mas foi a que melhor me atendeu no momento.

Ordenação de itens com angular


Does every irreducible projective cubic curve have a nonsingular point of inflection?

Question:
Does every irreducible projective cubic curve necessarily have a nonsingular point of inflection?

I've been trying to construct counterexamples, to no avail, which leads me to believe the question can be answered in the affirmative. Here we take $\mathbb{C}$ to be the ground field.
Answer: I think so. You can always stick an irreducible cubic into a more or less standard form $y^2=x(x-\lambda_1)(x-\lambda_2)$ by a linear change of variables. Then on the patch $y=1$ the curve is nonsingular -- either the whole curve is nonsingular or it has a unique singular point at the origin in the $xy$-plane, depending on the values of the $\lambda$s -- and in the form $z=x^3+ax^2z+bxz^2$. The tangent line here is clearly $z=0$ and it is also clearly inflectionary, as there is no degree-$2$ piece.