Views- Show a table of users with each column indicating whether or not a user has a role

Question: I am using Views Data Export to get data on my Drupal users into Excel.  My site has a large number of roles (Roles A - Z), and some of these are important for user statistics.
The view I use for data export is a table of fields.  I added Roles as follows:

This gives me something like RoleA, RoleC, RoleD, RoleI for each user.  This sort of data is difficult to manipulate in Excel.
What I would like to do instead is to have a column in the table for each important role that has 1 if the user has the role, or 0 if the user does not have the role.
In other words, my table looks like this now:

But I want it to look like this in Views:
Comment: Are your roles fixed? You could accomplish this by brute force using a custom views field template and adding a field for each role to your view. This isn't automatically scalable though.
Comment: @AdamBalsam The roles have a decent probability of changing in the future.
Answer: Here's a solution using a simple module and a custom field template.
Overview
The view (obviously of the User Table) should only contain one field: User: Name. All of the other Role columns are generated by implementing HOOK_views_pre_view() with a loop for each defined role. The module also defines a custom function that compares the original output (comma-separated list of roles) and returns true if the list contains the current column's role.
The custom views field template simply calls the custom function for each column that corresponds to a role.
This solution will automatically scale if you add/delete roles and adjust if you rename/reorder roles etc.
Module File
You'll obviously need an info file too. I chose to name the module views_urt (User Role Table) - but you can name it whatever you want or include these functions in an existing custom module if you choose.
<?php
/**
 * Implements HOOK_views_pre_view().
 *
 * Adds a field to the User Roles view for each role defined.
 */
function views_urt_views_pre_view(&$view) {
  if ($view->name == 'user_roles') {
    $roles = views_urt_roles();
    $count = count($roles);
    for($i=0;$i<$count;$i++) {
      $view->display['default']->handler->options['fields']['rid_' . $i]['id'] = 'rid_' . $i;
      $view->display['default']->handler->options['fields']['rid_' . $i]['table'] = 'users_roles';
      $view->display['default']->handler->options['fields']['rid_' . $i]['field'] = 'rid';
      $view->display['default']->handler->options['fields']['rid_' . $i]['label'] = $roles[$i];

    }
  }
}

/**
 * Determines if a comma-seperated list of roles contains the role of the
 * current column.
 *
 * @param $pos integer
 *   The column corresponding to the $field->position value in the view.
 * @param $user_roles string
 *   Comma seperated list of Roles (haystack)
 * @return bool
 */
function views_urt_has_role($pos, $user_roles) {
  $pos = ($pos -1);
  $user_roles = explode(',', $user_roles);
  $defined_roles = views_urt_roles();
  foreach ($user_roles as $user_role) {
    if (trim($user_role) == $defined_roles[$pos]) {
      return TRUE;
    }
  }
  return FALSE;
}

/**
 * Helper function that returns an array of roles exluding "Anonymous" and
 * "Authenticated" user.
 *
 * @return array
 *   An array of roles.
 */
function views_urt_roles() {
  $roles = user_roles();
  array_shift($roles);
  array_shift($roles);
  return $roles;
}

Views Field Template File
This template should be picked up by all of the fields in this view for all of the displays. So, since my view is named user_roles, this template is named views-view-field--user-roles.tpl.php.
<?php
if ($field->field_alias == 'users_name') {
  print $output;
}
else {
  // We're assuming that this view only has one field (User: Name). All other
  // fields are generated by the HOOK_views_pre_view() function in the
  // `views_urt.module` and those should be passed through the
  // `views_urt_has_role` function which determines if the $output
  // (comma-seperated roles per user) contains the column role.
  print views_urt_has_role($field->position, $output);
}
?>

Sample Output
Comment: Thanks, this did the trick.  I have it all working now.  A couple notes: 1) I couldn't figure out why the template wasn't working and I realized that was because I had put the template in the site theme folder, not the admin theme folder, and this is an admin view.  2) I had several other fields that I needed to add, so I needed to customize the code a little bit (changing the value of `$i`, etc.) but I was able to quickly develop a working view based on your code.  Many thanks!
Answer: I think another option is to build a custom view mode. You can implement hook_entity_info_alter:
function MYMODULE_entity_info_alter(&$entity_info) {
     $entity_info['user']['view modes']['VIEW_MODE_NAME'] = array(
        'label' => t('Display user relation to existing roles'),
        'custom settings' => TRUE,
      );
    }

Then you can attach your theme function:
function MYMODULE__view($entity, $type, $view_mode, $langcode){
  if ($enitity == 'user' && $view_mode == 'VIEW_MODE_NAME') {
   // add some additional variables for template
    $node->content['#theme'] = 'VIEW_MODE_NAME_view';
  }
}

and in your theme function VIEW_MODE_NAME_view:
   function  VIEW_MODE_NAME_view_theme(){
     // get all role and display the entity and
     //its roles the way you described
    }

Once you have your view mode working you can use it in views (any view) as well as any other place where the entity is rendered.


Google Cloud Endpoints Framework - EndpointServlet ClassNotFoundException

Question: I'm migrating from Google Cloud Endpoints(v1) to Google Cloud Endpoints Framework(v2).  I'm using Java standard environment on App Engine.  Also using the App Engine gradle plugin and the Gradle plugin for appengine and endpoints framework.
My project will compile and deploy, however it will deploy to what appears to be a staging version (version name is date + time despite being set in appengine-web.xml).
Then once hitting the endpoint I get the following exception:
java.lang.ClassNotFoundException: com.google.api.server.spi.EndpointServlet
    at com.google.appengine.runtime.Request.process-4c1b66acdf400e18(Request.java)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:375)
    at org.mortbay.util.Loader.loadClass(Loader.java:91)
    at org.mortbay.util.Loader.loadClass(Loader.java:71)
    at org.mortbay.jetty.servlet.Holder.doStart(Holder.java:73)

javax.servlet.ServletContext log: unavailable
javax.servlet.UnavailableException: com.google.api.server.spi.EndpointServlet
    at org.mortbay.jetty.servlet.Holder.doStart(Holder.java:79)
    at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:242)

I've followed the migration guides and updated my web.xml and appengine-web.xml to reflect the new classes.  Any help would be great!
Comment: Please post your gradle file.
Answer: By looking at the exception you pasted, it seems like you made a typo in your web.xml: you wrote com.google.api.server.spi.EndpointServlet instead of com.google.api.server.spi.EndpointsServlet.


Two tensors are on the same device, but I get the error: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu

Question: I have:
def loss_fn(self, pred, truth):
    truth_flat = torch.reshape(truth, (truth.size(0),-1)).to(truth.device)
    pred_flat = torch.reshape(pred, (pred.size(0),-1)).to(pred.device)

    stoi_loss = NegSTOILoss(sample_rate=16000)(pred_flat, truth_flat)
    print('truth', truth.size(), truth_flat.size(), stoi_loss)

    return torch.nn.MSELoss()(pred, truth)

As you can see, I'm making sure that it's on the same device, but I still get the error:
Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu

Any ideas?
Answer: You are assigning to two different devices, truth.device and pred.device.
Comment: @Shamoon: And yet PyTorch clearly thinks otherwise. Only one of you is right......
Comment: Those are on the same device


$L^{2}(\mathbb{R},X)$ not Hilbert if $X$ is $C^{*}$-algebra?

Question: If $X$ is a Hilbert space, then $L^{2}(\mathbb{R},X)$ is a Hilbert space with the inner product $\langle f,g\rangle:=\int_{\mathbb{R}}\langle f(s),g(s)\rangle_{X}ds$. Suppose on the other hand that $X$ is an arbitrary $C^{*}$-algebra and define the function $\{\cdot|\cdot\}:L^{2}(\mathbb{R},X)\times L^{2}(\mathbb{R},X)\to\mathbb{R}$ by
\begin{equation*} \{f|g\}:=\int_{\mathbb{R}}\|f(s)g^{*}(s)\|_{X}ds \end{equation*}
where this function is well-defined by Holder's inequality. There are also several nice properties:

$\{f|g\}\geq 0$ and $\{f|g\}=0$ iff $\{s\in\mathbb{R} \mid f(s)g^{*}(s)\neq 0\}$ is Lebesgue-null
$\{f|g\}=\int_{\mathbb{R}}\|f(s)g^{*}(s)\|_{X}ds=\int_{\mathbb{R}}\|g(s)f^{*}(s)\|_{X}ds=\{g|f\}$
$\{\lambda f|g\}=|\lambda|\{f|g\}$ and $\{(f+g)|h\}\leq \{f|h\}+\{g|h\}$

and, in addition, $\{f|f\}=\int_{\mathbb{R}}\|f(s)f^{*}(s)\|_{X}ds=\int_{\mathbb{R}}\|f(s)\|_{X}^{2}ds=\|f\|^{2}_{L^{2}(\mathbb{R},X)}$ by means of the $C^{*}$ condition on $\|\cdot\|_{X}$. This appears to lead to the following ``proposition:"
``Propostiion:" $L^{2}(\mathbb{R},X)$ is not a Hilbert space.
Proof: Suppose for a contradiction that there exists an inner product on $L^{2}(\mathbb{R},X)$ such that $\|f\|^{2}=\langle f,f\rangle$ for every $f\in L^{2}(\mathbb{R},X)$. Then,
\begin{align*} \langle f,g \rangle &=\frac{1}{4}\left(\|f+g\|^{2}-\|f-g\|^{2}+i\|if-g\|^{2}-i\|if+g\|^{2}\right) \\ &=\frac{1}{4}\left(\|f+g\|^{2}+\|f-g\|^{2}+i\{if-g|if-g\}-i\{if+g|if+g\}\right) \\ &=\frac{1}{4}\left(\|f+g\|^{2}+\|f-g\|^{2}+i\{f-g|f-g\}-i\{f+g|f+g\} \right) \\ &=\frac{1-i}{4}\|f+g\|^{2}+\frac{1+i}{4}\|f-g\|^{2}\end{align*}
and this obtains $\|f\|^{2}=(1-i)\|f\|^{2}$ by taking $g=f$ so the proof is complete.
My problem is this: I seem to have proved that $L^{2}(\mathbb{R},X)$ is not a Hilbert space whenever $X$ is an arbitrary $C^{*}$-algebra, but this cannot be true - there are $C^{*}$-algebras that are also Hilbert spaces (consider $X=\mathbb{C}$ where complex conjugation is the involution). So where is the issue with the above construction? Have I implicitly assumed something and/or missed something about the mapping $\{\cdot|\cdot\}$?
Possible solution: I just came across the Gelfand-Naimark-Segal theorem which states that every $C^{*}$-algebra is isometrically isomorphic to a $C^{*}$-sub-algebra of $\mathcal{B}(H)$ for some Hilbert space $H$. In particular, I have implicitly assumed above that $X$ (modulo an isometric isomorphism) is a $C^{*}$-sub-algebra of $\mathcal{B}(H)$ for some $H$ with $\dim(H)>1$, where there are least two projections $P,Q\in X$ onto orthogonal vectors in $H$. See this MSE post to see why this ensures $X$ is not Hilbert.
Comment: I have. The fact that $X$ is a $C^{*}$-algebra allows for the definition of $\{\cdot|\cdot\}$ and, in turn, the properties of this function lead to the imaginary units that come out at the end which give the contradiction. I actually think everything above is correct, but I am implicitly assuming that $X$ is a ``big enough" sub-algebra of $\mathcal{B}(H)$ for some $H$ (see the Gelfand-Naimark-Segal Theorem which I just came across) so that it cannot be Hilbert. In particular, this assumption would rule out the $X=\mathbb{C}$ counterexample and others like it.
Comment: You seem to have proven that a Hilbert space is not a Hilbert space. The calculation of $$ in your proof should hold when $f,g$ are members of a Hilbert space. Re-check your formulas & calculations.
Answer: The norm you are defining will be a Hilbert space norm precisely when $\|\cdot\|_X$ is a Hilbert space norm. If $X$ is a C$^*$-algebra, its norm is a Hilbert space norm precisely when $X=\mathbb C$.
C$^*$-norms are $L^\infty$-norms, while Hilbert space norms are $2$-norms.
Your "proposition" is not such. You write $\{if-g|if-g\}=\{f-g|f-g\}$, which is not true in general.


