How does the YOLO network create boundaries for object detection?

Question: I'm not sure I understood how the YOLO network works. If you look at the description, https://pjreddie.com/darknet/yolo/, it appears to me that all is done thanks to convolution only. You end up with NxNxM results, where each M array contains a couple bounding boxes, classes, etc. Apparently, from the way I understand it, is each array in those M wide cells you will have 4 values that tell the center position (but only if it lies in that grid cell), then the width and the height of the bounding box. This way it seems that the bounding box is "around" the cell.
See the explanation at https://medium.com/diaryofawannapreneur/yolo-you-only-look-once-for-object-detection-explained-6f80ea7aaa1e
But each cell is an aggregation of feature cells beneath that very same cell, so how is it possible that it may encode the size of the bounding box outside of it?
Answer: No, YOLO doesn't use only convolutions. As you can see in the architecture diagram, there are two fully-connected layers between the main convolutional part and the final convolutional output.

These fully-connected layers allow it to essentially do regression on the bounding box center coordinates as well as the size and width which can range over the whole image. Please let me know if I haven't understood your question correctly!
Answer: Disclaimer: This answer contains details about the SSD object detector net rather than YOLO, but the core idea is similar.
You are right that each cell in a feature map produced by a convolutional network represents some information about the corresponding region of the image. On the illustration bellow you can see a 4x4x256 feature maps visualized and the corresponding 4x4 grid of the original image:

However, that is not the same as the receptive filed of each of those cells: Receptive field would be the region of the image, whose pixels were used to compute the value of the cell. The exact receptive field depends on the exact size and number of your convolutional layers, but it is usually much larger than the image cell. That means the cell contains also information about its surroundings and it can predict also bounding boxes larger than itself.
Now regarding the mechanism of individual bounding box predictions (which are also realized as convolutions): You predefine some number of anchor boxes (bottom right in the image) defined as width and height, centered in the center of the cell. For each of them, the network predicts 4+num_classes numbers:

vertical offset of the center
horizontal offset of the center
width difference
height difference
probability of each class that an object of this class is present in this bounding box (these are normalized via softmax)

Therefore, $M = \mathrm{num\_anchors}\, \cdot\, (4+\mathrm{num\_classes})  $.
Comment: Thanks for the informative answer. Please elaborate on **The exact receptive field depends on the exact size and number of your convolutional layers**? The "receptive fields" means the 2 bounding boxes that YOLO predicts? What is the relation between the number of conv layers and the bounding boxes geometry?


Port foward to Server that has different gateway

Question: We have two ISPS (2 gateways  one Sonicwall and one Verizon Router) and one internal LAN.
The sonicwall internal IP is 192.168.1.1 and verizon is 192.168.1.2
On the sonicwall I configured a port forward for RDP to go to an internal server on the same 192.168.1 network. However, this server is using the Verizon router as a gateway.
When I tested it out, it doesnt work. I guess i'm trying to understand why it doesnt work. if the Sonicwall can ping the internal Server's IP, why can't it forward to this Server? Why does the Server HAVE to use the sonicwall as a gateway for this RDP to work?
Comment: Because routing happens at layer 3. When the Sonicwall forwards the traffic to the server, the server sees that the source ip address is not local and attempts to communicate with the source via its default gateway, which is the Verizon router.
Comment: I'd use an ssh tunnel or a UDP proxy to work around this.
Answer: you could try to add a static route on the RDP server (that server that has a default gateway to verizon / 192.168.1.2).  the static route would look like:

$remote_rdp_client_public_ip/32 via 192.168.1.1


Random forest regression produce different importance ranking

Question: I've been working a random forest regression model with my own datasets using the randomForest package.
The model produces a % var explained of ~27%. I also used the importance() function to produce a ranking of the relative importance of the variables, but everytime I use a different number for the set.seed() function, the random forest model produces a different ranking. It should be mentioned that I have several variables whose importance are relatively close.
I am wondering is there a consistent way to produce the ranking of the variable importance?
Answer: No- no consistent variable importance value is possible in this case.
The variable importance changes because the underlying model itself changes each time you change the seed value. Different models will have different values for variable importance.
One thing that you could do would be run many (say, 10) Random Forest models with different seed values and average the variable importance scores across the models- this would get you a better approximation of what you could expect variable importance to be on average from each individual Random Forest model you train on the dataset.
Comment: Id also reccomend bootstrapping + averaging, this should be standard practice. It has the benifit that you can also estimate the variance of your importance eatimates as well
Answer: It should be noted that RFs are an approximating approach to modelling (typically) massive amounts of information, based on a large number of bootstrapped, finite data "mini-models." Only in the theoretical, infinite limit do they approach stable, consistent results. As such, and even with massive numbers of bootstrapped subsamples, they remain approximating estimators that are subject to change as a function of the random draws from the underlying empirical information. This result generalizes to all finite data resampling tools including the bootstrap, jacknife, data augmentation, RFs, k-fold CV, you name it.
In other words, there is only one way to reproduce the rankings from one RF to the next and that is by using the same seed. You can evaluate the extent to which the rankings are consistent using a Spearman correlation for ordinal relationships based on the different importance rankings
Answer: I have another opinion to the different importance ranking, there are following reasons for this variation:
First, maybe there some highly correlated variables. random forest can't remove the highly correlated variables because of independent select features and tree construct process, so the highly correlated variables importance ranking will change every time. You can remove some highly correlated variables.
Second, the parameters of random forest is not tuned. you can tuning the parameters, and plot the parameters vs. rmse, then select a more suitable parameters.
Using the corresponding method, maybe you can produce a more stable results.


How to create template file for specific node?

Question: As I asked above is it possible to create template file for specific node id.
I now we can create template file for content type, but not clear for node id.
E.g. Suppose there are 10 Articles in website, each has node id from 1-10.
Now question is I want to create template file for node id 3. When user visit article node id 4, then user will see different page.
Answer: In Drupal 7, you can use node--[node-id].tpl.php for theming specific nodes. In your case, you can use node--3.tpl.php.
Comment: Thanks Suresh, I have one more query regarding this. Suppose instead of node id, if there is  alias in url and we don't know the node id then how we can create template in this condition.


Does variable_get() first go to 'variable' table in the database or the $conf array in settings.php?

Question: I can't tell from the source for variable_get() for Drupal 6 whether it first looks for something in the variable table in the database, or the $conf array in settings.php.
Also, if I were to add something in some code to the $conf array, would I need to do anything in order for variable_get to see it?
global $conf;
$conf['myvalue'] = 'newvalue';

If 'myvalue' were set to 'oldvalue' in settings.php, then what would I need to do in order for $conf['myvalue'] to now return newvalue instead of oldvalue?
Answer: The function that is responsible for loading the values of the Drupal variables in memory is variable_init(), which executes the following code:
  if ($cached = cache_get('variables', 'cache')) {
    $variables = $cached->data;
  }
  else {
    $result = db_query('SELECT * FROM {variable}');
    while ($variable = db_fetch_object($result)) {
      $variables[$variable->name] = unserialize($variable->value);
    }
    cache_set('variables', $variables);
  }

  foreach ($conf as $name => $value) {
    $variables[$name] = $value;
  }

$conf, the value passed to the function from _drupal_bootstrap() is the array read from the settings.php file. The function that reads the configuration file is conf_init(), which is called from _drupal_bootstrap() before calling variable_init().
As you see in the code, the values read from the database are then overwritten with the values find in the $conf array.
Similar code is present in Drupal 7 (see drupal_bootstrap(), _drupal_bootstrap_configuration(), and _drupal_bootstrap_variables()).
The only way to use the value read from the database is to remove the value set in settings.php.


Difference in Flux for Shallow Water