One Sample T-Test

Question: I want to test a hypothesis, where i want to test the marks scored by Boys and girls.
Gender = 1 is for males and gender = 0 is for females.
assuming I am reading a data from a CSV file this is how I am representing it.
hp<-read.csv("hyp.csv")
t.test(hp$Math[hp$Gender==1],mu=mean(hp$Math[hp$Gender==0]),alternative ="greater" ))
Is this the correct representation of the code. I am putting the girls mean in mu and boys as X.
Any help will be appreciated.
Thanks and regards,
Aditya
Comment: You have *two* groups, so why do you want to use *one* sample t-test?
Answer: There are two issues here, one about t-test and another about coding in R.
You don't have one sample from one population: you have two samples from two populations, and you are testing if means of both populations are equal. Therefore, you have to perform a two sample t-test.
About coding, you are using "hp" as variable, but "hp" is a data frame, and you need a single variable, that is one column of hp.
If scores are in a column named "score" code should be as following:
The code should be:
t.test(x=hp$score[Gender==1],y=hp$score[Gender==0],alt="greater")

Answer: Try the formula interface to t.test like so:
t.test(hp$Math ~ hp$Gender, alternative = "greater")

this will perform a Welch corrected t-test for independent groups. However, it is almost never justified to test alternative = "greater". In most instances by far, you should test alternative="two.sided" which is standard for t.test, if you do not specify alternative.
The formula interface (using ~) is shorter and therefore more readable and less error prone whenever the data comes in this form.
Use mu = if you want to perform a one sample test, e. g. compare female's grade to a fixed value like 2.5.
Finally: People at CrossValidated recognize questions on R syntax as off Topic (R Syntax is not statistics). Consider asking questions like this one on StackOverflow.

One Sample T-Test


How should I add a search method in this code