Question: I am looking for some help understanding if there is a difference in these two forms of the shallow water equations:
$\partial_t(\eta u)+\partial_x((\eta u)^2+\frac{1}{2}g\eta^2)=0$ (Momentum)
$\partial_t \eta+\partial_x(u\eta)=0$ (Area Conservation)
Simplifying the Momentum equation with the Area Conservation equation yields:
$\partial_tu+\partial_x(u^2/2+g\eta)=0$
$\partial_t \eta+\partial_x(u\eta)=0$.
where $u$ is the depth averaged horizontal velocity, $\eta$ is the depth, and $g$ is a constant.
Are the solutions to these two sets of equations the same? I am especially confused since they have different fluxes which would lead to different Rankine-Hugoniot conditions. Does anyone have a clear explanation or resource for how to think about this?
Answer: The two systems have the same differentiable solutions, as you prove by manipulating one system into the other; this argument relies on the functions being differentiable.
For solutions with shocks, they do not have the same solutions, because as you say, the jump conditions are different for the two systems.
The first system ought to be taken as the more important one, because it is intended as a model of a physical process, and the derivation uses fundamental physical reasoning, namely conservation of mass and conservation of momentum (or Newton's law, whichever you prefer to call it). The second system is less physical because there is no such thing as conservation of velocity. I prefer to think of the unknown functions in the first system as the physically conserved things, say $(\eta,m)$, depth and momentum $m=u\eta$.
By the way your first equation should have only one place where $\eta$ is squared.
Interestingly, it seems that both systems agree about the speed of a
very small jump in $(\eta,u)$, approximately $\sqrt{g\eta}$. I might be wrong about this, but don't have time right now to recheck.
Answer: This stems from the fact that after the reformulation there is no conservation law for $\eta u$, but instead for $u$ only. Thus, in general, you would be in trouble if the fluxes $f_1(\eta, u), f_2(\eta, u) $ would be the same for the conservation laws $$\partial_t (\eta u) + \partial_x f_1(\eta, u) = 0 \\ \partial_t u + \partial_x f_2(\eta, u) = 0.$$
Comment: I am still not sure what this means. I see that the conservation equation is for a different quantity but I don't understand if that would lead to a different solution or not.
Comment: I think by the reformulation you only exclude the trivial case $\eta \equiv 0$, which is a solution to both conservation laws in the first formulation. In the second formulation the momentum equation is not immediately fulfilled for $\eta \equiv 0$. (Although $\eta \equiv 0$ corresponds to the case that there is no water, so you would possibly exclude this anyways by demanding $\eta > 0 $.)

Difference in Flux for Shallow Water


If $x^2=e,y\neq e$ and $x^{-1}y^2x=y^3$ prove that $O(y)=5$

Question: I tried many ways to prove it but I couldn't find a method to prove it
Answer: We only need to prove that $y^5=e$. Note that $x^2=e$ implies $x=x^{-1}$. We have $y^4=(xy^3x)^2=xy^6x$ and $y^6=xy^9x$, so $y^4=x(xy^9x)x=y^9$ and obtain $y^5=1$
Comment: Thank you very much. That helped


How do I send verification mail from my drupal custom module?

Question: I have written a custom module, which can send simple mail. how do I send mail so that user should get the verification link or something similar.
<?php
/**
* implements hooks_menu
*/

function planet_extension_menu(){
$items['planetext']=array(
'title' => t('DEMO Planet Extension'),
'description' => 'Feeds aggregation ',
'page callback' => 'drupal_get_form',
'page arguments' => array('planet_extension'),
'access callback' => TRUE,
);
return $items;
}

// callback function
function planet_extension($form,&$form_submit){
$form['url']=array(
'#title' => 'URL',
'#type' => 'textfield',
'#required' => TRUE,
'#size' => 35,
'#description' => t('Enter the URL'),
'#attributes' =>array('placeholder' => t('www.example.com'))
);
$form['title']=array(
'#title' => 'Title',
'#type' => 'textfield',
'#required' => TRUE,
'#size' => 35,
'#description' => t('Enter the Title'),
'#attributes' =>array('placeholder' => t('Title'))
);
$form['email']=array(
'#title' => 'email',
'#type' => 'textfield',
'#required' => TRUE,
'#size' => 35,
'#description' => t('Enter you valid email'),
'#attributes' =>array('placeholder' => t('email@example.com'))
);
$form['submit']=array(
'#type' =>'submit',
'#value' => 'Submit',
);
return $form;
}

// below is the form submission function
function planet_extension_submit($form,$form_state){
//store the values entered in form into variables
$values = array(
'url' => $form_state['values']['url'],
'title' => $form_state['values']['title'],
'email' => $form_state['values']['email'],
);
//insert the variables into the table
$insert = db_insert('planet_extension')
                -> fields(array(
                        'url' => $values['url'],
                        'title' => $values['title'],
                        'email' => $values['email'],
                ))
                ->execute();

drupal_mail('planet_extension', 'planet_extension_mail', $form_state['values']['email'], 'en', array('values' => $values));

        drupal_set_message(t('Form submitted. Check your email for verification')); //custom message after form submission is successful
}

//implements hook_mail
function planet_extension_mail ($key, &$message, $params) {
  switch ($key) {
    case 'planet_extension_mail':
      $message['subject'] = t('Hello');
      $message['body'][] = t('Hello user');
      $message['body'][] = t('The main part of the message.');
      break;
  }
}

Comment: Format the code a bit, it will help other people understand what it does. Regarding your question - you will need a table to store generated verification codes paired with appropriate email addresses and a link that will accept the code, redirect to home page and show the message to the user.
Comment: Thank you so much for reply. But, how do i generate verification codes and pair with email ??
Comment: what kind of verification mails are you sending?
Comment: just the verification link in the mail to the user who entered the form. so that the user can click that link and verify.

hope i am clear for you. thank you
Comment: The logic of generating verification codes is up to you. You can have a look at the default Drupal implementation in user module: `modules/user/user.module`, line 2323, function `user_pass_reset_url()`.
Answer: I am not sure about what kind of verification emails you are sending, though I believe if you peep inside drupal core user module you can get hold of function which does the same,as for user registration process we have email verification option also.
A very simple straight custom way might go in the following way

How you will be generating the verification code?

while sending the email create a link something like www.mydomain.com/email-verification/%random_string%

Create a custom table with column as email,random_string,verified
once you have generated it, make a db query to insert the link you created a point back against the email user entered and set verified to 0 in the custom table.
send the email
In your custom module implement hook_menu() with menu entry fir "email-verification" .
In the page callback using wild card check if the random_string exists in you custom table, if so set verified to 1

Not exact but close to what you may need.
Update:
global $base_url;
$random_string = substr(str_shuffle(md5(time())),0,10);
// Link
$email_link = $base_url . "/email-verification/" . $random_string;

Comment: yes it is close enough to get me started with. thanks man really appreciated.
Comment: in step 1 : how do i create a link ?
Comment: @shrish check the updated answer


Plotly.js shift graph on x-axis by offset programmatically

Question: I'm rendering a 'scattergl' graph.
In my app there's the ability to switch between

data from a specific time frame,
or to show live data (updating each second).

For live view I'm using extendTraces to push new points every second.
In the live view I would like to change the x position of my graph, so the graph kind of "moves" through the screen having the new points always appear in the same spot.
Right now it is autoscaling, I don't want that when data is being streamed but I don't know how to set the frame or position or sth to achieve my goal.
This is now with the autoscaling:

This is opticallz what I want, + have all new points appear at the same spot, having old data being shifted to the left:

Also when switching from fixed time frame to live view I'd like to then "jump" to the updating data because when in live mode I'm not interested in the "big picture". I may like to zoom out manually, or pan back etc. but on switch it should "zoom" by my code to the new updating points.
I seem to use wrong search terms. Maybe someone knows the correct configuration option to pass ?
how I extend:
Plotly.extendTraces(nativeElement, {x, y}, numbers, maxPoints);

this is part of my data:
{
  "data": [
    {
      "type": "scatter",
      "x": [
        "2020-11-18T09:52:58.000Z",
        "2020-11-18T09:52:59.000Z",
        "2020-11-18T09:53:00.000Z",
        "2020-11-18T09:53:01.000Z"
      ],
      "y": [
        4.637524903199999,
        4.635876884400001,
        4.6342288656,
        4.635876884400001
      ],
      "time": [],
      "mode": "lines",
      "marker": {
        "size": 5
      },
      "domain": {
        "x": [
          0.25,
          0.75
        ],
        "y": [
          0.25,
          0.75
        ]
      },
      "showlegend": true,
      "name": "Euro/time\r\n<Beleuchtung 1>",
      "stackgroup": "one",
      "fill": "tonexty",
      "line": {
        "color": "rgba(230,230,77,1)",
        "width": 1,
        "dash": "solid"
      },
    },
  ],
  "layout": {
    "margin": {
      "l": 50,
      "r": 50,
      "t": 5,
      "b": 50
    },
    "autosize": true,
    "showlegend": false,
    "hovermode": "closest",
    "legend": {
      "x": 0,
      "y": 1,
      "traceorder": "normal",
      "font": {
        "family": "sans-serif",
        "size": 10,
        "color": "#000"
      },
      "bgcolor": "#E2E2E255",
      "bordercolor": "#FFFFFF",
      "borderwidth": 2,
      "orientation": "h"
    },
    "title": null,
    "xaxis": {
      "tickfont": {
        "color": "#333",
        "size": 8
      },
      "title": null,
      "titlefont": {
        "color": "rgb(148, 103, 189)",
        "size": 10
      },
      "nticks": 20,
      "domain": [
        0.01,
        0.99
      ],
      "tickformatstops": [
        {
          "dtickrange": [
            null,
            1000
          ],
          "value": "%H:%M:%S.%L"
        },
        {
          "dtickrange": [
            1000,
            60000
          ],
          "value": "%H:%M:%S"
        },
        {
          "dtickrange": [
            60000,
            86400000
          ],
          "value": "%d.%m. %H:%M"
        },
        {
          "dtickrange": [
            86400000,
            604800000
          ],
          "value": "%d.%m.%y"
        },
        {
          "dtickrange": [
            604800000,
            "M1"
          ],
          "value": "%d.%m.%y"
        },
        {
          "dtickrange": [
            "M1",
            "M12"
          ],
          "value": "%b '%y"
        },
        {
          "dtickrange": [
            "M12",
            null
          ],
          "value": "%Y Y"
        }
      ]
    },
    "yaxis": {
      "tickfont": {
        "color": "rgba(0,0,0,1)",
        "size": 8
      },
      "title": "Geld [T€/year]",
      "titlefont": {
        "color": "rgba(0,0,0,1)",
        "size": 10
      },
      "side": "left",
      "domain": [
        0.05,
        0.95
      ],
      "showgrid": true,
      "ticks": "",
      "showticklabels": true,
      "position": 0
    },
    "hoverlabel": {
      "font": {
        "size": 10
      },
      "bgcolor": "#FFF",
      "namelength": -1
    }
  }
}

Answer: You can achieve that by using a range value inside x-axis layout property.
layout = {
    xaxis: {
        autorange: false,
        range: ['2016-07-01', '2016-12-31']
   },
   .....
};

https://plotly.com/javascript/time-series/#manually-set-range


How do I migrate from the Taxonomy Access Control module to the Group module?

Question: We have a Drupal 6 site, and we are making use of the Taxonomy Access Control module for access control. We evaluated the migration steps, and even if that module could be ported to Drupal 8, we could use a different approach.
We are evaluating the Group module as an alternative to content access control, but there are no automatic path to migrate from. What would the preferred migration path be?
Answer: My recommendation: go for such replacement. In doing so, you could use the approach detailed in How to bulk assign content to a group. This community documentation page explains how you can use the Rules module together with the VBO module to bulk-assigning existing content to groups.
Here is the Rules Component included in that page (in Rules export format):
<code>{ "rules_assign_a_node_to_a_group" : {
    "LABEL" : "Assign a node to a group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ACCESS_EXPOSED" : "1",
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "group" : { "label" : "Group", "type" : "group" }
    },
    "ACTION SET" : [ { "data_set" : { "data" : [ "node:group" ], "value" : [ "group" ] } } ]
  }
}
</code>
Refer to the community page mentioned above for more details.
PS: the above rule assumes your migration target is D7 (there is no stable Rules release for D8 yet ...). But by using the Group module you're in very good shape also to later on upgrade to D8 also, since this module supports both releases.


Number of ways to send out $k$ distinct postcards to $n$ friends if we require each friends receives at least $1$ post card.