Question:         Scanner scanner = new Scanner(System.in);
        int weight;
        int age;
        //arrays
        List<String> last = new ArrayList<String>();
        List<Integer> zage = new ArrayList<Integer>();
        List<Integer> zweight = new ArrayList<Integer>();
        int i = 0;
        int userInput = 0;
        //menu options
        while(userInput != 2) {

            userInput = scanner.nextInt(); // collects the user inputs
            //several switch statements to answer each menu options
            switch(userInput) {
            case 1:

it saves and stores all the user inputs.

                System.out.println("Enter a last name, age, weight"); //stores all the user information

                    String lastName = scanner.next();
                last.add(lastName);

                age = scanner.nextInt();
                zage.add(age);

                weight = scanner.nextInt();
                zweight.add(weight);

                break;

Need to add a search code where it will retrieve the user inputs and display it, but i'm not sure on how to do it.

                            case 5:
                                    System.out.println("Enter the name; Enter DONE to exit");

                                    System.out.println("FOUND!!! Last Name: " +last+ " Age: " +zage+ " Weight: " +zweight);

Comment: I'm relearning java so i'm a little confuse on what to do
Comment: Do you know how to get the desired search parameters, and return the results once you have them? Is the actual searching algorithm the part you're having trouble with? Or is it the fact that your results are split between three lists?
Comment: I'm actually learning how to search right now so i'm new to it. I just have to add a search code that will match the name age and weight of the person
Comment: Are you allowing the user to go through all this multiple times? You need to initialize an object that will store all your names at the beginning then. You're also going to have to relate to the user's inputted weight.
Comment: Yes the user can enter the inputs as many times as they want. Not all of my code is shown but I basically have to search the original input that was saved
Comment: Have you considered a OOP approach? having an array list of a `Person` class with `name`, `age` and `weigth` properties? This way you only have one `ArrayList` instead of three and then you can use [any search algorithm you like](http://www.java2novice.com/java-search-algorithms/).
Answer: Your names are stored in a list so you can try this:
if (last.contains(searchName)) {
    String foundName = last.get(last.indexOf(searchName));
    System.out.println("FOUND!!! Last Name: " +foundName);
} else{
    System.out.println("Last Name: " +searchName+ " NOT FOUND!!! ");
}

Note that duplicate names may be in the list so you may want to loop over the indexes.
Answer: you can do this:
String enteredLastName = scanner.next();
for (String name : last){
   if (name.equals(enteredLastName ){
      //do something
   }
}

Comment: He would also need the index of matched `name` in the `last` list. It would be better to use a classic for instead of a for-each.


Cap colour in IPL

Question: If a player is the highest run scorer and at the same time is the highest wicket taker in IPL, which colour cap would he wear?
Comment: I think it is an award, both caps will be given to the player and the player can choose which one to wear, I don't have any supporting reference.
Comment: He can wear whichever cap he wants to wear. I am sorry, I don't really see any answerable question here.
Comment: Possible duplicate of [Rules for Orange and Purple Caps in IPL](http://sports.stackexchange.com/questions/2522/rules-for-orange-and-purple-caps-in-ipl)
Comment: @MaskedMan perhaps we should treat the question as "Is a player required to wear the orange or purple cap if they are entitled to them, and if so, which cap must they wear if they are required to wear both?" Well, I suppose they *could* wear both caps, but it would be a bit uncomfortable :-)
Answer: I see two questions here:

What caps would he be given if he's both the highest wicket taker and
  the leading run scorer?

According to the rules, both the caps would be awarded to the player, after the respective innings in which he earned them.

What cap would/should he wear if he's awarded both?

There isn't any rule which binds the player to the colour of the cap which he should be wearing. It is a personal choice for the player. (which is already addressed rightly in the comments under the question.)
Helpful Post

Cap colour in IPL


Como mudar a cor dos parênteses no vs code?

Question: Eu gostaria de mudar a cor dos parênteses no vs code para ter uma visualização melhor do código, mas não consegui. Só fica na cor branca.
Answer: Você consegue habilitar essa funcionalidade pelo settings.json do VS Code.
Para acessar o arquivo você pode usar o comando Ctlr+Shift+P e digitar settings.json.

Pode reparar que aparecerá 3 opções do arquivo, o específico para o usuário, para o workspace e o geral do VS Code. Edite na sua preferência, sabendo que a ordem de preferencia das configurações segue exatamente essa. Ou seja, se no settings.json a configuração estiver setada para false e a global em true, a configuração false prevalecerá.
Seguindo, no arquivo basta adicionar a seguinte chave e valor:
"editor.bracketPairColorization.enabled": true

Essa configuração mudará tanto a cor dos parênteses como dos colchetes e chaves também.
Espero ter ajudado.
Comment: Funcionou aqui. Obrigado!


Rotating boxes of variable width around a circle.

Question: first time posting a question. I'll try and be as descriptive as possible.
Let's say I have a circle with a Radius of r, and a variable amount of boxes with variable widths, but equal height, that I'd like to rotate around the circle. Each box should not overlap, but they should touch (I'm sure there is a math term for this). Given a starting point of 90 degrees, how would one go about doing this? Below is a link to a picture of what I'd like to accomplish. Also, here is a link to what I have managed to come up with: Link to project.
I hope that is a thorough enough explanation. Any help would be greatly appreciated, as I've hit a wall. I've stumbled across some great help, but haven't found anything that exactly fits my need. Thanks in advance.

Additional image to explain
Comment: "How would one go about doing this" $\rightarrow$ doing *what*? What exactly do you want? Rotating boxes is not mathematical in itself. Do you want an equation that describes the motion? In terms of which variables? Are there boxes all around the circle, or only those we can see?
Comment: Also, if the boxes *rotate* (around the tangency point) as opposed to *slide* (aka rotate around the centre of the circle) then it is not possible to preserve the condition that there is no overlap.
Comment: It appears that you want to arrange the rectangles so that the midpoint of a chosen side of each touches the circle and the rectangles are packed as tightly as possible. Is that about right?
Comment: Fair question. The boxes are to rotate around the centre of the circle, radius of 300. For now, let's just say there are three boxes, widths of 45, 75, and 50.

As the boxes are added, I want to determine the correct angle to rotate the next subsequent box.

@amd, that is correct.
Comment: I've added an additional image that hopefully offers some clarification.
Comment: Are you also assuming that the boxes are tall enough that none of them can slip under their neighbors? That's a possibility that complicates the computation somewhat.
Comment: Excellent question. Yes, I am operating under the assumption that the boxes are all equal height and could not slip under their neighbor.
Comment: OK. Equal height doesn't really matter; high enough does. The outer corners only need to be considered if the boxes can fit under each other.
Answer: It suffices to determine the angular offset between neighboring box centers. Let $r$ be the radius of the circle, $w_1$ the half-width of the box already in place and $w_2$ the half-width of the next box to be placed. Using half-widths seems natural: we really only care about the side of a box that faces its neighbor and this declutters the math by hiding otherwise extraneous factors of two in the variables. Polar coordinates seems best suited for this problem.
W.l.o.g. place the first box so that it touches the circle at $r\angle0$. Since we're assuming that the boxes are tall enough that no outer corners will fit under a neighboring box, there are three cases to consider:

$w_1=w_2$: The corners touch, so the angular displacement is simply twice the angle between the box corner and center. $$\Delta\theta = 2\arctan{w_2\over r}. \tag1$$
$w_2\gt w_1$: The corner of the second box hits the side of the first. That side is parallel to the polar axis, so its equation is $\rho = {w_1\over\sin\theta}$. The inner corners of the second box are at distance of $\sqrt{r^2+w_2^2}$ from the origin, so the corner will touch the box side at an angle of $$\arcsin{w_1\over\sqrt{r^2+w_2^2}}.$$ To this we add the angular displacement of the edge midpoint from the corner, so the total angular displacement of the second box from the first is $$\Delta\theta = \arcsin{w_1\over\sqrt{r^2+w_2^2}} + \arctan{w_2\over r}. \tag 2$$ Inverse trig functions can be quite expensive to compute, so it might be worthwhile in terms of overall efficiency to combine the two terms into a single tangent value by converting the sine to a tangent via the pythagorean theorem and using the formula for the tangent of a sum of angles.
$w_2\le w_1$: The corner of the first box hits the edge of the second. The roles of the boxes are reversed, so swap $w_1$ and $w_2$ and apply formula (2).

There is a further complication when the first box is wider than the circle and $w_2\gt w_1$: if we place the box corner on the side of its neighbor per the second case above, they'll overlap. Looking at what should happen as the second box's width is increased, once the corners of the two boxes meet, increasing the box width shouldn't change the angle any more. The box should simply keep extending in place. So, if $w_1\gt r$, clamp $w_2$ to $\min(w_1,w_2)$ and proceed as above.


How to change foreground on default RadRadioButton

Question: I'm trying to style my RadRadioButton's based on the default style for RadRadioButton:

Say I, for instance, would make a dark background for the Checked state, how can I change the button to have a white foreground (text color) in this state?
EDIT1
Based on Chris W.'s comment, I've added a ColorAnimation to this CheckStates VIsualStateGroup:
<VisualStateGroup x:Name="CheckStates">
    <VisualState x:Name="Checked">
        <Storyboard>
            <DoubleAnimation Duration="0" Storyboard.TargetName="CheckedVisual"
                             Storyboard.TargetProperty="Opacity" To="1" />
            <ColorAnimation Storyboard.TargetName="FontColor" Storyboard.TargetProperty="Color" To="White" Duration="0:0:0" />
        </Storyboard>
    </VisualState>
    <VisualState x:Name="Unchecked" />
</VisualStateGroup>

But that does not work, it gives me this error:

EDIT2
I changed to this based on new comment:
<VisualStateGroup x:Name="CheckStates">
    <VisualState x:Name="Checked">
        <Storyboard>
            <DoubleAnimation Duration="0" Storyboard.TargetName="CheckedVisual"
                             Storyboard.TargetProperty="Opacity" To="1" />
            <ColorAnimation Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground" To="White" Duration="0:0:0" />
        </Storyboard>
    </VisualState>
    <VisualState x:Name="Unchecked" />
</VisualStateGroup>

But now I got this error:
Comment: See your "Checked" `VisualState`? Slap this in between the `storyboard` tags there; ``
Comment: @ChrisW. Thankt for your comment, please see my updated question.
Comment: ah right, you've got a `ContentPresenter` in there. Change the `TargetName` to Content and the `TargetProperty` to `Foreground`
Comment: @ChrisW. Thank you again, please see my new edit.
Comment: Ah crap, actually just replace `Foreground` property with `TextElement.Foreground` and should be good. Sorry, my xaml is a lil rusty.
Comment: @ChrisW. Sorry, but I still got the same error. Except it now says: *Cannot resolve all property references in the property path 'TextElement.Foreground'. Verify that applicable objects support the properties.*
Comment: Hmmm, my xaml is rusty but it's not that rusty. That should be fine. Will try to go look at a copy of the telerik button in a button and see your culprit. I know in their docs there's a brush you can override real easily to accomplish your goal but you've essentially overridden the style template now so it wouldn't apply anyway. This task is also generally real easy using Blend and the states panel to see the available properties but I switched to web stuff some time ago. Either way, to be continued.
Comment: @dhrm Because I'm interested in it can you please check what happens when you use a `TextBlock` or something similar as `Content` of `telerik:RadRadioButton` (or do you already using something like that). Does the answer from Kamran Asim still working?
Answer: Did you changed Check background to Black?. You can edit  background property of

For Foreground Please apply ColorAnimation inside Checked VisualState="Checked"
 <VisualState x:Name="Checked">
  <Storyboard>
    ...........
    <ColorAnimation To="White" Storyboard.TargetProperty="(Control.Foreground).(SolidColorBrush.Color)" Storyboard.TargetName="Content" />
  </Storyboard>
</VisualState>

Comment: Your solution will work, unless you do something like this `Content` (I used `ToggleButton` for reference)
Comment: I tried above solution, by using Contenet to some text. it works. It should work with other controls, having foreground property. anyway you know what should be content, therefore you can set property accordingly
Comment: I am very thankful for your comment. I know this isn't the right place to ask questions, but I provided a litte [example](https://github.com/n0sale/showcases/blob/master/MainWindow.xaml) what I tried with your solution and which for me is not working.
Comment: Hellow @nosale Thanks for sharing example. I solved your issue in another way. Can you please try this.
1. Remove Foreground color animation from checked and unchecked
2. apply following style

It worked for me, please check it
Comment: Thanks for your time. I know that this will work, but the question is how to get it work by using `VisualStateManager` (I didn't find a solution so far, beside that one I posted). I found an [answer](https://stackoverflow.com/a/3068659/10718884) why your approach is not working under this conditions (still seems to apply in 2018)
Answer: Note: I don't have access to telerik:RadRadioButton therefore I used ToggleButton for reference
To make your animation work even when your Content is more complex
<telerik:RadRadioButton>
    <TextBlock>SomeContent</TextBlock>
</telerik:RadRadioButton>

You want to set the Foreground of RadRadioButton
Normally the first approach would be something like this
<ColorAnimation To="White" Storyboard.TargetProperty="Foreground.(SolidColorBrush.Color)" Storyboard.Target="{Binding RelativeSource={RelativeSource TemplatedParent}}" />

But then you will get this error

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element...

This error occurs because VisualStateManager is not part of the VisualTree
See also: WPF Error: Cannot find governing FrameworkElement for target element
To solve this you have to use a BindingProxy
For reference see also: Binding Visibility for DataGridColumn in WPF
public class BindingProxy : Freezable
{
    #region Overrides of Freezable

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    #endregion

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object),
            typeof(BindingProxy));
}

<ControlTemplate TargetType="{x:Type telerik:RadRadioButton}">
    <Grid SnapsToDevicePixels="True">
        <Grid.Resources>
            <local:BindingProxy x:Key="BindingProxy" Data="{Binding RelativeSource={RelativeSource TemplatedParent}}" />
        </Grid.Resources>
        ...
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                ...
                <VisualState x:Name="Checked">
                    <Storyboard>
                        ...
                        <ColorAnimation To="White" Storyboard.TargetProperty="Foreground.(SolidColorBrush.Color)" Storyboard.Target="{Binding Path=Data, Source={StaticResource BindingProxy}}" />
                        ...
                    </Storyboard>
                </VisualState>
                ...
            </VisualStateGroup>
            ...
        </VisualStateManager>
        ...
    </Grid>
</ControlTemplate>

Answer: Here is the code, that should work (works for me at least):
<VisualState x:Name="Checked">
                                    <Storyboard>
                                        <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="CheckedVisual"/>
                                        <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="(TextElement.Foreground)" Storyboard.TargetName="Content">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <SolidColorBrush Color="White"/>
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>

To make such styles in the correct way (means "recommended by Telerik"), you should  Right click on the component in designer -> Edit Template... -> Edit a Copy (well, you can try others at this point).
After those, correct (working) code will be generated in xaml, either in Resources or in the App.xaml file. Having this code, you can change those parameters. Hope it helped.


Float:left, div caindo pela largura da div

Question: Estou com um problema com o float:left;: para uma largura maior que a página a div cai, mas eu queria que continuasse a div anterior.
HTML:

    MENU

    RESTO DO CONTEUDO

CSS:
.menu {
    width: 250px;
    float: left;
    position: blocked;
    background-color: blue;
}

.resto {
    background-color: #ccc;
    width: 100%;
    float: right;
}

Resultado no JSFiddle.
Answer: Você não precisa do overflow: hidden;, retirando a width e o float: right; ela já vai para a mesma linha.
O bom seria você colocar uma width nas duas div's e deixa-las num bloco para evitar conflitos com elementos abaixo deles.
Veja o código no JSFiddle
Com isso você cria blocos no seu código e evita que elementos abaixo deles "quebrem" a página.
Bons estudos!
Answer: Pelo que me parece queres por a div fixa na linha.
Faltava-te a propriedade overflow: hidden; que faz isso mesmo.
Fiddle editado
Comment: Muito obrigado consegui resolver o meu problema
Comment: Sempre bem vindo! Nota: Se respondi à sua questão coloque a mesma com a resposta correta
Comment: eu coloquei a resposta do meu poblema,fiz certo??
Comment: Não, na resposta que eu dei está um visto/correcto. Basta clicar lá.


Cache Redis on Azure

Question: Contratei o serviço de cache Azure Cache Redis, porém para importar o database atual tive que migra-lo para Premium P1, após importar tentei voltar para o C0, impossível, o Azure Cache Redis só faz upscale nunca downscale.
Preciso criar o meu database, mas no C3 da timeout. Por padrão creio que ele rodaria em um B2, porém o processo de criação do database é pesado e complexo.
Então como conseguir importar ou gerar o database inicial se o scaling só é pra cima?
Será que se eu fizer, 2 conexões, um com meu servidor de redis atual e outro no azure, e fizer um select e depois um set no azure, será rapido? São 90mil keys pra gerar, cada uma bem grandinha.
Informações sobre os planos Redis Azure
https://azure.microsoft.com/pt-br/pricing/details/cache/
Pedido para poder fazer downscale no serviço do Redis no issue do Azure
https://feedback.azure.com/forums/169382-cache/suggestions/10560624-smaller-premium-redis-instances
Comment: O link sobre "pedido de downscale" não deve estar correto. Os assunto são diferentes.
Answer: Infelizmente o serviço Cache Redis (Paas) do Azure ainda possui algumas limitações como:

Importar somente camada premium;
Impossível fazer downgrade da camada, após colocar em um Premium para importação, ficará preso sempre neste.

Minha solução foi, contratar uma VM com windows e instalar o Redis Cache (poderia ser uma VM linux também) e assim o custo ficou menor e com desempenho superior a Premium P1.
Answer: Eu imagino que não esteja conseguindo fazer o downscaling pois, após carregar 90K keys, apenas alguns planos suportem estocar todos esses dados.
Não sei o tamanho da sua massa de dados, mas, por exemplo, a C0 suporta apenas 250MB de cache - esse tamanho é diretamente proporcional à sua massa de dados, mas a relação não é 1 para 1.
Sobre o timeout, se puder compartilhar o trecho do seu código que está suando para fazer a migraça, posso tentar ajudar a identificar pontos de melhoria, mas, de qualquer forma, eu recomendo a seguir os seguintes passos:

Crie seu serviço de Azure Redis Cache em um plano que seja interessante para seu negócio - no seu caso, provavelmente no B2;
Provisione uma VM no mesmo DataCenter - se possível no mesmo Resource Group - do seu serviço de cache;
Copie seu backup para essa VM e faça a importação dos dados a partir de lá.
Após a importação finalizar, exclua a VM.

Isso fará que vc realize a importação via "rede local", tornando menor a change de obter timeout ou perda de pacotes.
Comment: 90k não da nem 180mb
Comment: 180mb de dados exportados. Se somar as redundâncias, mais índices, etc, pode sim passar dos 250mb.
Comment: até concordo mas o plano q testei foi de c3 da mais de 2gb
Comment: Sim, mas isso me refiro a não conseguir fazer o downscale
Comment: mas não era esse o problema, de acordo com o manual do Azure o Redis ainda não possui downscale.

Cache Redis on Azure


PHP file upload not working. Getting error:

Question: To start things off, I've looked at a few similar problems on here but still can't resolve my issue here.
HTML:
<input type="file" name="filename" multiple="multiple" data-classIcon="icon-plus" data-buttonText="Upload Your File">

PHP:
$name = $_FILES['filename'];
$temp_name = $_FILES['filename']['tmp_name'];
if(isset($name)){
    if(!empty($name)){
        $location = 'uploads/';
        if(move_uploaded_file($temp_name, $location.$name)){
            echo 'uploaded';
        }
    }
} else {
    echo 'error: not uploaded';
}

JS:
$('#cc-submit').on('click', function(e){

            e.preventDefault();

            $.ajax({
                type: "POST",
                url: "balanced/example.php",
                data: $('#creditcardpost').serialize(),
                success: function(data)
                {
                    alert(data);
                }

            });
        });

Error:
Undefined index: filename in /public_html/script.php on line xx (the two lines that collect the $_FILES variables.
"error: not uploaded"
Comment: It seems $_FILES doesn't contain a key for 'filename'. Did you add `enctype=multipart/form-data` to your form tag?
Comment: Duplicate, see: http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery
Comment: I just added it, and the issue persists.  :(
Comment: Can you post your form tag? Can you also `print_r($_FILES)` and see what comes out? There is another thing you should change to your code btw. `isset()` checks the existence of a variable, $name always exists in your case, whether it's empty or not. Use `isset($_FILES['filename'])` instead.
Comment: I just changed to isset($_FILES), then at the end used print_r($_FILES) and it returns an empty array: Array(
Comment: @IAteYourKitten, `isset($_FILES)` will also always be true since it's a global variable. However, see jeroen's comment above, that's your problem.
Comment: I'm looking at that.  It appears to be a very similar issue.  I will check that and see if I can fix the issue.  Thanks you guys.  I'm always surprised with how quickly you can get help here.  :)
Answer: You must use:
$name = $_FILES['filename']['name'];

Comment: @Chris That's my point, so this answer is correct. Apart from the file not being uploaded because of ajax...
Comment: This outputs the same error.  This is not the issue.
Comment: I don't think this is true, he needs to use tmp_name if he wants to move the file to a different location. `name` contains the original file name.
Comment: @IAteYourKitten Check if your form use `enctype=multipart/form-data`.
Comment: +1 I don't know why this is downvoted, `$_FILES['filename']` is an array so that is not going to work when the OP tries to move the file.
Comment: I'm submitting form via jquery as well.  If that helps anyone get an idea of what's happening.  Site is: http://certitrans.com/checkout.php
Comment: @IAteYourKitten That's kind-of essential information, you should add that - and the javascript - to your post.
Comment: Ok, so $_FILES['filename']['name']; is now the first variable and it's still happening, though.  It;s still giving the error of undefined index.
Comment: @jeroen, that's correct. But that's another problem. OP should change that the first line to `$name = $_FILES['filename']['name']`
Comment: @Chris Ummm, which comment are you commenting on?
Comment: @jeroen, Your first one.
Comment: @IAteYourKitten Plus `enctype: 'multipart/form-data'` in your ajax.
Comment: I did all that.  It was an issue separate from this answer.  It was with how jquery was sending the form to php, but also that I wasn't picking up the correct file in my php script.
Answer: I used print_r on $_FILES and found my files were coming through as "file-0".  I'm not doing multi file uploads, so this works for me.  And here is the solution.  PHP:
$name = $_FILES['file-0']['name'];
$temp_name = $_FILES['file-0']['tmp_name'];
        $location = '../uploads/';
        if(move_uploaded_file($temp_name, $location.$name)){

        }

print_r($name);

And the JS that sends it needed to be worked a bit:
var data = new FormData();
jQuery.each($('#file')[0].files, function(i, file) {
    data.append('file-'+i, file);
});

$.ajax({
    url: 'balanced/upload.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        alert(data);
        $('#creditcardpost').append('<input type="hidden" value="' + data + '" name="filename" />');
    }
});

I've got it working.  Thanks for helping out guys.


Maximum error bound for ODE

Question: For $f\in C([0,T]×\mathbb{R})$, let $|f(t,x)-f(t,y)|\leq L|x-y|$ for a $L\geq0$. Also suppose we have a differential equation
\begin{align}
y'(t) &= f(t,y(t))\\
y(0)&=y_0
\end{align}
with $y_1,\dots, y_N$ the solutions given by the Forward Euler method.
So far I found that a bound for the maximum error is given by
$$\max_{0\leq n \leq N} e_n \leq \frac{M}{2L}(e^{LT}-1)h$$
where $M=\max_{0\leq t \leq T}|y''(\tau)|$ for a $\tau\in[0,T]$, and $h=T/N$ the step size.
My question is: how do I find this bound for the following initial value problem:
\begin{align}
y'(t)&=\arctan(y(t))\\
y(0)&=y_0?
\end{align}
I am stuck at finding $M$ and $L$. How could I find the maximum of the double derivative of $y(t)$ if I do not know anything about the function?
Answer: In fact, the correct expression is $\displaystyle M = \max_{t \in [0,T]}|y''(t)|$. In order to get an error estimate, you don't need to exactly compute $M$, you just need to have an upper bound:
$$
|y''(t)| = |(\arctan(y(t)))'| = \left|\dfrac{y'(t)}{1+y(t)^2}\right|=\left| \dfrac{\arctan(y(t))}{1+y(t)^2}\right|\leq \frac{\pi}{2}.
$$
Comment: If $f$ is $C^1$ you have that $L = \sup \left|\frac{\partial f}{\partial y}\right|$. You'll see that $L\leq 1$.
Comment: Yeah makes sense! How do I compute/bound the $L$ though?

Maximum error bound for ODE


Are Abel's and Dirichlet tests necessary for uniform convergence?

Question: Can a series of functions $$\sum_{n=1}^{\infty} {f_n(x)}$$  that doesn't meet the conditions of Abel's (or Dirichlet) test be uniformly convergent?
Comment: Sure. All those convergence criteria are only suficient conditions for convergence.
Comment: An important question comes to my mind: how do you check that a series of functions does not meet the condition of Abel's (or Dirichlet) test? This seems to be VERY complicated. This is the reason why I think that no decent answer will be given to this answer.
Comment: van der Corput estimations of exponential sums help sometimes if the coefficients oscillate nicely but not as nicely as in the Abel-Dirichlet case
Answer: Both of these criteria require you to write $f_n(x)$ in the form $a_n(x)b_n(x)$ where one of these new sequences of functions is monotonically decreasing. So to prevent these tests from being applicable, you just need to deny the possibility of finding a useful monotonically decreasing sequence of functions. For example if
$$
f_n(x):=\begin{cases}
\frac1n&\text{if $n\le x<n+1$}\\
0&\text{otherwise}
\end{cases}
$$
then $\sum_nf_n(x)$ converges uniformly. However, the $f_n$'s are nonzero on non-overlapping intervals, so if you write $f_n=a_nb_n$ with $b_n$ monotonically decreasing, then the $a_n$ you wind up with isn't materially different from $f_n$: proving uniform convergence (or uniform boundedness) for $a_n$ is no easier than for $f_n$. In other words, for this counterexample the Abel and Dirichlet criteria don't offer any help.


GA or ANN, and suggestions

Question: I am working to approximate, to extrapolate rather, values of a function from a few known values. Here is what I have:

Less than 100 known I/O pairs.
A monotonously positive correlation.en
Something that is not exactly Gaussian, Poisson, or inverse binomial.

Right now I can choose between a genetic algorithm and an artificial neural network. If I use a genetic algorithm, then I will use it to approximate the relation with a polynomial or a rational function. If I use a neural network, I will simply find the first Google result for a C++ NN library (unless I am advised otherwise).
Here are my questions. Suppose I have access to a long time (1-2 week max) as well great computational might (university clusters).

Would I achieve a closer approximation with a GA or an ANN?
Which would be faster?
For those ANN specialists out there: I am unacquainted with the world of ANN technology. If I am looking for portability, programmability, speed, and adaptability for such extrapolation, which C++ toolkit would you recommend?

Thank you.
Comment: We need more information regarding the nature of the function you want to extrapolate in addition to how far you want to extrapolate away from known values.
Comment: Why would you use a genetic algorithm to learn the parameters of a polynomial? There are much [better](http://en.wikipedia.org/wiki/Polynomial_regression) ways.
Comment: @alto Well, a GA in general.
Comment: @MarcClaesen Values range from 0 to 200. We have about 50 values, and want to extrapolate about 200. What would you like to know about the nature of the function?
Answer: Genetic algorithms and neural networks are not really competing methods. For instance one could use a genetic algorithm to train a neural network (a field called neuroEvolution).
Genetic algorithms are used to optimise 'thing' and neural networks are 'something' to be optimised. i.e. one could optimise a neural network using backpropagation, some form of hebbian learning or a genetic algorithm.
1)
If you are going to use a genetic algorithm to optimise the weights of a polynomial function then as @alto suggests there are likely better methods.
As for neural networks, they can be universal approximators, so in theory you could achieve a very good approximation.
2)
I couldn't find and results on typical training times. Firstly people do not often quote the training time in 'wall time'. The backpropagation world are more concerned with the final result and the genetic algorithms world compare methods using the number of evaluations to find a suitable solution. So a comparison between the two can't be made.
Answer: If using C++ is a must, you may take a look at Shogun. As I understand, it could be a NN, but any method that get the job done will do as well. Shogun focuses on kernel methods (SVM and GP).
As for genetic algorithms: I have no experience whatsoever with that optimization technique, but mostly because I have not come across it in the literature. It seems to me that not many people in the Machine Learning community uses it.

GA or ANN, and suggestions


High School Projectile Motion and Quadratics

Question: High school students are learning about the basics of solving quadratics and trigonometric ratios, including trigonometric inverses. The eventual goal of their project is to be able to show a reasonable firing solution, given in initial angle $\theta$ and initial velocity $v_0$.
Projectile motion is given by
$$y=\left(\tan{\theta}\right)x-\left(\frac{g}{2v_0^2\cos^2{\theta}}\right)x^2$$
where $x$ and $y$ are horizontal and vertical displacement. In this equation, one might change $\theta$ or $v_0$ and the equation behaves as expected - allowing students to directly give a reasonable solution.
My goal is to find a way to help my students build up understanding from basic quadratics, which appear like a trajectory in shape, to a more accurate representation of trajectory given by the equation above. Since the trajectory equation is quadratic in nature and can be reduced to $ax+bx^2$, and because students will also learn trigonometric ratios, this is reasonable. Note that I am giving the context because the answer needs to be at a relatively low level, and I also hope that someone might have a contribution for the approach.
Students initially create quadratics that look like projectile motion using quadratics of the form $y=-x(x-a)$. This gives a nice way to discuss solutions (the impact point) using the zero product property. We build up to $ax^2 +bx+c$ form, now discussing other ways to find solutions. Then I ask students to convert this equation to an initial angle and velocity (after discussion of what a firing solution might constitute). They realize quickly that such an equation doesn't make a lot of necessary information very obvious - eg, gravity, angle, velocity, etc.
While we eventually discuss the trajectory motion equation (sadly, I haven't discovered how to build this in a way high school geometry students understand), we initially account for gravity using the equation
$$h(t)=\frac{1}{2}gt^2+v_{0,y} t+h_0$$
where $t$ is time in seconds, $g$ is acceleration due to gravity, and $h(t)$ is height in meters, and $v_{0,y}$ is initial $y$ velocity. My question is: can $h(t)$ be modified with a particular initial angle $\theta$ and initial velocity $v_0$? My suspicion is that the answer to this question will look like the parameterized version of the trajectory equation.
Comment: Which equation do you mean by "this equation"?
Comment: Edited for clarity - I meant the equation most proximal - $h(t)$
Answer: Here's how I understood this before I studied calculus:
Suppose the projectile is to be launched from the point $(0,0)$
at initial speed $v_0$ in a direction making an angle $\theta$
above the positive $x$ axis,
and suppose (for now) that there is no gravity here.
Then the projectile travels a distance $v_0$ in that direction in the first
unit of time,
and a distance $v_0 t$ in that direction in the first $t$
units of time.
Construct a right triangle with legs parallel to the $x$ and $y$ axes
and hypotenuse $v_0 t.$
The horizontal leg is then $v_0 t\cos\theta$
and the vertical leg is $v_0 t\sin\theta.$
If we construct this triangle on the coordinate plane with the
hypotenuse in the initial direction of the projectile
with one end of the hypotenuse at $(0,0),$
we find that the $(x,y)$ coordinates at time $t$ are given by
\begin{align}
x &= v_0 t\cos\theta,\\
y &= v_0 t\sin\theta & \text{(in zero gravity).}
\end{align}
Now we consider the effects of gravity.
Assuming you have already derived the fact that an object starting
at $(0,0)$ with no initial velocity will fall under the influence of
gravity so that it reaches the vertical coordinate $y = -\frac12 g t^2$
at time $t,$
we combine the motion due to the initial velocity of the projectile
with the motion due to gravity.
The result is that the projectile ends up at a position displaced
vertically by $-\frac12 g t^2$ from where it would have been if there
were no gravity, and not displaced horizontally (because things don't fall sideways!), so it ends up at
\begin{align}
x &= v_0 t\cos\theta, \tag1 \\
y &= v_0 t\sin\theta - \tfrac12 g t^2 & \text{(where gravity is $g$).}\tag2
\end{align}
To really understand this, I think you need some notion of Galilean relativity: the launch speed and angle establish an inertial frame of reference traveling at velocity $v_x=v_0\cos\theta,$
$v_y=v_0\sin\theta$ relative to the ground, and the projectile falls
straight down within that frame of reference.
One way to explain it might be, you fire two cannonballs from the
same place in the same direction at the same speed; one is a magic cannonball that isn't affected by gravity, but the other is an ordinary cannonball.
A hypothetical observer riding on the magic cannonball will initially see the
ground receding down and behind while the ordinary cannonball is stationary,
but after $t=0$ the ordinary cannonball will appear to fall straight down
(as seen from the vantage point on the magic cannonball).
So while the magic cannonball follows a trajectory with $y=v_0t\sin\theta,$
the ordinary cannonball follows Equation $(2).$
If you launch the projectile from a point $(x_0,y_0)$ instead of
$(0,0),$ everything is displaced by $x_0$ horizontally and $y_0$ vertically,
and you get the more general equations
\begin{align}
x &= v_0 t\cos\theta + x_0,\\
y &= v_0 t\sin\theta - \tfrac12 g t^2 + y_0.
\end{align}
But as long as you launch from $(0,0),$ then $x_0 = y_0 = 0$ and the
equations end up acting like $(1)$ and $(2).$
Now observe that if $x = v_0 t\cos\theta$ (from Equation $(1)$), then
$$t = \frac{x}{v_0\cos\theta}.$$
Make this substitution for $t$ in Equation $(2)$ and you can work out
the equation for $y$ as a function of $x.$
I don't agree with the way the question implies that
parabolas of the form $y = ax + bx^2$
merely appear to be like trajectories in shape,
nor the implication that the formula with $v_0$ and $\theta$
is more accurate than $y = ax + bx^2.$
On the contrary, I would say that $y = ax + bx^2$ is just as
accurate an equation of a projectile trajectory (provided that $b$ is negative), even though it does not explicitly tell you what the initial velocity and angle are.
If you want the initial velocity and angle of the projectile that follows
the trajectory $y = ax + bx^2,$
you have to solve for $v_0$ and $\theta$ in terms of $a,$ $b,$
and $g.$

Update: For reference, it may be helpful to show the derivation of $v_0$ and $\theta$ from $a$ and $b.$ We suppose that we are given the path
$$ y = ax + bx^2 $$
for some given (known) values of $a$ and $b.$
This can only be a projectile trajectory if the same path is also given by an equation of the form
$$ y = (\tan\theta)x - \left(\frac{g}{2v_0^2\cos^2\theta}\right)x^2$$
for some values of $v_0,$ $\theta,$ and $g.$
In order for both equations to describe the same path, the right hand side must be the same polynomial in each equation. This means the coefficient of $x$ must be the same each time, and the coefficient of $x^2$ must be the same. So we have a projectile trajectory only if we can simultaneously solve these two equations:
\begin{align}
a &= \tan\theta, \\
b &= -\frac{g}{2v_0^2\cos^2\theta} = -\frac{g}{2v_0^2}\sec^2\theta.
\end{align}
From the first of these equations we have $\theta = \tan^{-1}(a)$
(for a projectile that travels over the part of the parabola for
which $x \geq 0$)
or $\theta = \tan^{-1}(a) + \pi$ (for the other part of the parabola).
Using the identity $\sec^2\theta = 1 + \tan^2\theta,$ we have
$$
b = -\frac{g}{2v_0^2}\sec^2\theta = -\frac{g}{2v_0^2}(1 + \tan^2\theta),
$$
and using the fact that $a = \tan\theta,$
$$
b = -\frac{g}{2v_0^2}(1 +a^2).
$$
If $g$ is known, then there is only one unknown in this last equation,
$v_0.$  To find $v_0$ we first isolate $v_0^2$ on one side of the equation:
$$
v_0^2 = -\frac{g(1 + a^2)}{2b}.
$$
The left side must be positive; making the usual assumption that $g > 0,$ and and noticing that $1 + a^2$ is necessarily positive,
we conclude that we can only solve this equation if $b < 0.$
Provided that $b < 0,$ we find that
$$
v_0 = \sqrt{-\frac{g(1 + a^2)}{2b}},
$$
so we have derived both the angle and initial velocity from the coefficients $a$ and $b.$ Moreover, this derivation always works as long as $b < 0$:
any downward-opening parabola is the path of a projectile trajectory.
Comment: For a given value of $g,$ there are only very specific sets of equations that correctly relate all three of the variables $x,$ $y,$ and $t.$ If you're only looking at the path in the $x,y$ plane ($y$ as a function of $x$), however, you just need to make sure the curvature of the parabola is consistent with the direction of gravity; that is, you need $b<0.$ As long as $b<0,$ you can always find an angle and initial speed that will follow the parabola $y = ax + bx^2.$ I've added the explicit derivation to the answer.
Comment: Good point about trajectory - what I really meant was that if a student uses $ax+bx^2$ where $a$ and $b$ are arbitrary numbers, then their understanding isn't as accurate as if they deliberately created those two constants using understanding of velocity and angle. Further, students will be unable to easily derive  $v_0$ and $\theta$ if $a$ and $b$ are arbitrary. I'd fix the question, but I'll leave it for others to learn from my misconceptions. =)
Comment: That said, gravity needs to be accounted for in a specific way. While a student might be able to provide an acceptable looking trajectory with an arbitrary $a$ and negative $b$, won't that equation most likely fail to account correctly for gravity?
Comment: For the record, this explanation went over extremely well. I added the trig connection that the coefficient of the $x$ term, $\tan \theta$, is the slope of the initial angle, so naturally, the inverse tangent of that coefficient provides the initial angle. Finding $v_0$ in terms of $a$ and $b$ is a great idea (why didn't I think of that?). My geometry kiddos have to take my word for it on that equation though. =) Excellent explanation.
Answer: You want $\boxed{h(t)=gt^2+v_0\sin(\theta)t+h_0}$.
This is because the vertical component of the $v_0$ arrow pointed in the $\theta$ direction has height $v_0\sin(\theta)$.
By the way, in this problem $g=-4.9$, because the acceleration due to gravity is $-9.81$ m/$s^2$.


Martingale property of a stochastic process

Question: Suppose $(X_t)_{t\ge0}$ follows $dX_t=dt+X_t\,dW_t$ and $X_0=x\ge0$. It's not too hard to see that $\mathbb{E}[X_t]-x=t$ because the Ito integral of $X_t\,dW_t$ averages out to zero. How would I go about finding $\mathbb{E}[X_t^2]$? Is it true that the Ito integral of $X_t^2\,dW_t$ averages out to zero as well?
This question is related to this one.
Comment: Please clarify if your question is mainly about a) how to calculate $\mathbb{E}(X_t^2)$ OR b) under which assumptions is a stochastic integral a martingale
Comment: Sure, please see my comment to your answer.
Answer: There is the following well-known statement which you can find in (almost) any book on stochastic differential equations:

Let $\sigma$ and $b$ be two globally Lipschitz continuous functions. Then there exists a unique (strong) solution to the SDE $$dX_t = b(X_t) \, dt + \sigma(X_t) \, dW_t$$ for any (square-integrable) initial distribution and, moreover, $$\mathbb{E} \left( \sup_{s \leq t} |X_s|^2 \right)<\infty \qquad \text{for all $t \geq 0$.} \tag{$\star$}$$

Applying this result we find that the solution $(X_t)_{t \geq 0}$ to the given SDE is square integrable (in the sense of $(\star$)). Since this gives
$$\int_0^t \mathbb{E}(X_s^2) \, ds < \infty$$
for any $t \geq 0$, we get that the stochastic integral $\int_0^t X_s^2 \, dW_s$ is a martingale.

Regarding the calculation of $\mathbb{E}(X_t^2)$: It follows from Itô's formula that
$$X_t^2-X_0^2 = 2 \int_0^t X_s \, dX_s + \langle X \rangle_t$$
where $\langle X \rangle_t$ denotes the angle bracket:
$$\langle X \rangle_t = \int_0^t X_s^2 \, ds.$$
Using that
$$dX_t = \, dt + X_t \, dW_t$$
we get
$$X_t^2-x^2 = 2 \int_0^t X_s^2 \, dW_s + 2 \int_0^t X_s \, ds + \int_0^t X_s^2 \, ds. \tag{1}$$
The stochastic integral
$$M_t := \int_0^t X_s^2 \, dW_s$$
is a martingale (see the first part of this answer), and therefore we have in particular $\mathbb{E}(M_t) = \mathbb{E}(M_0)=0$. Consequently, $(1)$ gives
$$\mathbb{E}(X_t^2)-x^2 = 2 \int_0^t \mathbb{E}(X_s) \, ds+ \int_0^t \mathbb{E}(X_s^2) \, ds.$$
As $\mathbb{E}(X_s) = x+s$, we get
$$\mathbb{E}(X_t^2)-x^2 = 2xt + t^2 + \int_0^t \mathbb{E}(X_s^2) \, ds$$
which shows that $\varphi(t) := \mathbb{E}(X_t^2)$ solves the ODE
$$\varphi'(t) = 2(x+t) + \varphi(t), \qquad \varphi(0)=x^2.$$
The solution is given by
$$\mathbb{E}(X_t^2) =\varphi(t) = -2(x+t+1)+e^{t} (x^2+2x+2).$$
Comment: Thank you for the detailed solution. My specific question was actually about verifying that $M_t$ is indeed a zero-mean martingale. It's not always the case that $\int_{0}^{t} f(\omega,s)\,dW_s$ averages out to zero; there is a certain integrability condition that $f(\omega,s)$ has to satisfy.
Comment: @Jason See my edited answer.
Comment: Shouldn't the exponent in your formula for $\phi(t)$ be to the positive $t$?
Comment: @Jason Yeah, thanks.


Trying to learn Ab Scale on Piano, and can't make sense of the fingers

Question: I am trying to learn Ab Scale, and fingers are tripping me up. I only know C Major till now and a beginner, so please help.
For right hand : Its suppose to be 2,3,1,2,3,1,2,3 but I am starting Ab on 2 and ending at 3, isn't this weird. Wouldn't it be better to start Ab on 3 so I can end on 3 as well (similar to C Major where I use 1 if I want to switch up octaves).
The left hand is following that principle starting and ending Ab at 3, so why is the 4th finger never used in right hand and when I move up octaves, wouldn't I end up using 3,4,1,2,3,1,2,3. So why not start the scale at 3 as well, what part am I getting wrong?
Comment: Can you confirm: the only scale you know is `C` major, and the next scale you are learning is `Ab` major?
Answer: It looks like you're only playing one octave. If you continue for another octave you'll end up playing the Ab with RH3 and Bb with RH4. You could start the scale that way if you like, but 2 3 make the thumb movement easier. Do whatever works for you.
Comment: Any specific accidentals that are easier managed by starting at 2, or is all about personal comfort?
Comment: @AnonyMous It's all about comfort. Start with 2 for comfort, or with 3 to make the fingering consistent across octaves.
Answer: 'Supposed to be' according to who?
23123123 might be considered superficially 'easier' when playing just one octave of the scale.
34123123 keeps the fingering consistent when continuing into a second octave.
The first couple of online resources I found suggest 34123123.  I agree with them. I think you should too.
https://www.pianoscales.org/major.html
http://robertkelleyphd.com/home/teaching/keyboard/keyboard-scale-fingering-chart/
Comment: According to a couple of youtube videos and reddit post I found. I was wondering if there were any accidentals commonly used near A# that were easier managed by starting at 2. Would likely start at 3 myself, since it felt more natural and comfortable.
Comment: In isolation, Ab, Bb, C is probably 'easier' 231.   But in the context of a continuing Ab major scale, 321 is necessary.  You don't HAVE to play every fragment as if it was part of a scale though.


Como saber se todos os objetos de um array estão inseridos em outro array baseado em uma propriedade em comum nos dois arrays

Question: Possuo dois arrays de objetos e preciso verificar se todos os itens de um array estão contidos no outro array.
Preciso saber se o array2 está contido no array1 utilizando a propriedade id de cada item dos arrays.
Deve retornar true se todos os elementos de array2 estão presentes no array1 e false caso contrário.

const array1 = [
  {
    id: 25,
    name: 'Badaró',
    altura: 1.75,
  },
  {
    id: 68,
    name: 'Badalão',
    altura: 1.65,
  },
  {
    id: 74,
    name: 'Badalador',
    altura: 1.55,
  },
  {
    id: 49,
    name: 'Badaladinho',
    altura: 1.45,
  },
];

const array2 = [
  {
    id: 68,
    name: 'Badalão Choris',
    altura: 1.69,
  },
  {
    id: 74,
    name: 'Badalador Bang',
    altura: 1.59,
  },
];

Tentei utilizar .every() combinado com .includes() da seguinte maneira (achei aqui):
array1.every((v) => array2.includes(v))

Mas o resultado que obtive não foi o esperado, preciso verificar por ID, pois possivelmente os objetos de cada array podem conter outras propriedades diferentes.
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Você pode criar duas novas variáveis que irão armazenar a lista de id's dos 2 arrays, após isso, verificar se o array2 está inteiramente inserido no array1. Exemplo:
const idList = array1.map(item => item.id);

const idListCheck = array2.map(item => item.id);

const isEveryInList = idListCheck.every(id => idList.includes(id));

Uma dica seria nomear as variáveis de forma mais clara, no lugar de usar "array1" utilizar algo mais simples de entender, exemplos de variáveis
productList ou products
itemList ou items
...


Dúvida de como exibir o nome de uma key de um dicionário

Question: É possível exibir o nome de somente uma key de um dicionário?
ex:
notas_por_materias = { "Matematica" : 7,
                       "Portugues" : 8,
                       "Historia" : 10 }

Consigo exibir um print mostrando o nome da matéria e depois a nota dela? Ex:
print (f"Sua nota em {Matematica}, foi de {nota_por_materias["Matematica"]}")

Eu consigo exibir o valor da nota, porem não consigo fazer o mesmo com o nome da matéria. Tentei passar como índice [0] e como notas_por_materias.keys(0), porém sem sucesso. Sei que tem varias outras formas bem mais simples de fazer isso, porém como estou aprendendo a utilizar dicionários, gostaria de saber como exibir por meio deles.
Answer: O que você está fazendo não faz muito sentido. Se você sabe o que deseja imprimir então não tem porque fazer diferente do que fez, exceto que não usar essas chaves. Tem erros de sintaxe nisso também (nome da variável escrito errado, confusão entre aspas duplas e simples para separar o que é o texto e o que é a chave do dicionário, feito assim ele acha que o dicionário está encerrando o texto), fazendo tudo certo ficaria assim:
print (f"Sua nota em Matemática, foi de {notas_por_materias['Matematica']}")

Se deseja fazer em um laço, aí faria mais ou menos algum sentido em generalizar o nome da matéria, mas aí é outro problema. Um dos motivos que não faz tanto sentido assim é porque a chave é um dado escrito de uma forma muito simples pra facilitar o código e o que quer que seja impresso é algo apresentável para um ser humano, são conceitos diferentes, só nesse exemplo já vemos um problema, a chave não tem acento e o que deseja apresentar tem, fora que começa com maiúsculo o que pode não ser o desejado no texto em alguns cenários. Se quiser insistir nisso, seria algo assim:
for key, value in notas_por_materias.items() :
    print (f"Sua nota em {key}, foi de {value}")

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Consegui compreender o erro, obrigado pela ajuda!!


How do I use string gauge tables?

Question: I have seen that string manufacturers publish tables of string gauges and tensions.
For example, this one.
How can I use these to choose a set of strings for my instrument?
Answer: The simple answer is to leave it to the experts. Strings are sold in packs, with a sensibly chosen set of gauges, for most common instrument configurations, whether you have a 4 or 5 string bass guitar, a 6 or 12 string guitar, a mandolin, or whatever.
Even if you don't want to buy a full set, you can look at the gauges supplied in a set, and buy an individual string of that gauge.
But standard sets might not meet your needs for various reasons:

you might be experimenting with alternative tunings
you might want an unconventional mixture of string types
you might have reached a sophistication in your playing where you find you want a very specific variation of string tensions from one string to another.

So if you do want to work from the tables, here's how.
There are two factors that affect your choice of string:

pitch: you want the open string to play at a certain pitch; whether that's the standard pitch for the string in that position, or you're experimenting with alternative tunings.
tension: you want a certain tension because it suits your playing. Too taut, and it requires too much pressure to fret. Too loose and it vibrates too widely. Tension also affects the timbre - see How does string gauge affect a guitar's sound and playability?

So, let's find out approximately what tension your current strings have. You can use this as a guideline.
One row in the D'Addario tables describes their plain steel PL010 string:

Item# Unit Weight g'   f'   e'   d'   c'   b   a   g
PL010 .00002215   22.9 18.2 16.2 12.9 10.2 9.1 7.2 5.7

The '010' in the string's item number refers to its width in 1000ths of an inch; but for shorthand we refer to this string as "a 10". The unit weight is its weight in pounds per inch. The remaining numbers are the tension in pounds, at the pitch shown.
So if your guitar's top E -- e' -- uses this string, then its tension is 16.2 pounds.
(D'Addario has chosen to produce its tables in non-metric measures, alas)
If you feel you want a tighter top E string, then, you might choose a PL013 at 27.4 pounds. If you want a looser top E string, you might choose a PL07 at 7.9 pounds.
As you can see, there is quite a difference in tension - the 13 is three times tauter than the 7.
As a starting point, you're likely to want all your strings to have approximately the same tension, so that the action of fretting a note feels similar on all strings. So, let's say you've decided that you're comfortable with the 16.2 pound tension of your top E string, and you'd like a G string to match.
Look through the tables, until you find a string in the g column which is close to 16.2.

Item# Unit weight b    a    g    f    e    d   c   B
NW018 .00006215   25.5 20.2 16.1 12.8 11.4 9.0 7.2 6.4

Note that this part of the chart has lower pitches than the previous example. That's because we've moved on to nickel-wound strings designed for lower pitches. Here, we've found a string that, when tuned to 16.1 pounds of tension, plays a G.
Now you have the flexibility to play with these tensions. Perhaps you'd prefer your bass strings to be slightly looser than the treble strings; just decide on the pitch and tension you want, and choose the string that matches.
Note that your instrument's neck has to endure the sum of all the string tensions. So if you have 6 strings at 16.1 pounds, that's 96.6 pounds your neck has to stand up to. You may have some documentation that indicates the maximum tension your instrument is designed for. If not, sticking to tensions that are similar to standard sets is likely to be safe.
Finally, when you change string gauge, it's likely that other aspects of your instrument will also need adjustment. The bridge intonation may need adjustment. The truss rod will probably need adjustment. These are reasonably advanced jobs. There is a lot to be said for sticking with standard string sets and letting a professional set up your instrument.

How do I use string gauge tables?


Use simplecv to display videos in multiple windows

Question: I'm trying to display the output of 2 webcams in 2 windows using SimpleCV, but what I get with the following code is a sputtering combination in what appears to be 2 different sized windows, merged into one.
cam = Camera(0)
cam1 = Camera(1)
while True:
    cam.getImage().show()
    cam1.getImage().show()

I have performed the same operation successfully with C++/OpenCV, but am hoping to dev using Python/SimpleCV.
The SimpleCV docs on show() which I've found aren't very verbose. Any leads?
Answer: Sadly pygame only supports a single window which is the library we use to render the display.  You could always use some other type of library to display them separately like GTK.
Another hack is to use the side by side function:
cam = Camera(0)
cam1 = Camera(1)
while True:
    i1 = cam.getImage()
    i2 = cam1.getImage()
    i1.sideBySide(i2).show()

I should mention you could always use two JpegStreamCameras as well:
cam = Camera(0)
cam1 = Camera(1)
js = JPegStreamer()
js1 = JPegStreamer(8081)

while True:
    js.save(cam.getImage())
    js1.save(cam1.getImage())

Then in your web browser go to:
localhost:8080
localhost:8081
Each should show a separate camera.


I got infinite loop while practicing array in C++ to find reversed number

Question: Hye, Im a beginner trying to learn C++ language. This is my code that I tried to find reverse input numbers using array. Can help me point my mistakes since I always got infinite loop.
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
const int ARRAY_SIZE=50;
int size[ARRAY_SIZE];
unsigned short int i;

cout << "You may enter up to 50 integers:\n";
cout << "\nHow many would you like to enter?  ";
cin >> size[ARRAY_SIZE];

cout << "Enter your number: \n";

for (int i = 0; i < ARRAY_SIZE; i++)
{
    cin >> size[i];
}

cout << "\nYour numbers reversed are:\n";

for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
    cout << " size[i]" << " ";

}

Comment: `cin >> size[ARRAY_SIZE];` writes off the end of the array. Everything after that is undefined behaviour. This is not writing to the "array size property" of the array. This is writing to the array at index `ARRAY_SIZE`, but only `0`..`ARRAY_SIZE-1` exists.
Comment: Tip: Since you're using C++, *use* C++. `std::vector array` and then `int v; cin >> v ` is an easy way to capture single integers, then `array.push_back(v)` to add to the array.
Answer: Your infinite loop is because i is unsigned, so i >= 0 is always true.
Answer: Here's a C++-ified version:
#include <iostream>
#include <vector>

int main() {
  std::cout << "You may enter up to 50 integers:\n";
  std::cout << "\nHow many would you like to enter?  ";

  int count;
  std::cin >> count;

  // Use a std::vector which can be extended easily
  std::vector<int> numbers;

  for (int i = 0; i < count; ++i) {
    std::cout << "Enter your number: \n";

    int v;
    std::cin >> v;

    // Add this number to the list
    numbers.push_back(v);
  }

  std::cout << "\nYour numbers reversed are:\n";

  // Use a reverse iterator to iterate through the list backwards
  for (auto i = numbers.rbegin(); i != numbers.rend(); ++i) {
    // An iterator needs to be de-referenced with * to yield the value
    std::cout << *i << " ";
  }

  std::cout << std::endl;

  return 0;
}

There's many problems in your original code, but the clincher is this:
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
    cout << " size[i]" << " ";

}

Since you keep adding to i through each cycle you'll never go below zero, especially not for an unsigned short int. This should be:
for (int i = count - 1; i > 0; --i) {
   std::cout << numbers[i];
}

Presuming you have a thing called numbers instead of the bizarrely named size and the array size is count, not i, as i is generally reserved for iterators and loop indexes.


Extract Table name and Count

Question: I do have a table like this shown at input.
In this table i want to extract only this
Table Space Name and Count
<code>*******************************************************************************************************************************
Output
*******************************************************************************************************************************

TABLESPACE_NAME               Nr of parts

ACCUM_JOURNAL_ENTRIES_DATA  24
ACCOUNT_BALANCES_DATA           24
*******************************************************************************************************************************
Input
*******************************************************************************************************************************

DWSADM               ACCUMULATOR_JOURNAL_ENTRIES    M200905_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20090601000
DWSADM                                              M200906_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20090701000

TABLE_OWNER          TABLE_NAME                     PARTITION_NAME                 TABLESPACE_NAME                HIGH_VALUE
-------------------- ------------------------------ ------------------------------ ------------------------------ ---------------
DWSADM               ACCUMULATOR_JOURNAL_ENTRIES    M200907_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20090801000
DWSADM                                              M200908_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20090901000
DWSADM                                              M200909_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20091001000
DWSADM                                              M200910_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20091101000
DWSADM                                              M200911_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20091201000
DWSADM                                              M200912_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20100101000
DWSADM                                              M201001_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20100201000
DWSADM                                              M201002_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20100301000
DWSADM                                              M201003_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20100401000
DWSADM                                              M201004_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20100501000
DWSADM                                              M201005_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20100601000
DWSADM                                              M201006_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20100701000
DWSADM                                              M201007_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20100801000
DWSADM                                              M201008_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20100901000
DWSADM                                              M201009_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20101001000
DWSADM                                              M201010_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20101101000
DWSADM                                              M201011_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20101201000
DWSADM                                              M201012_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20110101000
DWSADM                                              M201101_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20110201000
DWSADM                                              M201102_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20110301000
DWSADM                                              M201103_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20110401000
DWSADM                                              M201104_ACCUM_JOU_ENT          ACCUM_JOURNAL_ENTRIES_DATA     20110501000
                     ****************************** ------------------------------
                     Nr of parts                                                24

DWSADM               ACC_ACCOUNT_BALANCES           M200905_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20090601000
DWSADM                                              M200906_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20090701000
DWSADM                                              M200907_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20090801000
DWSADM                                              M200908_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20090901000
DWSADM                                              M200909_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20091001000
DWSADM                                              M200910_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20091101000
DWSADM                                              M200911_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20091201000
DWSADM                                              M200912_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20100101000
DWSADM                                              M201001_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20100201000
DWSADM                                              M201002_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20100301000
DWSADM                                              M201003_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20100401000

TABLE_OWNER          TABLE_NAME                     PARTITION_NAME                 TABLESPACE_NAME                HIGH_VALUE
-------------------- ------------------------------ ------------------------------ ------------------------------ ---------------
DWSADM               ACC_ACCOUNT_BALANCES           M201004_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20100501000
DWSADM                                              M201005_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20100601000
DWSADM                                              M201006_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20100701000
DWSADM                                              M201007_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20100801000
DWSADM                                              M201008_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20100901000
DWSADM                                              M201009_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20101001000
DWSADM                                              M201010_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20101101000
DWSADM                                              M201011_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20101201000
DWSADM                                              M201012_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20110101000
DWSADM                                              M201101_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20110201000
DWSADM                                              M201102_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20110301000
DWSADM                                              M201103_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20110401000
DWSADM                                              M201104_ACC_ACC_BAL            ACCOUNT_BALANCES_DATA          20110501000
                     ****************************** ------------------------------
                     Nr of parts                                                24
</code>
Answer: your question is not very clear, although it seems a simple GROUP BY would work here:
<code>SELECT tablespace_name, COUNT(*) nb_of_parts
  FROM your_table
 GROUP BY tablespace_name
</code>

Extract Table name and Count


Multiple regression with raw and derived variables as predictors

Question: Extending my previous question ( Multiple regression with correlated variables ), can I do multiple regression with height, weight, waist, BMI (body mass index) and BSA (body surface area) as predictor variables on a health variable (yvar) in a large data set (N=about 7000)? Obviously, BMI and BSA are derived from height and weight, but I want to find out if correlation is greater for BMI or BSA (so that they may be better to use for prediction) than for height and weight. Will the results be valid or is there some major limitation?
Edit:
The regression runs without any error and shows that height, weight and BSA are significant predictors of yvar but waist and BMI are not significant predictors.
Comment: Have you tried to run it? Unless I'm missing something, it sounds like you'll get an error saying that BMI is a (perfect) linear combination of other predictors included in your model (I don't know what BSA is)
Comment: BSA is body surface area (also derived from height and weight). The regression runs without any error and shows that height, weight and BSA are significant predictors of yvar but BMI is not a significant predictor.
Comment: Right, @AK12's comment about the BMI term being something of an interaction term is a nice way to phrase it, I was mistaken in thinking it wouldn't run.
Answer: Assuming multicollinearity is not an issue (from the answer to your previous question), BMI and/or BSA will effectively serve as an interaction(s) between height and weight in your model, because they both incorporate height and weight into their calculations. So, does the effect of height on your health variable depend on weight (or vice-versa)? If BMI and/or BSA are significant predictors, then the answer yes.
I would still be concerned about multicollinearity in your model if you include both BMI and BSA at the same time, but as the answer to your previous question mentions, you may have enough data to make this a non-issue.


My wrists hurt after playing bass for a long time

Question: I've been playing bass for about 3 years, but only as a hobby. I've never had a teacher either. Usually I play for around 1 hour a day, sometimes up to 3 hours, but now I've got a gig coming up, so I met up with my band and practice for a whole day, two days in a row.
I didn't have any problem during the practice itself, but a few days after the practice they just hurt (after waking up, playing badminton which usually doesn't hurt either).
This has happened to me twice now. What should I do? How can I figure out if I have bad posture? Thank you.
Ps. Both my wrists hurt, but not necessarily at the same time.
Comment: I'm no bass player but do get into the habit to relax your hands when you play. So much discomfort in guitar  playing comes from unnecessary stress.
Comment: Thanks for that. It's still weird for me. I usually play metal when I practice alone, but the band only play pop/rock, so I thought I should have plenty of stamina for it.
Comment: Wristbands/taping wrists will help when playing or even when not... do extra wrist exercises regularly to strengthen them: no pain, no gain is not applicable here - when it hurts, stop and rest them. You,re likely dealing with inflammation in the wrists so, an aspirin may help. Examine your diet for acidic foods that may increase chances of inflammation in the body (acidic ph level.)
Answer: It's almost impossible to be a direct help here. We don't know what sort of stuff you're playing, how you play - low slung bass, etc., so more clues will help.
If it's your wrists, it may be because your bass is too low for your hands to reach comfortably, thus stressing your wrists. Ifd there's a lot of high energy playing, maybe you're not fit enough in the appropriate way. It may also be the stress brought on by an impending gig, which makes you squeeze the neck harder than needed, and play the strings harder than you need.
All supposition, but it may help. A whole day's practice seems over the top - to me, a rehearsal is to just polish stuff together, after each member has sorted out his own parts. The time needs to be shared between playing and other things, not solid play.
Answer: There are to many cares might be You are avoiding/omitting/not aware.
Don't use cold water on hands after playing for example. This also could cause arthritis in a long term. And definitely get instructions from a real master in case You are playing/using a wrong wrist/hand/arm/back/body position.
And practicing is like any physical exercise, should start slowly and eventually going to more intense/faster exercises. Can't immediately do a pull off from 5rd fret to 12th ;)
You can use a bandage and some unguent/ointment after playing before go sleep.
All the best with the band!
Answer: Sounds like basic tendinitis.  Your tendons are probably a little raw from all the practice before the gig.  A little rest, ice and tylenol / ibuprofen should help.  I usually rest or do a very light practice the night before a gig.
Answer: When you do something physical for an unusually long time, you will get tired and/or sore.   Maybe consult a teacher to check you aren't making it worse with bad posture.  Try to relax anything that CAN be relaxed while playing.  Again a teacher can advise.
But if you suddenly decide to run a marathon, you must expect blisters on your feet.  You knew that really, didn't you?
Answer: Play less.
Some ways you can prepare while not having your bass strapped on:

Memorize anything you need to: lyrics, chord progressions, etc.
Listen to rehearsal recordings (you should always make them), figure out what's good and what's not, take notes.
Practice any singing separately, if you have any.
If you have any rhythmic coordination issues (tricky bass rhythm, different rhythms in vocal and bass line), you can often sort those out just by e.g. tapping on a table.
Mentally practice: literally run through what you're going to play in your head.  A whole song, or a tricky passage, whatever needs it most.


How can I print only one of the inputs from a for i in range loop?

Question: x = 64
root = 0

for pwr in range(2,6):
    if x > 1:
        while root <= x:
            root += 1

            if root**pwr == x:
                print('root = ', root, ' and pwr = ', pwr)
        root = 0
    elif x < 0:
        while root >= x:
            root -= 1

            if root**pwr == x:
                print('root = ', root, ' and pwr = ', pwr)
        root = 0
    elif x == 0:
        print('There is no such pair')
        break

The inputs I receive are:
root =  8  and pwr =  2
root =  4  and pwr =  3
However, I am only looking to get the highest root answer if available.
So what I want my input to be is only:
root =  8  and pwr =  2
And also vice versa... what should I do if I only want it to display:
root =  4  and pwr =  3
Thanks!
Comment: "I cannot think of any variable to represent the best result." This doesn't make any sense. You know what a variable is. What you need to do is assign a value to it. You know what `=` does, right? Try to think about the process step by step. Use a real pencil and piece of paper and draw a diagram.
Comment: Well, do things inside the loop happen once, or multiple times? Do you want the `print` to happen once, or multiple times? Therefore, should it happen inside, or outside the loop? Now, the next question is how you figure out what it should print. Here is a hint: try using a variable to remember the *best result seen so far*. Can you see how to use that result after the loop has finished?
Comment: Not sure I fully understand the requirement but it looks as though a *break* after *print()* might be all you need
Comment: @BrutusForcus Yes! That fixed my first issue, but now how do I go about getting it to only print root = 4 and power = 3?
Comment: @KarlKnechtel Can you expand on your hint? I cannot think of any variable to represent the best result. I appreciate the first tip it makes a lot more sense now why I was printing multiple values.
Comment: you should keep results `root`, `pwr` in some other variables (ie. `max_root, max_pwr`) and later compare with new `root`, `pwr` and keep old values or replace by new values - and you should print these values only after all calculations. This way you check all values and you get only one result. OR you should keep all results on list and after all calculations filter result which you need and display it.
Answer: You should create new variables max_root, max_pwr and when you calculate root then you should check if it is bigger then max_root and replace max_root, max_pwr or keep older value.
And you should display only after all calculations
x = 64
root = 0

max_root = 0
max_pwr = 0

for pwr in range(2,6):
    if x > 1:
        while root <= x:
            root += 1

            if root**pwr == x:
                #print('root = ', root, ' and pwr = ', pwr)
                if root > max_root:
                    max_root = root
                    max_pwr = pwr
        root = 0
    elif x < 0:
        while root >= x:
            root -= 1

            if root**pwr == x:
                #print('root = ', root, ' and pwr = ', pwr)
                if root > max_root:
                    max_root = root
                    max_pwr = pwr

        root = 0
    elif x == 0:
        print('There is no such pair')
        break

# after `for`-loop

print('root = ', max_root, ' and pwr = ', max_pwr)

Similar way you can do for other result but you may need < instead of > in line root > max_root and you need to set big max_root at start - ie. 99999.
x = 64
root = 0

max_root = 99999
max_pwr = 0

for pwr in range(2,6):
    if x > 1:
        while root <= x:
            root += 1

            if root**pwr == x:
                #print('root = ', root, ' and pwr = ', pwr)
                if root < max_root:
                    max_root = root
                    max_pwr = pwr
        root = 0
    elif x < 0:
        while root >= x:
            root -= 1

            if root**pwr == x:
                #print('root = ', root, ' and pwr = ', pwr)
                if root < max_root:
                    max_root = root
                    max_pwr = pwr

        root = 0
    elif x == 0:
        print('There is no such pair')
        break

# after `for`-loop

print('root = ', max_root, ' and pwr = ', max_pwr)

Other method to create list for all results and after calculations filter results and display only results which you need.
x = 64
root = 0

all_results = []

for pwr in range(2,6):
    if x > 1:
        while root <= x:
            root += 1

            if root**pwr == x:
                #print('root = ', root, ' and pwr = ', pwr)
                all_results.append( [root, pwr] )
        root = 0
    elif x < 0:
        while root >= x:
            root -= 1

            if root**pwr == x:
                #print('root = ', root, ' and pwr = ', pwr)
                all_results.append( [root, pwr] )
        root = 0
    elif x == 0:
        print('There is no such pair')
        break

# after `for`-loop

#print(all_results)

max_result = max(all_results, key=lambda x:x[0])
max_root, max_pwr = max_result
print('MAX: root = ', max_root, ' and pwr = ', max_pwr)

min_result = min(all_results, key=lambda x:x[0])
min_root, min_pwr = min_result
print('MIN: root = ', min_root, ' and pwr = ', min_pwr)


Write permissions for Network service in network folder

Question: I'm trying to setup Team Foundation Server (TFS) authomatic backups, and to do that I need to set up a network folder for database backups. When trying to set folder path I receive a message from TFS saying SQl Server service has not permissions for this folder.
Looking in services I see SQLExpress service is run under Network service account, and lookin in that remote folder from my computer I see Network service has all permissions for that folder, so I can't grant any more permissions from this computer. Going to the othe computer I can't (or don't know how to do it) assign permission to Network service account from the other computer.
What do I need to do?
Comment: Then you can't do it that way. Network Service = "Computer Account" (COMPUTER$) on remote systems
Comment: Did you try assigning permissions to to computer account (i.e, domain\computername$)?
Comment: I think network is not configured under a domain
Comment: My advice would be to put the backup on the local machine and use something like Cobian Backup to push it someplace else.
Comment: @NathanC I like Cobian Backup but in this case it's not possible, TFS stores repositories in SQLServer not files and it's SQLServer Service which needs permissions to write in that folder, and plus, TFS requires backup folder not to be local
Comment: You can use SQL Management Studio to create a job that backs up the database manually. You don't *have* to use TFS to do your backup.
Answer: If I understand that this isn't on a windows domain, then:

Create a local administrative level account (say "TFSSQL")
Set the SQL Service to run under that account
Start up SQL again and make sure TFS is running fine
On the remote computer, add `TFSCOMPUTERNAME\TFSSQL" as having Modify rights to the share and NTFS permissions of the backup shared folder
Back on the TFS server, log out and log back in as TFSSQL
Go in and run the backup wizard again.

That should do it.