Question: This problem comes from the Lovasz Combinatorial Problems and Exercises book. I'm left rather confused for the second half of the second problem. It asks:  We have $k$ distinct postcards and want to send them all to our $n$ friends (a
friend can get any number of postcards, including 0). How many ways can this
be done? What happens if we want to send at least one card to each friend?
The first half is rather simple, however, the second half has me puzzled. This is equivalent to counting the number of surjections yes? However, the answer in the back of the book is $\binom{k}{n}*n!$.
My reasoning gives me that the number of ways to do this would be:
$$n^k-\sum_{i=1}^{n}\binom{n}{i}(n-i)^{k}$$
(something like that I'm typing in a bit of a rush so forgive a mistake if there is one).
But my reasoning is that you count the number of ways to send out the postcards in any manner, and subtract out the ones where you miss some group of $i$ friends. I can't see my error or how my answer is related to the books.
Answer: I think you meant $$\sum_{i=0}^n(-1)^i\binom{n}{i}(n-i)^k$$
And what the book meant was using Stirling numbers of the second kind, viz $${k\brace n}n!$$
Comment: In the formula the way you wrote, the signs need to alternate. $$n^k - \binom{n}1 (n-1)^k + \binom{n}2 (n-2)^k - ... $$
Comment: For more information, see [Stirling numbers of the second kind](https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind).
Comment: @trueblueanil Apologies yes there was supposed to be an alternating -1 from inclusion exclusion.
Answer: The answer in the book i.e. $\begin{pmatrix}k\\n\end{pmatrix}.n!=\frac{k!}{(k-n)!}$ represents the number of permutations of $n$ objects out of total $k$ distinct objects; which surely is the number of ways to distribute $k$ postcards among $n$ friends so that each gets exactly one. To get the correct answer, you need to further distribute the remaining $k-n$ postcards among $n$ friends without any restriction. Now this can be done in $n^{k-n}$ ways so the correct answer is the product $\frac{k!}{(k-n)!}\times n^{k-n}$.
Answer: I believe you're right. The solution given by the textbook, $\binom{k}{n}*n!$ is the number of ways you can send out the $k$ cards such that every friend gets exactly one. (First we assume $k \geq n$). We first choose the $n$ cards to send ($\binom{k}{n}$), next we count every permutation of the chosen cards over the friends (multiply by $n !$).
Obviously this does not count, for example, the possibility that everyone gets at least one card and one gets all leftover cards (which adds $\binom{k}{n-1}*n$ possibilities).


Partial Orders and Hasse Diagrams: Totally confused

Question: Seems I've stumbled upon one of the most confusing topics in discrete mathematics...My book does a terrible job of explaining how you actually create Hasse diagrams and only shows premade diagrams without explaining how they're constructed.
Example:

How on earth do you draw these things? The above diagram makes NO sense whatsoever to me. I already read this post about Hasse diagrams, but it didn't clear up my confusion as to how you actually go about drawing these things. In the above diagram for the partial order on the set of letters, how did they decide where each letter would go? Why are $B$ and $G$ off to the side? All of it seems very arbitrary to me and not at all intuitive.
Answer: A partially ordered set can be considered as a directed graph. In a Hasse diagram, the edges $u\rightarrow v$ are drawn in the plane such the node $u$ is drawn below the node $v$ and there is an undirected edge $u-v$. With this kind of drawing, you can drop the direction. Moreover, in a Hasse diagram, you don't draw transitive links. If $u\rightarrow v$ and $v\rightarrow w$, then $u\rightarrow w$ but you don't draw the link $u-w$. This gives you a very compact graphical representation of a poset.


IdentityServer4 and SPA Applications and New User Registration

Question: What is the correct approach to handle new user registration for a SPA (Angular) application?  I am using IdentityServer 4 for authentication (Code Flow) and authorization to my APIs and that is working well.  However, I am unsure where should new user registration takes place, especially I want the new user to be automatically logged in after registration, in other words, I would not want them to have to go to a log-screen after registration.  Should the registration be handle in the SPA application or in a special view in IdentityServer?  In either case, how do I get the JWT token afterward to allow access to my APIs?
Thanks in advance.
Comment: this seems to be similar question https://stackoverflow.com/questions/42450840/user-registration-process-with-identityserver4?answertab=active#tab-top
Answer: You'll want the registration to be handled in the Identity Server project.  You can add two new methods to the AccountController.cs class that will be similar to the Login* methods in the class, one for loading the page and another for handling the registration input.
Assuming that you are using Microsoft Identity for managing user accounts you can have your registration endpoint take the info from the registration page, create the Identity in the database, then call the same login method that the login endpoint calls.  Something along the lines of this
// Do model validation, verify the user doesn't already exist, etc...
...
var createUser = await _userManager.CreateAsync(new ApplicationUser
    {
        Email = model.UserName,
        NormalizedEmail = model.UserName,
        UserName = model.UserName,
        FirstName = model.FirstName,
        LastName = model.LastName
    }, model.Password);
var user = await _userManager.FindByEmailAsync(model.UserName);
if (createUser.Succeeded)
{
    // Add roles to the user
    await _userManager.AddToRoleAsync(user, "Customer");
    var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, lockoutOnFailure: false);
...
// You'll want to redirect back to the client site to complete the login process


Streaming WebRadio

Question: I want to stream a webradio channels but android MediaPlayer Supports only streaming of files that are in downloadable form.
Anybody have solution for this?
Answer: You can play the web radio stations as shown here.
Please note that the "audio/aacp streaming is not supported directly" so you have two solutions:
1- Use some decoder
2- Use some local Streaming Proxy
For detail about above two points please see this.
Answer: You can use any of the RTSP servers to do it, e.g. Wowza works just fine and there are many other rtsp servers out there. You might want also some encoder, adobe live encoder with AAC plugin is a good option.

Streaming WebRadio


How does one automate the install of lessc using pip and setup.py?

Question: I have a django project that uses the django-static-precompiler, which required lessc (a css pre-processor) for converting LESS files into CSS.
Unfortunately, lessc is not a Python program, and the django-static-precompiler documentation doesn't give tips on how to include this automatically.
I'd like a user to be able to run setup.py install and be at a point where the system is relatively functional, but this is a small hurdle.
What can I put in setup.py to require the install of lessc, or any non-pip available package for that matter?
Comment: Did you check out fabric and fabtools? They can install system packages for you or run any other system command. http://stackoverflow.com/questions/11861802/fabric-api-direct-call-in-python
Answer: Try the virtual-less package.  It uses python-less to create a lessc executable in your virtualenv.
pip install virtual-lessc

lessc styles.scss styles.css

Comment: it's got to be 'pip install virtual-less'


count column in SQL and obtain condition

Question: I have a table with name test in Oracle, and (sal(integer),gender) are the two columns in it.
I want to get counter number where gender is male, sal betwwen 1000,3000.
For example:  If I have three people in table test (two male ,one  female) and person1 sal =1000, person2 sal = 2020, person3 sal = 1040
The return value of sql statement will be equals (2).
The variable will store return value from java.
Comment: variable witch store count of person male and sal values from(1000,3000)
Comment: there's no function `sal` in oracle
Comment: sal is column name , can u tell me how to store value of condition that i wrote in question ..
Answer: you actually want to count rows not column, as per what i understood from ur question. then you can use count(column_name) function of SQL along with the conditions (where clause).
Query: SELECT COUNT(*) "Count" FROM test WHERE gender='male' AND salary BETWEEN 1000 AND 3000
Comment: in this table person1, person2 = male
person3 =female
Comment: thanks sooo much , but i wont to store it in java  variable .
Comment: as similar to how you query any other SELECT statement, it will return a resulset. whose result will contain only 1 row and 1 column, from which you can call getInt(0), and store it in a variable.
Comment: sire , why getInt(0) , whats (0) ?
Comment: do u think require while(rs.next()) ?
Comment: getInt(int index), it takes the index of columns in result-set. as there would be only 1 column, the 0th index would be that column.
Comment: please see my code
int i=0;
resultset = statement.executeQuery("SELECT COUNT(gender) FROM test WHERE gender= 'Male' AND sal  BETWEEN '111' AND '200'");
while (resultset.next())
{i++}
i = resultset.getInt(0);
Comment: to keep it simple, being just 1 row, you can actually skip while :::-

resultset = statement.executeQuery("SELECT COUNT(gender) FROM test WHERE gender= 'Male' AND sal = '111' ");

resultset.next();
int i = resultset.getInt(0);
Comment: yesss,  i understood  , u say that if i have more row then can i while . right ?
Answer: try this query,
select count(*) from <table_name> where gender='male' and salary between 1000 to 3000;

Comment: thank u , i know . but return value store in variable java !!?  can u help
Comment: yes, you need to store it in java variable only. You can use java.sql.ResultSet and iterate on it using resultSet.next() and you can access those values in java code


How to create DataTemplate dynamically and assign a StackPanel to it?

Question: Lets say I want to make the following a DataTemplate:
StackPanel stackPanel = new StackPanel();

Button button1 = new Button();
button1.Click += button1_Click;
Button button2 = new Button();
button2.Click += button2_Click;

stackPanel.Children.Add(button1);
stackPanel.Children.Add(button2);

How can I turn this into DataTemplate? I tried creating an instance of DataTemplate class, but I see no method or property that would let me set the stackpanel above as the content of the DataTemplate object.
EDIT:
I am trying to do this in a Windows Store app.
Comment: I think you could try assigning the `StackPanel` to the `DataTemplate` object's `VisualTree` property, but that is just a guess.  Why don't you just build the template in XAML?
Comment: DataTemplate object doesn't have VisualTree property, unfortunately. And I can't do it in XAML for reasons that are too complex to explain right now :/
@TonyVitabile
Comment: Actually, according to this: http://msdn.microsoft.com/en-us/library/system.windows.datatemplate(v=vs.110).aspx, it does.  It's inherited from `FrameworkTemplate`.
Comment: Yeah, but I am building a Windows Store app. The only availaible class named "DataTemplate" would be this:
http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.datatemplate.aspx
@TonyVitabile
Answer: The accepted answer to this question shows how you build a DataTemplate in the code behind.
//create the data template
DataTemplate objDataTemplate = new DataTemplate();
objDataTemplate.DataType = typeof(CreditCardPayment);

//set up the stack panel
FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(StackPanel));
spFactory.Name = "myFactory";
spFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal); // Use Oritentation.Vertical if appropriate.

//Your code for creating the buttons goes here.

//set the visual tree of the data template
objDataTemplate.VisualTree = spFactory;

That should do it.
Comment: Unfortunately, Windows Store apps don't have access to the mentioned FrameworkElementFactory and DataTemplate classes :/
This is the only availaible class named DataTemplate:
http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.datatemplate.aspx
Comment: Sorry, your question originally didn't say that.  Why don't you try building a test app with a simple `DataTemplate` in XAML in the window's resources, then get a reference to the resource & inspect it?  That will show you what you have to build, then you can back into what code to write to produce the similar template.
Comment: That makes a lot of sense, will try that. Thank you!
@TonyVitabile
Answer: Create a new StackPanel, add the DataTemplate object as a child of it.
StackPanel stackPanel = new StackPanel();
stackPanel.Children.Add(objDataTemplate);

Are you looking for this (although you will not able do it like this), or I misunderstood your question?

UPDATE:
  For the opposite

DataTemplate objDataTemplate = new DataTemplate(typeof(StackPanel));
        FrameworkElementFactory stPanelElement = new FrameworkElementFactory(typeof(StackPanel));
        objDataTemplate.VisualTree = stPanelElement;

Hope this will help.
Comment: I am trying to do the opposite, assign StackPanel to DataTemplate.
Comment: If you have both, the `StackPanel` and the `DataTemplate`, then why are you trying to do the opposite?
Comment: Unfortunately, Windows Store apps don't have access to the mentioned FrameworkElementFactory and DataTemplate classes :/
@Debasis


How should staccatissimo be played?

Question: How should staccatissimo be played on Handel, Beethoven, and Liszt pieces? I have read that it is like staccato only shorter, but it seems like it is used when notes should be staccato and accented. Am I dreaming?
Comment: Generally staccato notes should be accented slightly anyways.
Answer: You're right, it is accented and shorter. The notes should be extremely separated and distinct.

How should staccatissimo be played?


Value for calculated property only if bit value equals true

Question: If I am going to have a page that displays Ingredients that are marked IsProduct on one page and use the Ingredient name to generate an image url value.
And then on another page use ingredients that are not marked IsProduct. Is there anything I could do so that when I display the ingredients that are not marked IsProduct that they will not shot a URL value for ProductImage, because it's not a product.
Is there something I should be doing in the class? or since it's a calculated value shuld I just be doing it when I'm writing the items to the page.
<code>    namespace XXX.Models
    {
        public class Ingredient
        {
            public int IngredientID { get; set; }
            [StringLength(50), Column(TypeName = "varchar")]
            public string IngredientNameEn { get; set; }
            [StringLength(50), Column(TypeName = "varchar")]
            public string IngredientNameEs { get; set; }
            [Column(TypeName = "varchar(Max)")]
            public string IngredientDescriptEn { get; set; }
            [Column(TypeName = "varchar(Max)")]
            public string IngredientDescriptEs { get; set; }
            [Column(TypeName = "bit")]
            public bool IsProduct { get; set; }

            public string ProductImage
            {
                get { return IngredientNameEs.Replace(" ", string.Empty) + ".jpg"; }
            }
        }
    }
</code>
Answer: This question is a bit confusing.  I think you are asking for a way to generate an URL for a valid product, and hide/disable the URL for a non product.
Outside the issue of which area of MVC should have this logic...
The code can be the same
<code>    string url == string.Empty;
    if (model.IsProduct)
    {
        var builder = new UriBuilder();
        builder.  { populate the needed properties ,  model.ProductImage}
        url = builder.ToString();
    }
</code>


How can I find the roots of a quadratic function?

Question: Bascially we are trying to find the roots of a quadratic equation, and 'apparently' there is a theorem for this, but every one that I have found so far mentions that the degree of the polynomial is directly related to the number of zeros (where X is an integer and Y is 0).. However, most of the theorems also mention complex numbers, which our math teacher does not want us to include in this theorem. Does anyone know of a way to find the number of real zereos using a theorem that does not involve complex numbers?
Note: The theorem also has to account for vertical shifts, which I don't see how that can be possible.
Comment: Use the [discriminant](http://en.wikipedia.org/wiki/Discriminant#Quadratic_formula) of the quadratic polynomial to find the number of (real) roots.
Comment: I don't understand what you mean by "account for vertical shifts".  The discriminant of the quadratic polynomial $f(x) = ax^2 + bx + c$ is $b^2 - 4ac$. If it is positive, the quadratic polynomial has two real roots.  If it is zero, the polynomial has one real root (with multiplicity two), and if it is negative, the polynomial has two complex (and hence, zero real) roots.
Comment: One other alternative: If you can find the vertex of the polynomial, then knowing the $y$-value of the vertex and knowing whether the quadratic function opens up or down will tell you how many times the quadratic crosses the $x$-axis.
Comment: Note that the quadratic equation has two roots -- both real roots or no real roots.
Comment: Just to nitpick: roots belong to equations, zeros belong to functions.
Answer: The quadratic functions are generally in the form $f(x)=Ax^2+Bx+C$.
The zeroes of this function is then the solution to the equation $Ax^2+Bx+C=0$.$($where $A\ne 0)$
Hence we try to solve this equation.
If you try to solve the equation (just like you'd solve a linear equation), you'd run into trouble when you realize that the  $x$s can't be as easily isolated like in the case with linear equations. So we use a different approach, what is called the "completion of squares".
If you are familiar with the method of "completing the squares" (and it isn't very difficult,) you'd know that our goal is to somehow "arrange" the equation in the form $(\text{linear binomial})^2+\text{constant term}$.
When you arrange the equation in this way, isolating the $x$s is very easy.
I'll not show you the entire process of completing the square for our given function but I presume that you are somewhat familiar with it (if not, I suggest you look it up on the internet). The end result of our method will yield a very familiar expression, what we are used to calling as the "quadratic formula". You should end up with something like this:
$$x=\frac{-B}{2\cdot A} \pm \frac{\sqrt{B^2-4\cdot A\cdot C}}{2\cdot A}$$
where $A$, $B$ and $C$ are the coeffients of our function $f(x)$.
The relation above should give you the zeroes of any quadratic function with coefficients $A$, $B$ and $C$ ( Also note that $A$, $B$, $C \in \mathbb R$). Note that this particular relation has many take-aways. First it hints you of the existence of $2$ zeroes (notice the $\pm$ sign in our relation). Second it kind of explains why $ A \ne 0$ (if $A=0$ then the whole relation goes meaningless, for when you divide any thing by $0 $; in our case $2 \times 0  $, the result is undefined.)
The third, and probably the most important one, is that it tells you when $x$ is a Real number or when it is not (i.e when it is a Complex number). Remember that  while $A$, $B$ and $C$ must always be Real numbers, it isn't necessary for $x$ to be Real. It is a well known fact square roots of negative numbers are not Real number, instead, we call them the imaginary numbers $($ and the complex of Real and Imaginary numbers are called the Complex Numbers, usually in the form $a+b\mathbb i $ and $\mathbb i =\sqrt{-1})$.
 So,

The expression under the square root sign, if positive, we have two zeroes that are real (more commonly known as two distinct and Real roots).
If the expression under the square root sign is negative, we will get two zeroes that are Complex Numbers (more commonly known as two distinct but Complex roots).
You might ask what happens if the expression under the square root sign equals $0$? In that case, our relation would reduce down to $$x=\frac{-B}{2\cdot A} \pm 0$$ OR,
$$x=\frac{-B}{2\cdot A}$$ So if the expression under the square root sign equals zero then you'd still get Real values for the zeroes but you'd get just a single "zero" for the equation (more commonly known as repeated and Real roots).

The geometric interpretation of these three cases is also pretty interesting and gives a deeper insight at what is going on (Although your question has already been answered, i suggest you keep reading, I'm almost done :)).  You should know that the zeroes of a function are those values of $x$ which results in $f(x)$ being equal to zero. Or, if you graph the function, It is that point on the graph(or that value for $x$ ), where the function crosses the x-axis. So, what do these three cases imply on the graph then?

If the roots are distinct and real, or, if the discriminant (btw, that is the name for the expression under the square root) is positive, then, the function should cross the x axis twice.Or

Similarly, if the roots are Real and repeated, (i.e the discriminant is zero), the function should have only one point crossing (or in this case touching) the x-axis. Or

Now if the roots are not real, then what? Because there are two distinct roots (but not real), it might be tempting to think that it also crosses the x- axis twice but, good luck finding the point where it actually crosses the x-axis! (where will you find a number $2+3\mathbb i $ on the x axis?). So the next logical deduction could be that it doesn't actually cross the x-axis at all, which is very plausible. And this is exactly what happens. OR,

 And with that I have come to the end of my uber-long answer. (Phew!)

 As far as your question is concerned, If you'd like to know if the zeroes are Real or not, check if $B^2 -4AC$ is positive, negative or zero, the nature of the roots (zeroes) should be apparent.
 I bothered to write down such long an answer because I really wanted you to know what's going on behind the scenes. You might already know this stuff but still, I Hope it helps
Comment: While I mentioned that $A$,$B$ and $C$ must always be real numbers,The OP should know that there can be quadratic functions with complex coefficients but, it is something that you need not bother right now (it is also irrelevant to your question)
Comment: Ridiculously thorough answer! Nice writing.
Comment: Thank you. It means a lot :)
Answer: Depending on the level that you are at, you will find that most quadratics you are given will probably either factorise or have observable roots.
There is a measure of the number of real roots a quadratic has called the discriminant. This essentially comes from completing the square or looking at the quadratic formula.
If your quadratic is $ax^2 + bx + c$ then calculate $b^2 - 4ac$. If this is positive then you have $2$ different real roots. If it is zero then you have one (repeated) real root and. If it is negative then you have no real roots (they are complex numbers).


A negative binomial-ish probability

Question: Suppose you have a biased coin favoring heads with probability $0.5 < p < 1$. Define the $\mathit{net \; win}$ to be the number of heads minus the number of tails. Let $\alpha, \beta \in \left\{1,2,\ldots\right\}$. Define the random variable $X$ where one flips the biased coin indefinitely until the net win reaches either $-\alpha$ or $\beta$. What is the probability of reaching $-\alpha$? How about reaching $\beta$?
I was thinking of using the negative binomial distribution here, however, that does not seem to consider the termination of the trials when it either reaches $-\alpha$ or $\beta$.
Comment: Your `net win` starts at `0`. So do you want $\alpha < 0 < \beta$?
Comment: This is a version of [Gambler's ruin with an unfair coin](https://en.wikipedia.org/wiki/Gambler%27s_ruin#Unfair_coin_flipping)
Comment: Oh yes. That's what I meant. Let me edit it. Thanks
Comment: @doge5ever does my answer cover your queries? Henry's link is also very useful, giving the answer. I suggest that you go through _both_ methods so that you understand best how to approach these types of questions in the future! `:-)`
Comment: Both approach works well in fact! Henry's solution is a quick solution, and I will be needing deeper analysis using your solution. Thanks @SamOT and @Henry!
Answer: Let $X$ be a $p$-biased SRW on $\mathbb Z$, with positive drift. Then the net win $N$ satisfies $N_n = X_n - n$, where $n$ is the number of coin tosses.
You will be able to solve your question using martingales. See, for example, Chapter 2 in here: http://www.statslab.cam.ac.uk/~james/Lectures/ap.pdf. Proposition 3.1.4 there is very related to your question.
Let me outline the general approach. Let $\tau$ be the time you hit $\alpha$ or $\beta$.

Use a martingale based on $X_n$ to find $\mathbb E(\tau)$.
Use a martingale based on $X_n^2$ to find $\Pr(X_\tau = \alpha)$.

@Henry points out in the comments that unfair Gambler's ruin is actually covered on the relevant Wiki page: https://en.wikipedia.org/wiki/Gambler%27s_ruin#Unfair_coin_flipping.

A negative binomial-ish probability


Node/website architecture visualization

Question: I am seeking to build a website which contains quite a lot of information. All this information will be structured in a specific way. As such I am looking for a way to represent this data/articles/nodes visually.
The purpose is to be able to add new articles to an already existing visual structure by simply adding a node and classifying it/linking to existing articles that are already structured/adding taxonomy terms etc.
The visual structure will as such have a changing shape/size. A map of the information presented on the site if you will.
A way to navigate the wealth of information visually.
Does something like this already exist or is there a way to create such a module/program for the site - potentially as a separate site that presents the drupal site?
Thanks,
Answer: I don't believe there is a Drupal specific option, but you can utilize a module like XML Sitemap:

The XML sitemap module creates a sitemap that conforms to the
  sitemaps.org specification. This helps search engines to more
  intelligently crawl a website and keep their results up to date. The
  sitemap created by the module can be automatically submitted to Ask,
  Google, Bing (formerly Windows Live Search), and Yahoo! search
  engines. The module also comes with several submodules that can add
  sitemap links for content, menu items, taxonomy terms, and user
  profiles.

and then use a number of third party online or software based options for visualising xml data.  A quick search in google yielded a number of options for 'visualise sitemap'
Answer: In addition to Geoff's answer (which is an stroke of genius), note that you can link nodes using Entity Reference, and create heirarchies of nodes using Node Hierarchy.
I recommend the former unless you really need to specify which node is parent and which is child, in which case the latter works pretty well.
Answer: There is also the often forgotten book module which is part of Drupal core. It allows for nesting of nodes inside other nodes so you can create a book with chapters. (the guide pages on Drupal.org are an example of this.) depending on the stucture you need this could be useful.

Node/website architecture visualization


c# Cannot access file because it is being used by another process

Question: I am Trying To Write To A File After Creating It. And It Cannot access it, this is my code:
                string[] name = file.Split('.');
                HttpWebRequest FileRequest = (HttpWebRequest)WebRequest.Create(URL + name[0] + ".html");
                FileRequest.UserAgent = "FSL File Getter Agent";

                using (HttpWebResponse response = (HttpWebResponse)FileRequest.GetResponse())
                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    File.Create("C:\\Users\\" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\')[1] + "\\FSL\\" + Item + "\\" + file);
                    File.WriteAllText("C:\\Users\\" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\')[1] + "\\FSL\\" + Item + "\\" + file, reader.ReadToEnd());
                }

This Is The Stack Trace:
The process cannot access the file 'C:\Users\Winksplorer\FSL\TestPRG\main.py' because it is being used by another process.
Stack Trace:
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
   at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
   at System.IO.File.InternalWriteAllText(String path, String contents, Encoding encoding, Boolean checkHost)
   at System.IO.File.WriteAllText(String path, String contents)
   at FSL.Program.GetPKG(String URL, String Item) in Z:\FSL\Program.cs:line 85
   at FSL.Program.Main(String[] args) in Z:\FSL\Program.cs:line 30

Comment: Pro tip: check what methods return before you use them.
Answer: File.Create returns a FileStream for which you are happily ignoring. The result of this action is holding a handle to the file open which will not get disposed in a timely manner. Furthermore, you are then trying to use another method File.WriteAllText to write to that file using a different file handle which results in the error you see.
The solve to this is to use the FileStream you originally created, however even better, just use one of the streams CopyTo Methods
using var stream = response.GetResponseStream();
using var fs = File.Create(...)
stream.CopyTo(fs);

Disclaimer : There are async versions to these methods and many other ways to achieve the same thing. This wasn't tested, and was not meant to be the bastion of perfect code. It's only a tribute... in short, research the methods you use.


Invoke Put Odata Controller Method through Code in C#

Question: I have a Odata controller class in my project, and I need to invoke PUT controller method from other piece of code.
My PUT controller method's declaration looks like this, which accepts two parameters and class object.
public IHttpActionResult Put([FromODataUri] string name, [FromODataUri] string version, Product product)

I can invoke this method through fiddler with this URL, this works fine, now I need to invoke this Put controller method through code.
https://127.0.0.1/odata/ControllerName(name='ProductName',version=1)

The code, I have written so far works fine with Put method and accepting one Odata param from URL, but not sure how to make it work with two parameters.
Container container = new ProductService.Container(baseUri);
container.AttachTo("Products", product);
container.UpdateObject(product);
container.SaveChanges(SaveChangesOptions.ReplaceOnUpdate);

Here, this invokes Put Controller with one parameter, passing parameter value equal to Primary Key but as I have two primary keys and same two parameters accepting Put Controller Method.
How should I invoke Put controller method from C# code?
Answer: Here is a similar sample project https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v3/ODataCompositeKeySample/ There are POST, PATCH methods:
public HttpResponseMessage PutPerson([FromODataUri] string firstName, [FromODataUri] string lastName, Person person)
{
    _repo.UpdateOrAdd(person);

    return Request.CreateResponse(HttpStatusCode.OK);
}

and an example of invoking PATCH:
private static void PatchPerson()
{
    Console.WriteLine("Patch Person");
    Container c = new Container();
    var person = c.People.Where(p => p.FirstName == "Eric" && p.LastName == "Smith").Single();
    person.Age = 9;
    c.UpdateObject(person);
    c.SaveChanges(SaveChangesOptions.PatchOnUpdate);
    Console.WriteLine("\t{0}, {1}'s age is changed to {2}", person.FirstName, person.LastName, person.Age);
    GetPeople();
}

Please make sure there is a composite key in your entity, just the same as:
public class Person
{
    [Key]
    public string FirstName { get; set; }
    [Key]
    public string LastName { get; set; }

    public int Age { get; set; }
}


Modal Bootstrap não funciona

Question: estou tentando usar o modal do template Gentelella, mas quando clico no link, o modal está estático e não consigo colocar informações ou clicar nos botões. Segue código:

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title></title>

    <link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="../vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet">

    <link href="../vendors/nprogress/nprogress.css" rel="stylesheet">

    <link href="../vendors/animate.css/animate.min.css" rel="stylesheet">

    <link href="../vendors/iCheck/skins/flat/green.css" rel="stylesheet">

    <link href="../vendors/bootstrap-progressbar/css/bootstrap-progressbar-3.3.4.min.css" rel="stylesheet">

    <link href="../build/css/custom.min.css" rel="stylesheet">

            <form method="POST" action="validacao_usuario.php">

Sistema

                <input type="text" name="usuario" class="form-control" placeholder="Usuário" required />

                <input type="password" name="senha" class="form-control" placeholder="Senha" required="" />

                 <button class="btn btn-primary" type="submit">Entrar</button>

                  <button type="button" class="btn btn-link" data-toggle="modal" data-target=".bs-example-modal-lg">Esqueceu senha/usuário?</button>

                          <button type="button" class="close" data-dismiss="modal">×
                          </button>

Recuperação da senha/usuário

Informe seu email:

                       <input type="email" id="email" name="email" required="required" class="form-control">

                          <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                          <button type="button" href="recuperacao.php" class="btn btn-primary">Enviar</button>

 -Todos os direitos reservados 2017.

            </form>

Alguém consegue enxergar o erro?
Obrigada!
Answer: Eu entendi mais ou menos o que  você esta querendo fazer, você vai ter que tirar esse modal de dentro do  form  validacao_usuario.php e enviar os dados dele via post para sua pagina recuperacao.php. Desse jeito ai também dará certo, você terá que deixar  assim, em vez de utilizar (button)  colocar  em uma tag (ancora) mais ai você terá recuperar os dados dele via GET. Espero ter ajudado, qualquer duvida pergunta de novo, tentaremos te ajudar da melhor forma possível.
seu código com modificações

<title></title>

<link href="..../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

<link href="../vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet">

<link href="../vendors/nprogress/nprogress.css" rel="stylesheet">

<link href="../vendors/animate.css/animate.min.css" rel="stylesheet">

<link href="../vendors/iCheck/skins/flat/green.css" rel="stylesheet">

<link href="../vendors/bootstrap-progressbar/css/bootstrap-progressbar-3.3.4.min.css" rel="stylesheet">

<link href="../build/css/custom.min.css" rel="stylesheet">

        <form method="POST" action="validacao_usuario.php">

Sistema

            <input type="text" name="usuario" class="form-control" placeholder="Usuário" required />

            <input type="password" name="senha" class="form-control" placeholder="Senha" required="" />

             <button class="btn btn-primary" type="submit">Entrar</button>

              <button type="button" class="btn btn-link" data-toggle="modal" data-target=".bs-example-modal-lg">Esqueceu senha/usuário?</button>

                      <button type="button" class="close" data-dismiss="modal">×
                      </button>

Recuperação da senha/usuário

Informe seu email:

                   <input type="email" id="email" name="email" required="required" class="form-control">

                      <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                      Enviar

 -Todos os direitos reservados 2017.

        </form>

Comment: Muito obrigada pelas sugestões, amigo. Consegui resolver!
Comment: se precisar de mais ajuda é só perguntar.
Answer: Tente retirar a estrutura do Modal onde ele se encontra, e coloque-o no final do body, pra não haver conflito com algum elemento do grid anterior, como até mesmo uma limitação de visualização de camadas por z-index ou renderização. (não conheço o CSS restante).
Geralmente modais sempre são appends no fim do código do elemento. Mas vai da utilização de cada um, porque nesse modelo utilizado, caso tentasse replitar, você usaria vários grids de modal no código. Sugiro que generalize mais para usar menos linguagem de marcação.
Outra coisa, ao invés de utilizar o target, coloque onclick="$('.modal').modal('show') (só por teste mesmo)
Boa sorte
Comment: Obrigada pela informação, amigo! Coloquei toda a Div modal no final do body e funcionou.

Modal Bootstrap não funciona


Finding the tangent vector of a cubesphere using world coordinates

Question: TLDR.:
I'm trying to find the tangent vector of a cubesphere using only world space coordinates.
Background:
A cubesphere is basically just an inflated cube. It is commonly used to project 2D textures onto a sphere due to its comparatively even pixel density. Cubesphere tangent space coordinates (also known as UVs) are generated using the following HLSL code:
<code>// Default Cubemap using if from IG https://www.shadertoy.com/view/ltl3D8
vec2 Cubemap(vec3 uvw)
{
    // intersect cube
    vec3 n = abs(uvw);
    vec3 v = (n.x>n.y && n.x>n.z) ? uvw.xyz:
             (n.y>n.z) ?            uvw.yzx:
                                    uvw.zxy;
    // project into face
    vec2 uv = v.yz/v.x;

    // Cass Everitt's piecewise quadratic warp to even out pixel density
    // https://github.com/casseveritt/projection/blob/master/envmap.h (Ctrl+F pinch)
    vec2 distort = (1.45109572583 - 0.451095725826*abs(uv));
    uv *= distort;

    // rescale to 0-1 range
    return 0.5+0.5*uv;
}
</code>
The tangent vector is used together with the normal and bitangent vectors to translate vectors vetween world space and the tangent space of the mapping.
The normal vector just points straight up from the sphere surface and for a cubesphere and spheres in general is just normalize(uvw). The bitangent is perpendicular to the tangent and normal, so it is calculated as cross(Normal, Tangent).
The tangent is a vector that points in the direction of the tangent coordinates' positive x-axis direction in world space. The bitangent does the same for the y-axis. So if we use a quiver plot to show the vector (1,0) in tangent space, we can see what vector we have to match in world space. Tangent Space Vector (1,0) as blue quiver plot, with white outlines of the cube edges.
There are a few naive solutions:

Use the same function that you used to translate the coordinates into tangent space for the vector. This does not work as the function only takes only the XY axis of the vector for the positive z side, for example, and vectors like (0,0,1) would be 0 for the entire side which is not correct.

Normally one would just generate a mesh of a cubesphere and read out the vertex tangent coordinates (Catlike Coding). While that works well enough, I can't use this method for my application and need to calculate it from scratch using world coordinates. But we can use it to check what our solution should look like. Tangent space (1,0) vector in blue quiver plot, XY component of world space Tangent vector in green quiver plot. While the arrow positions do not align due to different projections, their direction does.

Using a perpendicular vector and normals to generate the tangent like For example for the positive z side of the cubesphere this would be Normalize(cross(Normal, (0,1,0))). Tangent space (1,0) vector in blue quiver plot, XY component of world space Tangent vector in red quiver plot. Notice how the vectors do not point in the same direction.

I also tried approximating the tangent vector ,see code below. This is certainly technically wrong but is quite close. Tangent space (1,0) vector in blue quiver plot, XY component of world space Tangent vector in red quiver plot. Notice how the vectors mostly point in the same direction.

<code>vec3 normal = normalize(UVW);
vec3 tangent = normalize(vec3(abs(0.5(normal.x)-1),
                normal.x*normal.y*normal.z,
                normal.x));
</code>
Final Notes:
I only need the tangent vector for a single side of the cubemap as rotating and flipping it for the other 6 sides is trivial.
I've searched for information on this topic but haven't been able to find anything that specifically addresses my problem. Can anyone help me with this tricky geometry problem?
Answer: I found two solutions. You can either solve it with finite difference or derivatives. I have both implemented.
See here my shadertoy implementation.
And here the python script on how I got to the solutions.


pidof giving inaccurate result

Question: I want to get the pid of a php script:
php /var/www/html/test.php

I have a couple of other php scripts running as well, for instance
php /var/www/html/hello.php
php /var/www/html/world.php

When I run pidof -s -x php /var/www/html/test.php, it randomly gives me the pid of any of the 3 running scripts. I think it's because it's only seeing the php after -x and ignoring the rest. I tried it with quotes and I didn't get any result at all.
pidof -s -x 'php /var/www/html/test.php'

Comment: What you are actually asking pidof to do is to give you a single result (-s), also checking for scripts (-x), of either "php" or "/var/www/html/test.php".  I suspect you are assuming pidof will AND the results, which it doesn't.  Removing "php" from the command line is probably more what you want.
Comment: I tried that and that didn't work either.
Answer: Give this a try:
pgrep -f 'php /var/www/html/test.php'

pidof giving inaccurate result


What is the geometric meaning of $||2z||>||z^2+1||$?

Question: I'm trying to solve the Volkovyski book and I'm having trouble with the following problem :
(Consider $z\in\mathbb{C}$)
Describe the geometric meaning of the following relationship:
$$||2z||>||z^2+1||$$
I already know that $||2z||$ is a circle in the origin with radius equal to 1/2, but what is $||z^2+1||$ ?
If I let $\lambda\in\mathbb{R}^+_0$ then the relation $||z^2+1||=\lambda$ is not always a simple curve, so what is the geometric meaning of $||z^2+1||<||2z||$?
Comment: Just a remark, but $|2z|$ is not a circle, it is just an expression. The relation $|2z|=1$ looks like a circle when you plot it in the complex plane, and for example the relation $|2z| = |2z|$ is the entire plane when you plot it, so it is an important distinction
Comment: Thanks for the insight , @Jean-ClaudeArbaut , I get what you want to convey. When answer downvote is due to question , I have seen some users put that in a comment , which at least gives the thought behind the downvote. Here , there is no feedback at all.
Comment: Yes, thanks for the comment. I was just trying to visualize what could represent the relations between the expressions, and to do so I separated them into two expressions to see how they behaved when equal to some constant.
Comment: You should leave Problem 1 here & make a new Question to cover Problem 2. I will try to make that change , which you can revert if that is not satisfactory.
Comment: Some Downvoter seems to not like my Answer , though it is essentially Correct. No Comment or Constructive feedback was given hence not sure what the Issue is.
Comment: Knowing what $f(x)=C$ and $g(x)=C$ look like is generally not a useful way to understand what $f(x)=g(x)$ looks like.
Comment: Your question should be "What is the locus of points $z  \in \mathbb{C}$ such that $|2z|>|z^2+1|$"
Comment: @Parker Emmerson ; your (erased) answer has a strong "Chat GTP" flavour. What is the point to copy-paste such **completely nonsense** texts ?
Answer: Without having the Volkovyski book , I am not sure what technique has been introduced & what method we have to use.
Here is what I would try :
Consider $z=x+iy$
then we will have $||2z||=\sqrt{(2x)^2+(2y)^2}$
We can calculate $z^2+1$ & then calculate $||z^2+1||$
The given "Equation" can then be written like this :
$\sqrt{(2X)^2+(2Y)^2} = \sqrt{[(X^2-Y^2+1)]^2+(2XY)^2}$
$(2X)^2+(2Y)^2 = [(X^2-Y^2+1)]^2+(2XY)^2$
Algebra can expand the terms & rearrange to make it $f(x,y)g(x,y)=0$ which can then be interpreted.
Plotting is one alternate technique.
Plot that Equation to see that it is 2 Circles :

Plot $(2X)^2+(2Y)^2 < [(X^2-Y^2+1)]^2+(2XY)^2$ :

Plot $(2X)^2+(2Y)^2 > [(X^2-Y^2+1)]^2+(2XY)^2$ :

We can expand the terms & re-arrange to get the 2 Circles , without the Visualizations [[ courtesy of Wolfram Online Tool ! ]] through algebra.
It will be like :
$[(X-A_1)^2+(Y-B_1)^2-C_1^2][(X-A_2)^2+(Y-B_2)^2-C_2^2]=0$
That gives :
A Circle with Center at $(A_1,B_1)$ & radius $C_1$
A Circle with Center at $(A_2,B_2)$ & radius $C_2$
A little bit of algebra gives :
$A_1=0$ , $B_1=+1$ , $C_1=1.5$
$A_2=0$ , $B_2=-1$ , $C_2=1.5$
Geometric Interpretation , in normal English , is that it is the Set of Points which are in Exactly 1 Circle , excluding the Points which are Both Circles & excluding the Points which are in neither Circle.


Xcode how to display array inside array in tableview

Question: In Xcode5 I have application of recipes.
screen1 is list of recipes in a tableview. The recipe are objects in an array at MVC model. at Screen1 when clicking on a row you move to screen2 to see a specific recipe Details.  One of them is Ingredients which I try to display as array (inside array) in UITextView (divided by \n).
I run the app - screen1 is displayed, but when clicking a row the app crashes at: signal SIGABRT.
Can you please advise what is best way to display array of ingredients in the textview?
Thanks in advance.
This is code at DetailsVC.m  (screen2):
-(void)viewWillAppear:(BOOL)animated {

    self.detailName.text = self.presentedRecipe.title;
    self.detailImage.image = [UIImage imageNamed:self.presentedRecipe.imageName];

    NSMutableString *ingredientText = [NSMutableString string];

    for (NSString* ingredient in myRecipeDM.ingredients) {
        [ingredientText appendFormat:@"%@\n", ingredient];
    }
    self.ingTV.text = (NSString*) self.presentedRecipe.ingredients;
}

Answer: Try
NSString *final=[[NSString alloc] init];
for (NSString* ingredient in myRecipeDM.ingredients)
{
    if[ingredientText isEqualToString:""]
    {
      ingredientText=ingredient;
     }
    else
    {
      ingredientText=final;
      ingredientText=[final stringByAppendingFormat:@"%@\n", ingredient];
     }
}

Answer: You can use:
NSString *ingredientstring = @"";
for (NSString* ingredient in myRecipeDM.ingredients)
{
ingredientstring = [NSString stringWithFormat:@"%@\n%@", ingredientstring, ingredient];
}
_ingTV.text = ingredientstring;


How to keep in sync git repository and related htdocs directory?

Question: I use the following set up for my <code>@dev</code> site:
(a) ../git/repository/dev
where I keep version control using git,
and a separate
(b) ../htdocs/dev
that I have an almost exact copy of  git repositor (a) used by the http server
How to make sure git repository (a) is always in sync with http (b) ?
I don't want to version control (b) directly from various reasons.
Answer: use the "post-update" hook in the /hooks directory provided in your .git directory to push a copy (sans -gitignore- the files not needed) each time you make git commits to your dev files


Is there a way to calculate R-squared in OLS without computing the coefficients?

Question: The background of my question is that for e.g. the White heteroskedasticity test or the Breusch-Godfrey (LM) autocorrelation test, we are generally only interested in the R-squared of the "auxiliary" regression. However, the only way of computing said R-squared that I am aware of involves deriving the coefficients etc. This can potentially consume a lot of time due to a large number of regressors and thus a large dimension of the matrix that needs to be inverted (in the case of the White test, regressing the squared residuals on the independent variables, their squares and cross-products - the number of regressors is thus a quadratic function of the number of independent variables).
Is there an "alternative way" to calculate (or perhaps approximate) R-squared?
(I know that the problem could be avoided by using different tests - e.g. Breusch-Pagan instead of White for heteroskedasticity, Durbin-Watson instead of Breusch-Godfrey. However, I am interested in this question both for the fun of it and because the mentioned alternative tests can be inferior to the ones mentioned at the beginning.)
Comment: My question was based on the assumptions that (i) calculating R-squared required computing the coefficients and that (ii) computing the coefficients required inverting the $X'X$ matrix, which can be computationally expensive. As the great answer by @gordonsmyth explains, the former assumption was correct but the latter was not. I am leaving the question untouched because I hope that my learning journey will be useful to others who were taught the theory of econometrics but not how to best make it happen on a computer.
Answer: No, given a multiple regression, there is no way to compute R-squared while avoiding the bulk of the other computations. You can certainly avoid computing the coefficients themselves, but the main work of the computation still needs to be done.
Note however that no matrix is ever inverted during a linear regression if the computation is done properly. There are many answers on this site that explain that, for example Residual Sum of squares in Weighted regression
Here is what might be the minimum possible computation to get R-square. You have to somehow orthogonalize $y$ for the regression covariates, and the QR decomposition is the most-used method of doing that. Let's assume we have a $y$ vector of 10 observations:
<code>    > y <- rnorm(10)
</code>
and an $X$ matrix with 2 predictors:
<code>    > x1 <- rnorm(10)
    > x2 <- rnorm(10)
</code>
The quickest way to get R-square would be like this.
First mean correct:
<code>    > y.c <- y-mean(y)
    > x1.c <- x1-mean(x1)
    > x2.c <- x2-mean(x2)
</code>
Then compute a QR matrix decomposition for $X$ and $y$ together:
<code>    > QR <- qr( cbind(x1.c, x2.c, y.c) )
</code>
Then R-squared is one minus the proportion of the sum of squares that still remains:
<code>    > Rsquared <- 1 - QR$qr[3,3]^2 / sum(y.c^2)
    > Rsquared
          y.c
    0.3266491
</code>
We can confirm that this is correct:
<code>    > fit <- lm(y ~ x1+x2)
    > summary(fit)

    Call:
    lm(formula = y ~ x1 + x2)

    Residuals:
         Min       1Q   Median       3Q      Max
    -2.44213 -0.47947  0.08121  0.89085  1.54395

    Coefficients:
                Estimate Std. Error t value Pr(>|t|)
    (Intercept)   0.5032     0.4761   1.057    0.326
    x1            0.5330     0.4118   1.294    0.237
    x2           -0.6153     0.4215  -1.460    0.188

    Residual standard error: 1.323 on 7 degrees of freedom
    Multiple R-squared:  0.3266,    Adjusted R-squared:  0.1343
    F-statistic: 1.698 on 2 and 7 DF,  p-value: 0.2505
</code>
By the way, if you don't want to bother de-meaning the x-variables, then you can compute the QR decomposition using the entire design matrix including the intercept:
<code>    > QR <- qr( cbind(1, x1, x2, y) )
    > Rsquared <- 1 - QR$qr[4,4]^2 / sum(y.c^2)
</code>
This gives the same result because the QR decomposition orthogonalizes each column in succession with respect to the previous columns and de-meaning simply orthogonalizes all the columns with respect to the constant vector.
Comment: @Candamir You can either de-mean or you can include the intercept in the matrix for the QR-decomposition by qr( cbind(1, x1, x2, y) ). Either approach gives the same result. I chose to de-mean just because it reduces the QR decomposition by one column.
Comment: Thanks for the great answer! One question though: Why is it necessary to de-mean the column vectors? I couldn't find any de-meaning going on in the other answers on CV that deal with solving OLS with the QR decomposition (see https://stats.stackexchange.com/a/160025/182174 and https://stats.stackexchange.com/a/154514/182174). Obviously `y` eventually needs to be de-meaned for the denominator in the R-squared expression, but what about `X`? I checked in R and it _is_ necessary to get the correct $R^2$, but I can't fully follow why / why nobody else talks about it.
Answer: No, because the derivation for an OLS regression is the minimization problem for the sum of squared regression residuals.  Since R-squared is monotonic w.r.t. SS-reg, the optimization problem can be rewritten as the maximization of R-sqaured and the Lagrangian will yield the same first orders.


Enviar variável para Command à partir do Controller Laravel

Question: Hoje eu chamo um command pelo controler perfeitamente, mas gostaria de enviar variáveis também. No controller, chamo o command desse jeito:
\Artisan::call('syncustomer:sav');

O atributo name do command atual:
protected $name = 'syncustomer:sav';

Na documentação eu vi que poderia passar as variáveis da seguinte maneira:
\Artisan::call('syncustomer:sav', ['firstname.lastname@example.com']);

Assim, o name do command ficaria assim:
protected $name = 'syncustomer:sav {data}';

O controller não mostra erro, mas quando tento pegar essa variável no handle() dá erro dizendo que não existe o argumento data:
public function handle(){
    $email = $this->argument('data');
    DB::table('customer')
       ->where('email', 'email@example.com')
       ->update(array('email' => $email));
}

The data argument does not exist.

Alguém pode me ajudar?
Comment: Já tentou usar array associtativo? `['data' => 'firstname.lastname@example.com']`
Comment: Descobri como fazer, vou colocar como resposta
Comment: Já sim, dá o mesmo problema
Comment: Que estranho, porque na doc ele tá fazendo assim: https://laravel.com/docs/5.3/artisan#programmatically-executing-commands
Answer: Consegui descobrir
a chamada para o command pode ser feito enviando as variáveis (argumentos) como um array associativo, como sugerido pelo JuniorNunes
\Artisan::call('syncustomer:sav', array('data' => $data, 'customer' => $customer));

Agora, para criar esses argumentos no command, eu preciso criar dois métodos para mapeamento
protected function getArguments()
{
    return [
        ['data', InputArgument::REQUIRED,
            'An example argument.'],
        ['customer', InputArgument::REQUIRED,
            'An example argument.']
    ];
}

protected function getOptions()
{
    return [
        ['data', null, InputOption::VALUE_REQUIRED,
            'An example option.', null],
        ['customer', null, InputOption::VALUE_REQUIRED,
            'An example option.', null],
    ];
}

Dentro do handle() eu busquei os argumentos com o seguinte método:
$data = $this->argument('data');
$customer = $this->argument('customer');

Desse jeito consegui recuperar os argumentos enviados.


Multiple forms on single page?

Question: Is it possible to put multiple forms on a single page?
I am trying to make a coupon offer page. I wanted to have two forms for two different offers on each side of a page. Each form has a text field for the coupon code and its own submit button. The first form works okay; however the second form's hidden values seem to be overridden by the first form's.
I'm using hook_alter to alter the second form to make it different, but it still has the same form_id as the first. Is this what's causing my problems, or do I need to look/think somewhere else?
The two forms have the same values for "form_id" and "form_token," but different values for "form_build_id."
Answer: If you want to add the same form multiple times, you need to implement hook_forms(). See node_forms() for an example.
This allows to use different form_id's, which all point to the same form builder function. For example, you can use yourmodule_some_form_$i and then use hook_forms() to point these to yourmodule_some_form.
See http://www.mohitsharma.net/content/how-show-same-form-multiple-time-page for an example
Comment: The OP is talking of using two forms on the same page; using `hook_forms()` doesn't automatically solve this. If you simple use the same form twice on the same page, you still have the problem of having the same form field repeated twice.
Comment: Not sure if I follow you. Not sure about 6.x right now, but at leat Drupal 7 makes sure that that there are no duplicate id's, so there shouldn't be a problem when having the same form fields multiple times on the same page?
Comment: `hook_forms()` is not used to have two forms with the same form fields in the same page; it is used to allow to have a single form builder for different form IDs.
Comment: You can use hook_forms() for exactly this. See for example http://www.mohitsharma.net/content/how-show-same-form-multiple-time-page
Comment: The example given in that article is not practical; the form doesn't even have a submission button, and for such form I would not use `hook_forms()`. The OP is then altering one of the two forms.
Answer: You can have more than one form in the same page; see what done by node_admin_content(), which uses the following code:
function node_admin_content($form_state) {
  if (isset($form_state['values']['operation']) && $form_state['values']['operation'] == 'delete') {
    return node_multiple_delete_confirm($form_state, array_filter($form_state['values']['nodes']));
  }
  $form = node_filter_form();

  $form['#theme'] = 'node_filter_form';
  $form['admin']  = node_admin_nodes();

  return $form;
}

Leaving out the first IF-statement, the function is adding two different forms that have their own submission handlers.
The problem is with the form fields that are repeated twice. The following array structure would create problems when the form array is flattened, as there would be two "coupon" fields.
$form['first form']['coupon'] = array(
  '#type' => 'textfield',
  '#title' => t('Coupon'),
  '#default_value' => variable_get('mymodule_coupon'),
  '#size' => 60,
  '#maxlength' => 128,
  '#required' => TRUE,
);

$form['second form']['coupon'] = array(
  '#type' => 'textfield',
  '#title' => t('Coupon'),
  '#default_value' => variable_get('mymodule_coupon'),
  '#size' => 60,
  '#maxlength' => 128,
  '#required' => TRUE,
);

Without to see the code being used, I could think that using a page callback that calls drupal_get_form() is probably the easier way, in your case.
$output = drupal_get_form("form identifier") . drupal_get_form("form identifier");

I tried using the following code in Drupal 6.
module_load_include('inc', 'path', 'path.admin');
$output = drupal_get_form('path_admin_form') . drupal_get_form('path_admin_form');

The content of $output for the two form was the following one (I removed the output for the single form fields).
<form action="/dr61/devel/php"  accept-charset="UTF-8" method="post" id="path-admin-form-1">

<input type="submit" name="op" id="edit-submit" value="Create new alias"  class="form-submit" />
<input type="hidden" name="form_build_id" id="form-4eb9304baac34f292901ca23d925ff03" value="form-4eb9304baac34f292901ca23d925ff03"  />
<input type="hidden" name="form_token" id="edit-path-admin-form-form-token" value="cd429a06b84e381eb82ef04cd5033eeb"  />
<input type="hidden" name="form_id" id="edit-path-admin-form" value="path_admin_form"  />

<form action="/dr61/devel/php"  accept-charset="UTF-8" method="post" id="path-admin-form-1">

<input type="submit" name="op" id="edit-submit-1" value="Create new alias"  class="form-submit" />
<input type="hidden" name="form_build_id" id="form-fb363c7ca6d88f71d98e86f8a69b0379" value="form-fb363c7ca6d88f71d98e86f8a69b0379"  />
<input type="hidden" name="form_token" id="edit-path-admin-form-form-token-1" value="cd429a06b84e381eb82ef04cd5033eeb"  />
<input type="hidden" name="form_id" id="edit-path-admin-form-1" value="path_admin_form"  />

There is not a conflict between the HTML ID assigned to the same form field, and the value for "form_build_id" (or "form_token") is different in the two forms.
The implementation of hook_form_alter() used to alter the form should be able to understand in which case to alter the form, or both the forms would show the same fields.
From the point of view of the user experience, I am not sure that showing two different forms with their own submission buttons is the best way to do what you are trying to achieve.
I would think that using a form that shows different fields basing on the values set for other fields would be better. For example, the form could have a selector for the type of the coupon, and would shown different form fields basing on the coupon type selected.
Comment: It's not that simple when you want to re-use the *same* form.

Multiple forms on single page?


Unhandled Exception: Bad state: Cannot add new events after calling close - Between screens

Question: I have the next architecture :
ScreenA > ScreenB

/// Here i navigate from ScreenA to ScreenB, so here i create the BlocB that i'm going to use
BlocProvider<BlocB>(
  create: (context) => BlocB(),
  child: const ScreenB(),
),

ScreenB > ScreenC

await Navigator.of(context).pushReplacementNamed(
  PageNames.screenC,
  arguments: context.read<BlocB>(),
);

/// Here i navigate from ScreenB to ScreenC, so i re-value the BlocB
BlocProvider<BlocB>.value(
  value: (args as BlocB),
  child: const ScreenC(),
),

Here i do the same logic until ScreenD where i'm going to use a BlocListener and do the add event from the BlocB
ScreenC > ScreenD

await Navigator.pushNamed(
  context,
  PageNames.screenD,
  arguments: context.read<BlocB>(),
);

/// Here i navigate from ScreenC to ScreenD, so i re-value the BlocB
BlocProvider<BlocB>.value(
  value: (args as BlocB),
  child: const ScreenD(),
),

The BlocF listener
return BlocListener<BlocF, BlocFState>(
  listener: (context, state) {
     if (state.status.isSuccess) {
        context.read<BlocB>().add(someEvent()); // error
     }
  },
  child: child...

Now, i'm going to use a add event from another Bloc (BlocF for example), now send a status and with its listener, i want to add event from BlocB, but a i have the error :
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Bad state: Cannot add new events after calling close
I don't know why if i pass through the screens my Bloc
Comment: why do you always recreate a provider? You can also pass the bloc instance as an argument and use it directly
Comment: I only create it once, in the ScreenB, i only pass it as a argument with value, or value is also create a bloc ?
Answer: The error message suggests that the BlocB instance being used in the BlocListener of ScreenF is no longer valid. This can happen if the BlocB instance is closed or disposed of when navigating away from ScreenA, and then trying to use it again in ScreenD.
Possible solutions:

Ensure that the BlocB instance is not closed or disposed of when navigating away from ScreenA by using a BlocProvider that is above the entire navigation stack and not just within the individual screens. This way the same BlocB instance is always available throughout the navigation stack.
Pass the BlocB instance as a constructor argument to the next screen, rather than relying on BlocProvider.value to re-create it.
Comment: But idk when my BlocB is disposed or close, because i send it in every argument, idk if it's the Navigator or what
Comment: What is weird, is that in the ScreenD i use a BlocSelector of BlocB and it works !


How come /bin/rm -rf /backups/hourly.5/ takes forever on a backup server?

Question: They're simply hardlinks so the files shouldn't actually even be deleted.
What options do I have? It even seems to take quite some load. I don't see how deleting 30.000 hard-links should take more than a minute, let alone a full hour.
I use rsnapshot,  centos and an ext3 file system.
Comment: I am also a rsnapshot user and deletes can take a looong time.
Answer: It may be that the dir_index feature is not enabled for the filesystem. Using debugfs will allow you to verify if enabled and set it if not.
Comment: `tune2fs` may be a more appropriate tool for end-users than `debugfs`.
Answer: In order to delete all those files it must traverse the directory tree, and go down into the whole lot, deleting each files & directory one by one. This can take a while.
Sometimes the choice of filesystem can matter. Some filesystems can take a long time to delete lots of little files, some are good at this.


Cluster Data based on Distribution

Question: I have a list of diseases for my research. For each disease, I have a list of ages for the diseases. "Breast Carcinoma" may be a list of [1,2,2,3,4,5,5,5,5,5] while "Adrenal Cortex Neoplasms" maybe be a different list with a thousand elements, BUT with the same general shape in a bincount (high number of 5s, a few 2s). I would like to stratify these diseases based on the shape of the bincount distributions. I am quite new to machine learning, and I honestly have no clue as to how I can begin. However, if you can give me a general approach that I can research more in detail, then I could code a python algorithm for what I wish for. By stratification, I imply a clustering of the data using the distributions.
Thank you for taking the time to help a beginner!
Comment: How do you expect these ages to vary? Is there a maximum age? For example, would it be more appropriate to model the age distribution for each disease as a multinomial or a poisson? My first thought would be to use some kind of dirichlet process clustering on the diseases with respect to the age distribution, but that may be too involved if this is supposed to be a quick task?
Answer: I would use a finite mixture model to cluster the histograms. I do not know of any implementations of finite mixture modeling in Python, but there must be. Alternatively, you could do this in R using the mclust package. The setup is to first bin the data by age group. Then you feed the bin data as rows into the Mclust() function. This function fits a series of finite mixture models with varying number of clusters, and with varying parameters governing the characteristics of the covariance matrix (which in turn governs the orientation, shape, size, and variance thereof across the clusters). It computes the BIC for each of these models. Due to the Mclust computes BIC, higher values of BIC are preferable. So you will look for the model with the highest BIC. Also be sure to check the BIC profile to make sure that the model with highest BIC has higher enough BIC (says, at least a difference of two in BIC from the next strongest model) to make all other models ignorable, or if you should consider other models. Also make sure that the model with highest BIC doesn't just have highest BIC because it is a boundary of the number of clusters considered. I also recommend plotting the data by cluster. Here is an example from my own research, where we clustered Normalized Difference Vegetation Index data by geographic-pixel-year.
Answer: Non-negative matrix factorisation seems suited to this kind of problem; alternatively, give Random Forests a go, but I generally use R and am not sure if Python implementations do pattern discovery (clustering).
The matrices would be tumour type along one dimension and the percentage of cases that fall into a particular age group on the other - if a particular age isn't represented in a tumour you need to set the count of that bin to 0.
To use an example
Age_Bin(Features)        BRCA    ACC    Colorectal Cancer  Kidney Cancer
30-40                     8        0       24                10
40-50                     54      20       35                30
50-60                     24      35       35                40

et cetera. NNMF will then attempt to split the tumour types into clusters based on features defined by age bins; so, to apply the method, a good starting point would be to identify all bins represented in the dataset, set counts to 0 for those tumour types that have no representation in a bin, and then apply the algorithm to find clusters; as has been done here, to use an example...
http://gdac.broadinstitute.org/runs/analyses__2014_04_16/reports/cancer/HNSC/miRseq_Mature_Clustering_CNMF/nozzle.html
The methods section in that report explains how to select the optimal number of clusters et cetera.
Additionally - here is a package for NNMF using Python should you be interested http://nimfa.biolab.si/
Comment: Could you flesh out some of the essential details? In particular, to what matrix do you refer and how would it be computed from the kinds of data described in the question?
Comment: I agree. I am a little confused as to how I would go about doing this from my limited knowledge of clustering

Cluster Data based on Distribution


url rewrite to make generated thumnails cache like static, a syntax question

Question: this is a pain in the ass-problem!! Given: most proxies, do not cache resources with a "?" in their URL even if a Cache-control: public header is present in the response. To enable proxy caching for these resources, i have removed query strings from references to static resources, at the expence of very ugly apache regex code!*
Part 1 DONE  with clues from two geniuses Dennis Williamson & Mark Henderson
Part 2 HERE  this question covers part II: making the code  elegant and less tidious
PREVIOUSLY HAD

NOW WORKING

AT THE COST OF THIS UN-ELEGANT CODE
# Rewrite imgcpu?src= thumbnail maker to nice static urls
RewriteCond %{REQUEST_URI} ^IMG.*$
RewriteRule ^IMG-(.+)_w(.+)_h(.+)_c(.+)_f(.+)_q(.+).jpg$ imgcpu\?src=$1\.jpg&w=$2&h=$3&c=$4&f=$5&q=$6 [L]
RewriteRule ^IMG-(.+)_w(.+)_h(.+)_c(.+)_f(.+).jpg$ imgcpu\?src=$1\.jpg&w=$2&h=$3&c=$4&f=$5 [L]
RewriteRule ^IMG-(.+)_w(.+)_h(.+)_c(.+)_q(.+).jpg$ imgcpu\?src=$1\.jpg&w=$2&h=$3&c=$4&q=$5 [L]
RewriteRule ^IMG-(.+)_w(.+)_h(.+)_c(.+).jpg$ imgcpu\?src=$1\.jpg&w=$2&h=$3&c=$4 [L]
RewriteRule ^IMG-(.+)_w(.+)_h(.+)_f(.+).jpg$ imgcpu\?src=$1\.jpg&w=$2&h=$3&f=$4 [L]
RewriteRule ^IMG-(.+)_w(.+)_h(.+)_q(.+).jpg$ imgcpu\?src=$1\.jpg&w=$2&h=$3&q=$4 [L]
RewriteRule ^IMG-(.+)_w(.+)_h(.+).jpg$ imgcpu\?src=$1\.jpg&w=$2&h=$3 [L]
RewriteRule ^IMG-(.+)_w(.+).jpg$ imgcpu\?src=$1\.jpg&w=$2 [L]
RewriteRule ^IMG-(.+)_h(.+).jpg$ imgcpu\?src=$1\.jpg&h=$3 [L]
+ many many other combinations etcettera!

notes: 1) imgcpu.php?src= can be modified if needed. 2) images will always be in one folder deep, never deeper 3) all files will end with .jpg after wich the delimiters start
IMG-folder1/some_file_w100_h200.jpg    (nice static .jpg url)
imgcpu?src=folder1/some_file.jpg&w=100&h=200  (ugly file url)
Comment: I'm late to the party here, but can we modify imgcpu?  If so, then the right thing to do would be to move the processing into imgcpu where you can execute loops and do other nice things, eg `RewriteRule ^IMG-(.+)$ imgcpu\?parseme=$1 [L]`
Comment: Hello! Change imgcpu ??? you mean in terms of its name or content? sure can do!  p.s. now both work: `imgcpu.php?src= as well as imgcpu?src=`
Answer: Since imgcpu[.php] can be changed, here's my answer for cleaning this up even though it's going to undo a lot of that work you've done
Within a program you can loop over all of the possible attributes and extract whichever ones are present (in any order!).  You can replace all of those rules with a single rule:
RewriteRule ^IMG-(.*)$ imgcpu\?parse=$1 [L]

and then in the imgcpu script, you'd have "parse" as a variable containing folder1/some_funny_kitty_w3500_h10_cp_q90.jpg.  Remove the extension from the end, the folder and file name from the beginning, and then you can loop through the various parameters and extract them from the string.  Something like (PHP, but the concept can be done in any language.  You might even save a few ms by doing it without regexes):
$values["q"]=50; // Set some defaults?
foreach (array("h","w","q","c","f") as $param) {
   if (preg_match("/_${param}([^_]+)/",$_REQUEST["parse"],$result)) {
     $values[$param]=$result[1];
   }
}

At the end $values["h"] would have the height.  This would be a ton easier to maintain if you ever want to add new parameters.  You'd need a little work to figure out what you're supposed to do with "my_w2000_desktop_w200_h100.jpg"  (or worse: "my_w2000_desktop_h100.jpg", or even worse "desktop_for_w2000_h100.jpg") but if you ban people from having double underscores in filenames, you could use double underscores to separate the filename from the options (eg "my_w2000_desktop__h100.jpg") and split the string there (note that the regexes above require that each option start with the _ character)
Easier Option
If you can accept not having the parameters encoded in the filename itself (this could lead to everyone having images of completely different sizes all called "some_funny_kitty.jpg") then parsing can be made trivial.  This would use a URL like http://example.com/IMG/w200/h100/folder1/my_w2000_desktop.jpg.  Remove the "-" from the RewriteRule (just ^IMG(.*)$, and change the parsing in PHP:
$parts=explode("/",$_REQUEST["parse"]);
$filename=array_pop($parts);
$folder=array_pop($parts);
foreach ($parts as $field) {
  $param=substr($field,0,1);
  $setting=substr($field,1); // assuming settings are always one letter followed by value
  $values[$param]=$setting;
}

If that is acceptable, you may be able to eliminate mod_rewrite entirely: Use URLs of the form
http://example.com/imgcpu/w200/h100/folder1/my_w2000_desktop.jpg

and Apache will execute imgcpu with the PATH_INFO environment variable set to /w200/h100/folder1/my_w2000_desktop.jpg ($_SERVER["PATH_INFO"] in PHP).  This works fine for me but I've seen some posts complaining that in certain environments PATH_INFO is broken.
Comment: Dear DerfK! Astoungly clever as well as Creative options to solve my problem, from the php point of view. I will give your optiona s try! meanwhile the easiest would be (since as you said we are so far with the apache rewrite method) to fix that, but i will give both a try and check back soon here!