Help with understanding why the distribution of the score difference isn't a normal distribution?

Question: The score difference is the winning score minus the losing score. I'm using data from 1230 NBA games this season.
My thinking is that the winning and losing score are two independent random variables, since if one team gets 100 points, the other team's chance of getting 100,101,102... points doesn't really change. So since they are two RV (and their distribution, the distribution of the winning/losing score looks fairly normal) I expected the distribution of the score difference to be normal as well. What I got isn't normal, however, and I'm a bit confused as to why it's like that[]Distribution of the 1
[]Distribution of the losing score2

EDIT: so I thought about it a bit, is because the game difference can only be positive, thus I'm missing the negative half of the distribution of score difference? The last graph does look like the right/positive half of a normal distribution.
Comment: You're not looking at score of team A minus score of team B here but the higher score (by whichever team) minus the lower score (by whichever team). Rather than being the distribution of $Y-X$ it's the distribution of $\max(X,Y) - \min(X,Y)$ you're looking at, or equivalently, $|Y-X|$. The distribution of $Y-X$ might look reasonably close to normal (it obviously isn't, but it can look close) -- but its absolute value typically won't look close to normal; it will be right skew.
Comment: Try subtracting the away team score from the home team score, as you suggested in your edit.
Answer: It is true that the sum of normal variables is itself normal, but that is only true if the two are independent. Your variables are not independent - if we know that the losing team scored $X$, then we have gained a lot of information about the winning team's score; specifically that it must be more than $X$. Similarly, if we know the winning's team score, we have gained a lot of information about what the losing team's score is not likely to be. This lack of independence means that the resulting distribution is definitely not normal, and will never be negative.
Comment: Most likely - it's not clear what distribution your variable has, but it's probably not a truncated normal distribution.
Comment: Ooooooh ok. Looking like half the normal distribution is just a coincidence?
Comment: Both winning and losing scores will be correlated.  This is because the pace of the game determines the total number of points scored.
Comment: an extension... https://stats.stackexchange.com/questions/30159/is-it-possible-to-have-a-pair-of-gaussian-random-variables-for-which-the-joint-d  for examples that the sum of normal variables need not be itself normal.


How to alter auto-complete exposed filter programmatically?

Question: I created a views to show parent and child term together using autocomplete expose filter .. but its show only one child. I have same child for two different parent.but its show only one child.
how to change this programmatically using view query alter. I need such type:
<code>Parent . Parent-1
           locality-1
           locality-2
         parent-2
           locality-2
           locality-4
</code>
I need such type of result on autocomplete expose filter.
Comment: Do you only want to do it with hook_views_query_alter?
hook_form_alter would also be an option, I could provide a code example for that.
Comment: It would be great help.
Comment: I have try lot of module .. but still not find a way to achive this using module. So finally I want to fix this via custom code.
Comment: Please provide me code example.
Comment: Hey there, I will do, need a little time though. :-)
Comment: Hello there, I am reading your question again. Just to be sure, you need a taxonomy exposed filter in a view that shows content? Or something else?
Comment: yes I need taxonomy autocomplete expose filter . with parent and child term.
Comment: Okey, one last question. If the child term has many parents, then selecting any of the instances of that child term will have the same filtering effect. Is that what is expected?
Comment: we have same child with different parent ..
Comment: did you have a look at the answer? would it work for you?
Answer: Here is a possible answer to this problem.
First of all, a litte visual.

To get this working you need the following:

Configure your View to display the exposed taxonomy filter as a dropdown. autcomplete will not work because you cannot have multiple entries with the same key in the generated JSON array.
Optional: Install and configure the Chosen module [https://www.drupal.org/project/chosen] to get your dropdown to render nicely and offer autocomplete options.

You will also need this JS library for Chosen to work => [https://github.com/harvesthq/chosen]

Optional: You can finally use some custom code for formatting the presentation of your list, here is a sample minimal module that adds the special arrow that you see in the screenshot.

define('YOUR_CUSTOM_TAXONOMY_AUTOCOMPLETE_PATH', 'mycustompath/1');
define('YOUR_EXPOSED_FILTER_MACHINE_NAME', 'field_tags_tid');

/**
 * Implements hook_form_alter()
 */
function se_form_alter(&$form, &$form_state, $form_id) {
  if( $form_id == 'views_exposed_form' ){
    if(isset($form[YOUR_EXPOSED_FILTER_MACHINE_NAME]) &&
    $form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#type'] == 'select'){
      $form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#options'] = _custom_update_options_for_taxonomy($form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#options']);
    }
  }
}

/**
 * Function that update select options for taxonomy filter
 *
 */
function _custom_update_options_for_taxonomy($options = array()) {
  $current_parent = '';
  foreach( $options as $i=>$option ) {
    if( is_int($i) && isset($option->option) && is_array($option->option) ) {
      $option_arr = $option->option;
      $tids = array_keys($option_arr);
      $tid = reset($tids);
      // is this a child of the previous parent
      if( strpos($option_arr[$tid], '-') === 0 && $current_parent != '') {
        $option_arr[$tid] = preg_replace('/^-/', ' ⤷ ', $option_arr[$tid]);
        $option->option = $option_arr;
      }
      // this is a parent node
      else {
        $current_parent = $option_arr[$tid];
      }
    }
  }
  return $options;
}

Hope this help some!


How do configure Zend_Form to use array notation?

Question: I'm having difficulty configuring Zend_Form. I have a Zend_Form sub-class. The form has some required information and some additional information. I want the additional information to be accessible via an array. The submitted data will look something like this:
$formData['required1']
$formData['required2']
$formData['addiotnalData']['aData1']
$formData['addiotnalData']['aData2']

I've Googled this and tried all the suggestions I've found (using subForms and setting the  Zend_Form::setIsArray($flag) and Zend_Form::setElementsBelongTo($array) methods), but have not figured out how to do this.
What am I doing wrong? How do I set the names of form elements so that I can access the data with array notation?
Answer: Sorted it! The problem is a custom decorator that was being used.
//In
$subForm = new Form_SubForm(); //this can be a Zend_Form or Zend_Form_SubForm
$subForm->setIsArray(true);
$this->addSubForm($subForm, 'subform');

Elements will be rendered with a id of subform-elementname and a name of subform[elementname].
Comment: Hi, I have the same problem and made the changes you have told. But this is not working according to my exceptions. what about custom decorators???
Answer: To expand on the answer because $form->setIsArray(TRUE) was not working with my custom decorator for elements. My custom ViewScript decorator was needed for rendering the Zend_Form_Element.
The problem, it was rendering the element name with $this->element->getName(). I had to use $this->element->getFullyQualifiedName() in the ViewScript decorator script.


SQL statement to update a column

Question: I have a Table T1 with following values

I need a result table with additional column which is the average of upto date.
i.e.,
x1= 1000.45
x2= (1000.45+2000.00)/2
x3= (1000.45+2000.00+3000.50)/3
x4= (1000.45+2000.00+3000.50+4000.24)/4
The result table should look like the following:

I need to write SQL statement in Oracle database to add a column to result table with column values x1, x2, x3, x4.
Comment: "I need to write SQL statement" yeah cool, so what have you written?
Comment: @Gonzalo Thank u for editing my question. I'm new here and does not know the format
Comment: See if [this article](http://www.adp-gmbh.ch/ora/sql/analytical/rollingavg.html) gives you some ideas.
Comment: Please read [**How to ask**](http://stackoverflow.com/help/how-to-ask)
And [**How to create a Minimal, Complete, and Verifiable example.**](http://stackoverflow.com/help/mcve)
We need sample data and desire output to find an answer faster, otherwise we will be wasting time guessing what you need. You also could create your schema with data using **http://www.sqlfiddle.com** . Even when pictures are cool is very hard to transcript so include code text.
Answer: You need to use an analytic function for this.  My untested SQL is as follows:
SELECT
 date,
 division,
 sum_sales,
 AVG( sum_sales ) OVER ( ORDER BY date ROWS UNBOUNDED PRECEDING )
FROM
 table;

date is a reserved word in Oracle, so if you are using that as your real column name you will need to include it in quotes.
Comment: @anwaar_hell No, there is no need for a GROUP BY with an analytic function.  There is not grouping because every original row is represented in the result.
Answer: select date,division,sum_sales,avg(sum_sales) over ( order by sum_sales ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
from table
group by date,division,sum_sales

Answer: You need to use AVG function OVER ordering by date. As each row is an aggregation result of all the preceding rows, you need to define the window of the aggregation as UNBOUNDED PRECEDING
By following these guidelines, the resultant statement would be like:
SELECT date_d,
       division,
       sum_sales,
       AVG(sum_sales)
         over (
           ORDER BY date_d ROWS unbounded preceding ) avrg
FROM   supplier;

You can test that in FIDDLE
Good two pieces of information about analytical functions in these two articles:
Introduction to Analytic Functions (Part 1)
Introduction to Analytic Functions (Part 2)

SQL statement to update a column


Desabilitar datas com evento (fullcalendar)

Question: Eu tenho o seguinte código utilizando o plugin "fullcalendar" e eu precisaria desabilitar as datas que tenham evento cadastrado. Eu fiz um cadastro com o dayClick do plugin e depois listei os cadastros com ajax.
var calendar = $("#calendar").fullCalendar({
            header: {
              left : "prev,next,today",
              center: "title",
              right: "month,listMonth"
            },
            buttonText: {
              listMonth: "Reservas"
            },
            height: 500,
                  navLinks: false, // can click day/week names to navigate views
                  editable: false,
                  eventLimit: true, // allow "more" link when too many events
            showNonCurrentDates: false,
            slotEventOverlap: false,
            // validRange,
            // dateIncrement,
            dayClick: function(date , view){
              $("#diaReserva").html(date.format('DD/MM/YYYY')+"?");
              $("#cadastroDataReserva").val(date.format());
              $('#confirmacaoReserva').modal();
            },
            defaultDate: new Date(),
            validRange: {
              start: moment().add('days',-1),
            },
            viewRender: function(view, element) {
              curdate = new Date();
              viewdate = new Date(view.start);
              // PREV - force minimum display month to current month
              if (new Date(viewdate.getFullYear(), viewdate.getMonth() + 1, 1).getTime() <= new Date(curdate.getFullYear(), curdate.getMonth(), 1).getTime()){
                $('.fc-prev-button').prop('disabled', true);
                $('.fc-prev-button').css('opacity', 0.5);
              }else {
                $('.fc-prev-button').prop('disabled', false);
                $('.fc-prev-button').css('opacity', 1);
              }
              // NEXT - force max display month to a year from current month
              if (new Date(viewdate.getFullYear(), viewdate.getMonth() + 1).getTime() >= new Date(curdate.getFullYear() + 1, curdate.getMonth() + 1).getTime()){
                $('.fc-next-button').prop('disabled', true);
                $('.fc-next-button').css('opacity', 0.5);
              }else {
                $('.fc-next-button').prop('disabled', false);
                $('.fc-next-button').css('opacity', 1);
              }
            },
            selectable: false,
            selectOverlap: false,
            events: "buscarReservas.php?idCondominio="+idCondominio,
          });

Então quando eu cadastro um evento ele não pode deixar eu cadastrar outro no mesmo dia por estar desabilitado
Answer: utilize o validRange:{start: new Date().toISOString().substring(0,10)}, essa option mostrara dias a partir da data atual. espero ter ajudado;


How to model 2 correlated Geometric Brownian Motions?

Question: Let's say we have 2 GBM processes:
$$S_1(t)=S_1(0)\cdot \exp{(\mu_1t-\frac{1}{2}\sigma_1^2t+\sigma_1\cdot W(t))}\text{  and  } S_2(t)=S_2(0)\cdot \exp{(\mu_2t-\frac{1}{2}\sigma_2^2t+\sigma_2\cdot W(t))}$$
such that $\mathbb{E}[dW_1;dW_2]=\rho$.
How can I model them together? Formulas above won't take the correlation into account. Since $S(t)$ are meant to be stock prices, I can look at daily returns directly as:
$$\frac{S(t+1)-S(t)}{S(t)}=\exp{(\mu-\frac{1}{2}\sigma^2+\sigma \cdot N(0;1))}-1=\exp{(N(\mu-\frac{1}{2}\sigma^2;\sigma^2))}-1$$
which is close to normal (transposed lognormal in fact). If it was in fact normally distributed then I would use 2-D $N(M;\Sigma)$ with $M=(\mu_1-\frac{1}{2}\sigma_1^2;\mu_2-\frac{1}{2}\sigma_2^2)$ and $\Sigma$ as the covariance matrix. But I want to be precise with the model and not assume (incorectly) that returns are normal if prices are GBM. So I'm struggling on how to include the correlation/covariance in the direct formulas for $S_1,S_2$.
Comment: You seem to have a typo. For GBM you should have $S(t) = S(0)\exp ((\mu - 0.5 \sigma^2) {\color{red} t} + \sigma W(t))$.
Answer: Let $B_1$ and $B_2$ be independent Brownian motions. Set $W_1 = B_1$ and $W_2 = \rho B_1 + \sqrt{1-\rho^2} B_2$. Then $W_1$ and $W_2$ are correlated Brownian motions with correlation coefficient $\rho$.
In your model for correlated geometric Brownian motion, you may let $S_1$ be driven by $W_1$ and $S_2$ be driven by $W_2$, to obtain:
$$\begin{align*}
S_1(t) &= S_1(0) \exp \left( (\mu_1 - 0.5\sigma_1^2)t + \sigma_1 W_1(t) \right) \\
S_2(t) &= S_2(0)\exp \left( (\mu_2 - 0.5\sigma_2^2)t + \sigma_2 W_2(t) \right)
\end{align*} \\
$$
Or, in terms of $(B_1, B_2)$,
$$\begin{align*}
S_1(t) &= S_1(0) \exp \left( (\mu_1 - 0.5\sigma_1^2)t + \sigma_1 B_1(t) \right) \\
S_2(t) &= S_2(0)\exp \left( (\mu_2 - 0.5\sigma_2^2)t + \sigma_2 (\rho B_1(t) + \sqrt{1-\rho^2} B_2(t)) \right)
\end{align*} \\
$$
Comment: Thank you :) Two more issues: when simulating $(S_1(t_0);S_2(t_0))$ for some given $t_0$ I will treat $B_1(t_0)$ as a sample from $N(0;t_0)$, do I have to use the exact same sample result for $B_1(t_0)$ in $S_1(t_0)$ and in $S_2(t_0)$? Also: let's say I have historical data of prices I'm about to model. How can I get the $\rho$ from them? Would the correlation between those historical prices be a good assumption for $\rho$ used later in your formulas or do I have to look at correlation between daily difference quotients (returns)?
Comment: @MichałDąbrowski You would need to sample two independent normal random variables $(B_1, B_2)$ and then correlate them using the formula for $(W_1, W_2)$. For estimating the question of estimating $\rho$, it would be best to ask this as a separate question so I can answer in detail. In short, you would want to filter out the driving Brownian motions and then compute $\sum (W_{s^\prime}^1 - W_s^1) (W_{s^\prime}^2 - W_s^2)$, as this is a consistent estimator for the covariation, from which you can read off $\rho$.
Comment: Yeah, it would be something in a form of:
$$W(t)=\frac{\log{\frac{S(t)}{S(0)}}-(\mu-\frac{1}{2}\sigma^2)\cdot t}{\sigma}$$
but I'm not sure what do you mean by $W_s$ and $W_{s'}$, are those indexes of different time moments for example $s'=s+1$? If so then I understand everything, thanks a lot for that :)
Comment: @MichałDąbrowski Yes by $s^\prime$ I mean the successor of $s$ (which could very well be $s+1$).


How do you get Product Variation Type fields and display modes to show up when displaying Products in a View?

Question: I've created a Product Variation Type for all my products, all of which have the following custom fields: Display Title, Subtitle, and Top Rated Product? (boolean checkbox):

When setting up a View to display my Products, I am unable to access any of these fields, regardless of whether I choose "Fields" or "Content" under "Format > Show:". Nothing shows up:

I also can't access any of the display modes I created for Products — not even the default "Cart" display mode shows up here:

Am I missing something that's required to get this working properly? I can only choose "Fields", "Product", or "Search Results", and like I said, even when I choose "Fields", I can't find any of the custom fields for my Products.
Answer: It turns out that I had to add a relationship to Product Variation Type in order for those fields to show up. Hope this helps others!


AWS RDS endpoint address

Question: Is the endpoint address of RDS instances unique across whole of AWS infrastructure irrespective of datacenter/VPC?
e.g:
<code>aws.xxxx.yyy.rds.amazonaws.com
</code>
Answer: Every unique RDS instance has a unique endpoint, regardless whether the instance is public or private.
The RDS endpoint is comprised of:

The selected RDS instance ID,
An account + region specific hash,
The region ID
".rds.amazonaws.com"

The account + region specific hash is constant for all RDS instances in the same region and the same AWS account.
Comment: a DB engineer during an AWS support call verified that the `account + region specific hash` string is _" is region specific and is static"._ in case you wondering if it would change for your region and account (and service).
Answer: Yes it's unique. It has to be since you can make the database publicly accessible and connect to it directly over the Internet via the endpoint address.
Comment: Thanks. But if it is not publicly accessible, even then is it true?
Comment: Yes. The endpoint doesn't change based on it being public or not.

AWS RDS endpoint address


Split dictionary into 2 dictionaries by specifying which key-value pair is to be inserted in new dictionary

Question: Suppose there is a  dictionary as follows:
d={'name': 'xyz', 'age':21, 'contact':2398402093, 'address': 'new_street', 'score':87}

I need to divide them into 2 dictionaries where the second one contains name and contact and the first one contains the rest.
This is what I need:
d={'age:21, 'address': 'new_street', 'score':87}
d1={'name':'xyz','contact':2398402093}

EDIT:
I tried splitting them based on length though I specifically want to split it based on the keys but even with length I get this error:
d={'name': 'xyz', 'age':21, 'contact':2398402093, 'address': 'new_street', 'score':87}
d1 = dict(d.items()[len(d)/2:])
d2 = dict(d.items()[:len(d)/2])
print(d1)
print(d2)

Error:
TypeError                                 Traceback (most recent call last)
<ipython-input-3-66f097c85c58> in <module>
      1 d={'name': 'xyz', 'age':21, 'contact':2398402093, 'address': 'new_street', 'score':87}
----> 2 d1 = dict(d.items()[len(d)/2:])
      3 d2 = dict(d.items()[:len(d)/2])
      4 print(d1)
      5 print(d2)

TypeError: 'dict_items' object is not subscriptable

How do I split it based on the keys I want to put in the different dictionaries?
Comment: What have you done so far ?
Comment: What have you tried? What specifically do you need help with?
Comment: Try [this](https://stackoverflow.com/questions/53560160/python-splitting-dictionary-into-smaller-dictionaries-by-keys-tuple)
Comment: Your dictionary definition isn't valid Python.
Answer: you can use .pop to get the value and also delete the key in a single operation:
d = {"name": "xyz", "age": 21, "contact": 2398402093, "address": "new_street", "score": 87}

keys = ["name", "contact"]

d1 = {}
for key in keys:
    d1[key] = d.pop(key)

print(d)
print(d1)

Output:
{'score': 87, 'address': 'new_street', 'age': 21}
{'name': 'xyz', 'contact': 2398402093}

Answer: Here's one way using a generator function to pop the entries of interest from the dictionary:
d1 = {'name':'xyz', 'age':21, 'contact':2398402093, 'address': 'new_street', 'score':87}

def fun(d, pop):
    for i in pop:
        yield (i, d.pop(i))

d2 = dict(fun(d1, ['age', 'contact']))

print(d1)
# {'address': 'new_street', 'name': 'xyz', 'score': 87}

print(d2)
#  {'age': 21, 'contact': 2398402093}

Answer:
d={'name': 'xyz', 'age':21, 'contact':2398402093, 'address': 'new_street', 'score':87}

keys = {'name', 'contact'}

d1 = {k:v for k, v in d.items() if k in keys}

d2 = {k:v for k, v in d.items() if k not in keys}

d1
{'contact': 2398402093, 'name': 'xyz'}

d2
{'address': 'new_street', 'age': 21, 'score': 87}


How to add 1000 nodes of the same content type in just one step?

Question: I need some advice with the following situation:
I have a content type called: "Flats".
I have to add 1000 nodes for this content type.
The only field I need to complete for all of them is the 'title'
I have the 1000 titles in a comma-separated-value format file called: title.csv
Is there any way to upload this file and add all the nodes in just one step.
Thanks
Comment: Which version of Drupal?
Answer: Feeds module will also allow you to import content/create nodes via CSV.
Comment: yes is is arbitrary, as long as it is unique to that 'flat'. If you will never need to re-import that 1,000 nodes again, it is optional.
Comment: It looks fine. I'll try it.
Comment: Just a question: what is GUID field?
Comment: Feeds can use this ID as an externally supplied unique ID that it recognizes so that it can updated the nodes it creates based on this ID.
Comment: ok, then it could be arbitrary? Let's say 'my guid' or '1234'
Answer: If it's sample data, you can use the Devel module. If you want to import data that is in some file or db you can use node_save(). If the data is exported from another Drupal installation, you can use the Node Import module.
Comment: I need to importa node from csv file. The right module is **Feeds module** but its documentations is really poor. Found a screencast but for d6.
Answer: You can try Node Import that supports CSV files
Comment: I forgot to mention that it is for drupal 7. Node import is not available for d7


HTML Viewer for FireMonkey

Question: Is there a HTML Viewer for FireMonkey like this (VCL): http://code.google.com/p/thtmlviewer/downloads/list? It will be great if it has a highlighting feature.
Added
I found later:
About TidHttp, mshtml, ActiveX, COMObj in Firemonkey (Delphi)
https://forums.embarcadero.com/thread.jspa?threadID=60670
Answer: Take a look at Chromium Embedded.
Answer: you can use TwebBrowser that under android is a wrap of chromium embded. it's also a native android control
Comment: Do you still recommend using TWebBrowser for this?

HTML Viewer for FireMonkey


Given numbers $1$ to $3n$, construct $n$ equations of the form $a + b = c$ or $a \times b = c$ such that each number is used exactly once.

Question:
Given numbers $1$ to $3n$, construct $n$ equations of the form $a + b = c$ or $a \times b = c$ such that each number is used exactly once.

For example:
n=1 => 1+2=3
n=2 => 1+4=5, 2x3=6
n=3 => 4+5=9, 1+7=8, 2x3=6

The question is, does a solution exist for every n?
I tried writing a basic program and it becomes too slow after n = 14. Here are the solutions I have so far:
1 ['1+2=3']
2 ['2*3=6', '1+4=5']
3 ['4+5=9', '1+7=8', '2*3=6']
4 ['3+6=9', '1+10=11', '4+8=12', '2+5=7']
5 ['2+8=10', '3+6=9', '1+13=14', '5+7=12', '11+4=15']
6 ['3*5=15', '2+8=10', '4+14=18', '6+11=17', '7+9=16', '1+12=13']
7 ['6+12=18', '3*5=15', '7+10=17', '1+20=21', '4+9=13', '2+14=16', '8+11=19']
8 ['8+14=22', '6+12=18', '7+10=17', '2+19=21', '1+15=16', '11+13=24', '4+5=9', '3+20=23']
9 ['6+19=25', '8+14=22', '4+13=17', '2+18=20', '1+26=27', '3+7=10', '9+15=24', '5+16=21', '11+12=23']
10 ['6+19=25', '14+15=29', '11+17=28', '4+26=30', '2+18=20', '1+21=22', '3*9=27', '8+16=24', '5+7=12', '10+13=23']
11 ['10+23=33', '6+19=25', '14+15=29', '11+17=28', '4+26=30', '2+18=20', '5+27=32', '1+12=13', '9+22=31', '3*7=21', '16+8=24']
12 ['10+23=33', '3+29=32', '6+19=25', '15+21=36', '11+17=28', '8+14=22', '4+16=20', '7+27=34', '2*12=24', '1+30=31', '5+13=18', '9+26=35']
13 ['10+23=33', '3+29=32', '7+30=37', '6+19=25', '5+34=39', '15+21=36', '11+17=28', '18+20=38', '4+31=35', '1+26=27', '9+13=22', '8+16=24', '2+12=14']
14 ['10+23=33', '4+37=41', '3+29=32', '9+25=34', '15+21=36', '11+17=28', '8+14=22', '6+24=30', '13+27=40', '5*7=35', '2+18=20', '1+38=39', '12+19=31', '16+26=42']

Here's the code for the program:
def main(n):
    r = set(range(1, n*3+1))
    print(n, solve(n, r, []))

def solve(n, lst, solution):
    if not lst:
        if len(solution) != n:
            return False
        return solution
    cs = set(combinations(lst, 3))
    for c in cs:
        valid_solution = valid(c)
        if valid_solution:
            new_solution = solution + [valid_solution]
            result = solve(n, set(lst) - set(c), new_solution)
            if result:
                return result
    return False

def valid(lst):
    a = lst[0]
    b = lst[1]
    c = lst[2]
    if a + b == c:
        return "%s+%s=%s" % (a, b, c)
    if a * b == c:
        return "%s*%s=%s" % (a, b, c)
    return False
```

Comment: There was a similar question https://math.stackexchange.com/questions/4179825/for-which-n-in-bbb-n-can-we-divide-1-2-3-3n-into-n-subsets-each-wi/4186633?noredirect=1#comment8689058_4186633
Comment: This is a special case of the problem known as "[exact cover by 3-sets](https://en.wikipedia.org/wiki/Exact_cover)".  The "3-sets" here are the triples $\{ a, b, c\}$ where $a+b=c$ or $a×b=c$.  Although no good methods are known to solve the exact cover problem in general, algorithms to solve it often run quickly in practice and would work for your special case.
Comment: If you have a solution for $n$ using only addition, you can get a solution for $4n$ using only addition.

> 1. Double all the numbers from the solutionvto $n$.  That uses all the even numbers up to $6n$.
> 2. $(2k-1)+(9n+1-k)=(9n+k),k=1..3n$
Comment: http://plover.com/~mjd/misc/x3c.txt contains a Python program that generates one or more solutions, and is fast enough to use for at least $n$ up to 60.  For example, here's a solution for $n=39$, which took 6 seconds on my laptop: `[(10, 23, 33), (2, 18, 20), (1, 12, 13), (3, 22, 25), (11, 16, 27), (6, 32, 38), (5, 24, 29), (15, 21, 36), (7, 30, 37), (8, 26, 34), (4, 35, 39), (14, 17, 31), (9, 19, 28)]`.  The `(10, 23, 33)` means $10+23+33$ and similarly the others.  I hope you find it instructive.
Comment: Tweak my earlier method to get a solution for $4n+1$.  Then you can recurse to get a solution whenever $n$ in base 4 contains only 0s and 1s.  For example 1,4,5,16,17,20,21.  That gives $2^k$ solutions for $n\lt4^k$
Comment: Let the $a$ be the numbers from $1$ to $n$, then the $b$ and $c$ form a Skolem set.  Thorall Skolem showed in 1957 there is a suitable set of $b$ and $c$ whenever $n$ is a multiple of $4$, or one more than a multiple of $4$.  See https://en.wikipedia.org/wiki/Langford_pairing
Comment: See also https://oeis.org/A014552 A Langford pairing for $n-1$ gives a Skolem set for $n$ by putting $b_1$ and $c_1=b_1+1$ at either end of the interval.
Comment: o that's cool! how did you come up with that?
Comment: @MJD oh interesting! Didn't know this fit into a bigger kind of problem. I came up with it based on a dream I had :P Your approach of generating all the solutions is helpful, I'll play around with it and see if there are any other patterns.
Comment: Oh nice! Based on this @ricky-tensor looks like addition-only solution always exist for n=0, 1 mod 4
Answer: Thinking about multiplication sounds hard, so I'll try with just addition.
In the equation $a+b=c$ we'll say that $a,b$ are "left numbers" and $c$ is a "right number". Let $L$ be the set of left numbers and $R$ be the set of right numbers. Then $|L|=2n$ and $|R|=n$.
By adding all the equations together, we have:
$$
\sum_{l\in L} l= \sum_{r\in R}r
$$
The sum of all the numbers is:
$$
\sum_{k=1}^{3n}k = \frac{3n(3n+1)}{2} = \frac{9}{2}n^2+\frac{3}{2}n
$$
This is just the sum of left and right numbers, so:
$$
\frac{3n(3n+1)}{2} = \sum_{l\in L} l + \sum_{r\in R}r = 2\sum_{l\in L}l = 2\sum_{r\in R}r
$$
So:
$$
\sum_{r\in R}r = \frac{3n(3n+1)}{4}
$$
For $n=0,1\mod 4$ this formula results in an integer, but for $n=2,3\mod 4$, it results in a non-integer. So the task is impossible to do using only addition for $n=2,3\mod 4$.
Are the remaining cases possible? I haven't been able to prove that there's always a solution for $n=0,1\mod 4$, though it seems like there is. This C code can quickly find solutions using only addition for $n$ up to about 60.
#include <stdio.h>

#define N 60

char used[N+1];

// return 0 if impossible to solve, 1 otherwise
// m is the maximum unused number, all other state is saved in "used"
int solve(int m) {
    while (used[m]) {
        m--;
        if (m == 0) return 1; // all numbers used, solving successful
    }
    for (int k = (m-1)/2; k >= 1; k--) { // counting down is much faster than couting up! (a solution that splits m nearly evenly is more likely to be correct)
        if ((!used[k]) && (!used[m-k])) {
            used[k] = 1;
            used[m-k] = 1;
            used[m] = 1;
            if (solve(m)) {
                printf("%d+%d=%d  ", k, m-k, m);
                return 1;
            }
            used[k] = 0;
            used[m-k] = 0;
            used[m] = 0;
        }
    }
    return 0;
}

int main() {
    for (int n = 1; n <= N; n++) {
        printf("\n%d:\n", n);
        if (n % 4 > 1) {
            printf("impossible\n");
            continue;
        }
        int m = 3*n;
        for (int i = 1; i <= m; i++) {
            used[i] = 0;
        }
        solve(m);
        printf("\n");
    }
}

Comment: that's a cool proof to show that multiplication is needed for n = 2,3 mod 4! thanks for the clear explanation!


Word 2013 VB script to loop through document and change styles

Question: I need a script which iterates through a word document and changes the style of paragraphs following a Headline style or an Image to a custom style without first line indent.
How do I loop through the paragraphs/headers/items in a word document? And how do I get the style? And how do I set the style afterwards?
The Goal is simple: I want the first line of a paragraph be indented, but not if the paragraph is following a Header line or image. And since this is a large document and I get those quite often I'd like some Kind of Automation and not try to do this by Hand.
So I'd like to write a script which is iterating through the paragraphs and changes the style from "paragraph" to "paragraph without indent" when it is after a header style or image.
Answer: Here is some basic code to get you started here.  Unfortunately, the Paragraph.Style parameter doesn't distinguish between text and images, but you can check and see if a Paragraph.Range object has any InlineShapes, which are images.
Sub indentParas()
    Dim doc As Document
    Set doc = ActiveDocument
    Dim para As Word.Paragraph
    Dim i As Boolean
    i = False
    For Each para In doc.Paragraphs

        If i = False Then
            para.IndentCharWidth 4
        End If

        If para.Range.InlineShapes.Count > 0 Then
            i = True
        ElseIf Left(para.Style, 7) = "Heading" Then
            i = True
        Else
            i = False
        End If
    Next
End Sub

Note: this is tested in Word 2010.
Comment: Ah yes, this was a good starting point to create my solution, thanks!!


power series for $\frac1{x^2+x+1}$

Question: So I am trying to find the sequence $(a_n)_{n\geq0}$ such that
$$\frac1{x^2+x+1}=\sum_{n\geq0}a_nx^n$$
My attempts:
I defined $$A(x)=\frac1{x^2+x+1}$$
Hence $$A(x)=\sum_{n\geq0}a_nx^n$$
And so $$(x^2+x+1)\sum_{n\geq0}a_nx^n=1$$
$$\sum_{n\geq0}a_nx^{n+2}+\sum_{n\geq0}a_nx^{n+1}+\sum_{n\geq0}a_nx^n=1$$
$$\sum_{n\geq0}a_n(x^{n+2}+x^{n+1}+x^n)=1$$
$$a_0(x^2+x+1)+\sum_{n\geq1}a_n(x^{n+2}+x^{n+1}+x^n)=1$$
$x=0$:
$$a_0=1$$
So
$$x^2+x+1+a_1(x^3+x^2+x)+\sum_{n\geq2}a_n(x^{n+2}+x^{n+1}+x^n)=1$$
$$\frac{x^2+x+1+a_1(x^3+x^2+x)+\sum_{n\geq2}a_n(x^{n+2}+x^{n+1}+x^n)}x=\frac1x$$
$$x+1+a_1(x^2+x+1)+\sum_{n\geq2}a_n(x^{n+1}+x^{n}+x^{n-1})=0$$
$x=0$:
$$a_1=-1$$
One more time:
$$x^2+x+1-x^3-x^2-x+a_2(x^4+x^3+x^2)+\sum_{n\geq3}a_n(x^{n+2}+x^{n+1}+x^n)=1$$
$$-x^3+a_2(x^4+x^3+x^2)+\sum_{n\geq3}a_n(x^{n+2}+x^{n+1}+x^n)=0$$
Divide both sides by $x^2$:
$$-x+a_2(x^2+x+1)+\sum_{n\geq3}a_n(x^{n}+x^{n-1}+x^{n-2})=0$$
$x=0$:
$$a_2=0$$
How do I find $a_n$? Am I doing things right so far? Thanks.
Answer: \begin{align}
\frac1{1+x+x^2} &= \frac{1-x}{1-x^3} \\
&= \frac1{1-x^3}-x\left(\frac1{1-x^3} \right)\\
&= \sum_{i=0}^\infty x^{3i}-x\sum_{i=0}^\infty x^{3i}\\
&=\sum_{i=0}^\infty x^{3i}-\sum_{i=0}^\infty x^{3i+1}\\
\end{align}
Comment: This is the one that should be marked as accepted answer.
Answer: Another way of doing this is to let the roots of $1+x+x^2=0$ be $a$ and $b$ so that $1+x+x^2=(1-ax)(1-bx)$ with $ab=1$ and $a+b=-1$. Then use partial fractions $$\frac 1{1+x+x^2}=\frac A{1-ax}+\frac B{1-bx}$$ where clearing fractions gives $$1=A(1-bx)+B(1-ax)$$
Set $a=\frac 1b$ to obtain $1=B(1-\frac ab)$ so that $B=\frac b{b-a}$ and similarly $A=\frac a{a-b}$ so that $$\frac 1{1+x+x^2}=\sum_{n=0}^\infty\frac a{a-b}a^nx^n-\sum_{n=0}^\infty \frac b{a-b}b^bx^n=\sum_{n=0}^\infty\frac {a^{n+1}-b^{n+1}}{a-b}x^n$$
Now observe $a^2=-1-a=b$ and $a^3=ab=1$ and similarly $b^2=-1-b=a$ and $b^3=1$. For $n=3m$ the coefficient is $\frac {a-b}{a-b}=1$, for $n=3m+1$ the coefficient is $\frac {b-a}{a-b}=-1$ and for $n=3m+2$ the coefficient is $0$.
We can also identify $a=\omega$ and $b=\omega^2$ as being primitive cube roots of $1$. Note how the coefficients are periodic with period $3$. These facts are related, as another answer shows.

Note: I have tried to express this in such a way as to show how partial fractions can be used more generally - even where a convenient short cut is not available - it doesn't matter that you get complex roots, the answer ends up with real coefficients. The only slight trick is that we would normally factorise $$x^2+px+q=(x-c)(x-d)$$ but, setting $a=\frac 1c, b= \frac 1d$ we need the form $$x^2+px+q=cd(1- ax)(1-bx)=q(1-ax)(1-bx)$$In the case above we had $q=1$, but in general the factor must not be forgotten.
Answer: You could have continue your way.
Starting from
$$\sum_{n=0}^\infty a_nx^{n+2}+\sum_{n=0}^\infty a_nx^{n+1}+\sum_{n=0}^\infty a_nx^n=1$$ you already found $a_0=1$ and $a_1=-1$.
Now, consider a given degree $m >1$. You then have the recurrence relation
$$a_{m-2}+a_{m-1}+a_m=0$$ and the roots of the characteristic equation
$$r^2+r+1=0 \implies r_\pm=\frac{-1 \pm i \sqrt 3} 2$$ making by the end (I let to you the intermediate steps)
$$a_m=\cos \left(\frac{2 \pi  m}{3}\right)-\frac{1}{\sqrt{3}}\sin \left(\frac{2 \pi
   m}{3}\right)$$ making $a_{3m}=1$, $a_{3m-1}=0$, $a_{3m+1}=-1$.
Comment: @clathratus. Look which terms you need for a given degree $m$. This is what I did.
Comment: How do we know that we have that recurrence relation?

power series for $\frac1{x^2+x+1}$


How i can call JavaScript function from asp.net server side if script in user control

Question: I have a ASP.NET page with 1 user controls registered.
i have one server control
<asp:LinkButton ID="vidoUpdatebtn" OnClick="vidoUpdatebtn_Click" runat="server">LinkButton</asp:LinkButton>

in .cs i handle
 protected void vidoUpdatebtn_Click(object sender, EventArgs e)
    {
        //do something
        ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript", "doSomeThing()", true);

    }

in user control i have function doSomeThing()
 function doSomeThing() {
         alert("TestReady");
     }

when i click on LinckButon registred function dosen't  work
Comment: 1st thing's 1st: RegisterStartupScript is a means of making javascript code appear in your page without actually writing it yourself everytime. You should write whatever javascript function you have instead of the "doSomeThing" identifier you wrote (that is the actual javascript code). Secondly: you shouldn't register the startup script when the user clicks the button (that is way to late). And last: registering the script is not enough. You must bind the OnClientClick attribute of the  tag to the javascript function's name like so: "FunctionName()". Look at my answer...
Answer: Write this in PageLoad (the only modifications from what you were writing are the moment in time of the registration -- PageLoad not Click, Click is too late and the face that you must write the actual implementation of the javascript function here):
    protected void Page_Load(object sender, EventArgs e) {
        ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript",
@"function doSomeThing() {
    alert(""TestReady"");
}"
        , true);
    }

and this in the asp:LinkButton tag (you must specify the OnClientClick attribute):
<asp:LinkButton ID="vidoUpdatebtn" runat="server" OnClick="vidoUpdatebtn_Click" OnClientClick="doSomeThing()" >LinkButton</asp:LinkButton>

And it should work.
Comment: thanks man this method helped me  but I changed it a little
its work  even if i write ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript", "fileUploadClick()" , true); because function doSomeThing()
already exist in my user control
Comment: might I add that you can completely forget about the ScriptManager.RegisterStartupScript in that case. Try it and you'll see what I mean : if you already have the fileUploadClick function in your javascript, in your page, all you need to do is assign it's OnClientClick attribute accordingly. One way to try and discover if I'm right or wrong is modifying the RegisterStartupScript to: _ScriptManager.RegisterStartupScript(this, this.GetType(), "**blahblahblah**", "**andsomemoreblah**" , true);_ (literally) or even by commenting it entirely
Answer: Have you tried this way:
Add Script manager on your aspx page
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />

Codebehind:
Page.ClientScript.RegisterStartupScript(this.GetType(),"myscript", "doSomeThing()",true);

Comment: What do you mean by it didn't help what is the error are you getting?
Answer: If you want client side code to run on the button click, you could use the OnClickClick property instead of the OnClick event. That'll also avoid the need for a postback and will give immediate feedback to the user.
e.g.
<asp:LinkButton ID="vidoUpdatebtn" OnClientClick="alert('TestReady'); return false;" runat="server">LinkButton</asp:LinkButton>


Non-convex polyhedron with 18 edges, 12 faces and 8 vertices

Question: Which non-convex polyhedron has 8 vertices, 12 faces and 18 edges?
Answer: The dual of @lhf's construction will work.  Take a (say, nonconvex) hexagon and form the (double) cone over the plane figure, to get a solid.
The two apexes and six points of the hexagon make eight vertices, there are twelve triangular faces (six meeting at each apex), and of course $18$ edges.
There is another way to make the solid nonconvex, as one cone could be "everted" inside the other.
Answer: Besides the hexagonal bipyramid mentioned by hardmath, you can also form such a solid by adding a pyramid over each face of a tetrahedron. This "triakis tetrahedron" has 8 vertices (the four original vertices, and the four new apices), $4 \cdot 3 = 12$ faces, and 18 edges (the six original edges, and 12 new ones.) If you make the pyramids sufficiently tall, or if you indent them inside the tetrahedron, then you have a non-convex solid.


Multi lined value stored in a batch string

Question: I have a batch file script that includes a copy to clipboard function
echo|set /p="Line 1 line 2 line 3"|clip
paste | command | clip

When I paste it, it comes out as
Line 1 line 2 line 3

is there a way to copy it so when I paste it pastes as:
Line 1
line 2
line 3

Comment: `(echo Line 1^&echo Line 2^&echo Line 3^&rem/) | clip`?
Answer: Currently you are echoing a single line. You are therefore getting a single line returned when pasting.
(
 @echo line 1
 @echo line 2
 @echo line 3
) | clip

The above however will do it line by line and pipe to clip
If you want to do it as a one liner:
echo line 1^& echo line 2^& echo line 3 |clip

As also similarly demonstrated by @aschiphl in the comment.


How do I use the administrative theme?

Question: I'm building a custom Drupal theme and wondering if there is a way to get the modal windows to use the default admin theme. I'm using the Layout builder module with a custom block that uses the Media Library module and it uses jQuery UI classes.
This is also for the modal content like the media modal.
Comment: It's not possible to use two themes in the same request - there would be too much conflict. The only way to do it would be to find a way to load the modal content in an iframe, and make the path of that content use the admin theme. Do bear in mind it opens up permissions issues, as anyone viewing the modals would need 'Access administration theme' enabled
Comment: But as they are logged in as an admin and this is an admin form, I'd assume the permission issue would be null.
Comment: https://www.drupal.org/project/layout_builder_admin_theme
Answer: I think Media Library Theme Reset may be what you're looking for. From the module description:

this module takes on the responsibility of replicating Seven's CSS and
  attaching it, as a library, in the context of the Media Library, when
  accessed via Layout Builder.
Comment: I tried that module, and it gets you part way there but it's missing some bits. I did see that there is a thread to look at this for Claro: https://www.drupal.org/project/drupal/issues/2195695

How do I use the administrative theme?


Carregamento de imagem com a implementação Picasso no android

Question: Estou usando a implementação Picasso para fazer o carregamento das imagens em minha aplicação. Porém, estou usando o efeito de devaneio da implementação shimmerfacebook para tornar o layout mais agradável para o usuário. Pra quem não conhece, essa implementação é um efeito de brilho que indica que a imagem está sendo carregada. A minha intenção é detectar no picasso quando a imagem foi carrega para que eu possa remover o efeito, já que este só é removido de forma dinâmica.
Picasso.get().load(https://imagem....).into.(imageView);
Detectar que a imagem foi carregada.
Answer: No ultimo médodo .into() você pode passar um objeto tipo Callback como segundo parâmetro e utilizar o onSuccess() e/ou onError() para saber quando o carregamento do Picasso terminou.
Exemplo do into com callback usando Kotlin:
 val requestOptions = Picasso.with(imageView.context).load(imagePath)
 requestOptions.into(this, object :Callback{
        override fun onSuccess() {
            TODO("FAZER ALGO")
        }

        override fun onError() {
            TODO("FAZER ALGO")
        }
    })

Javadoc: https://square.github.io/picasso/2.x/picasso/com/squareup/picasso/RequestCreator.html#into-android.widget.ImageView-com.squareup.picasso.Callback-


How to move two servos at the same time using pyfirmata, python and Arduino

Question: I am trying to program a robot arm and I need two servos to run at the same time and be able to run in different directions for example on going 90° to 180° and the other servo going 90° to 0° , I am using a Arduino, python and pyfirmata any help would be good thank you!
import pyfirmata
import time

board = pyfirmata.Arduino('/dev/cu.usbmodem14201')

armlower2 = board.get_pin('d:6:s')
armlower1 = board.get_pin('d:10:s')

for angle in range(90, 180, 1):
    armlower2.write(angle)
    time.sleep(0.015)

for angle in range(180, 90, -1):
    armlower2.write(angle)
    time.sleep(0.015)

for angle in range(90, 0, -1):
    armlower1.write(angle)
    time.sleep(0.015)

for angle in range(0, 90, 1):
    armlower1.write(angle)
    time.sleep(0.015)

This moves the servos but only one at a time ?
Comment: put everything in separate functions and use something like [`threading`](https://docs.python.org/3/library/threading.html)
Comment: I am new to python, I will look in to threading could you help with a example? thank you
Comment: Yes - check out my answer, though I haven't really used much threading.
Comment: thank you I will give it a go tomorrow and let you know
Answer: The easiest approach would be to use threading, here's a really simple example:
import threading

def move_armlower2():
    for angle in range(90, 180, 1):
        armlower2.write(angle)
        time.sleep(0.015)

    for angle in range(180, 90, -1):
        armlower2.write(angle)
        time.sleep(0.015)

def move_armlower1():
    for angle in range(90, 0, -1):
        armlower1.write(angle)
        time.sleep(0.015)

   for angle in range(0, 90, 1):
        armlower1.write(angle)
        time.sleep(0.015)

threads = [
    threading.Thread(target=move_armlower2), # Creating threads
    threading.Thread(target=move_armlower1)
]

for th in threads:
    th.start() # Starts the thread

for th in threads:
    th.join() # Waits for the thread to terminate

References:

threading.Thread
Thread.start
Thread.join
Comment: thank you I will give it a go tomorrow and let you know
Answer: You should write your main loop around the concepts of "current value" and "want value", i.e., the values you want vs the values (angles) you currently are at. This can be expanded to any number of motors using arrays for the motors, and traversing their values in a loop.  But for two, you can simply do the following.
// The angle values you want to achieve, and what they currently are
GLOBAL want1, want2
GLOBAL current1, current2
LOOP {
    LOCAL updelta = 1
    LOCAL downdelta = -1
    if want1 > current1
        movearm1(updelta)
        current1 = current1 + updelta
    else if want1 < current1
        movearm1(downdelta)
        current1 = current1 + downdelta
    if want2 > current2
        movearm2(updelta)
        current2 = current2 + updelta
    else if want2 < current2
        movearm2(downdelta)
        current2 = current2 + downdelta

    sleep(0.015)
}

Comment: thank you I will give it a go tomorrow and let you know


Relações entre Models PHP

Question: Olá!
Eu estou desenvolvendo um miniframework, para meus projetos, e tbm criar mais conhecimentos a respeito da orientação à objeto no PHP
Eu criei, uma MODEL onde faz boa parte de tudo, e minhas classes estendem essa MODEL.... Até agora está praticamente tudo funcionando, insert, update, delete, findAll, findAllByPk, FindAllByAttributes etc.
Mas o que eu queria fazer agora são as relações entre as classes.
Ex:Eu tenho uma classe Produto  e uma Categoria, onde todo produto possui uma categoria.
Na hora de mostrar isso na view, eu queria chamar da seguinte forma:

$Produto->Categoria->attribute_categoria

mas até agora estou sem sucesso, agradeço quem puder me ajudar (me dá um norte) de como fazer isso.
Comment: Mano acho que vc nao foi muito feliz ao finalizar a explicação do seu texto, post um exemplo do que vc ja tem, e oque voce quer, fica melhor para visualizarmos sua ideal e ajudar em uma solução
Answer: O que eu faria se fosse você seria o seguinte:
<code>class Produto
{

  protected $objCategoria; //faça get's end seter's
  protected $idCategoria;  //faça get's end seter's
  ...

  protected function getCategoriaProduto($idCategoria){
     $this->$categoria = new Categoria($idCategoria);
  }

  public function getProduto($idProduto){
    //processamento para pegar produto
    $this->getCategoriaProduto($this->$idCategoria);
  }
}
</code>
O que eu fiz foi criar uma propriedade objCategoria, que armazena um objeto da classe categoria(que tem que ser definido por você), isso quando você faz uma pesquisa no produto através de um método getProdutos, por exemplo. Tal método cria uma instância da classe Categoria, que alimenta a propriedade objCategoria.
para melhor se encaixar no que você já fez, você pode alimentar o $objCategoria com um findAllByPk da classe Categoria, dentro do seu método findAllByPk da Classe produto.

Relações entre Models PHP


Retornar dados obtidos no OnResponse

Question: Como faço o retorno dessa String reponse?
Se eu dar o return ali ele não aceita... e se e por no fim do método e usar uma variável auxiliar corre o risco de retornar um null.
public String getData(){
    StringRequest request = new StringRequest(
            Request.Method.POST,
            Config.urlMaster,

            new Response.Listener<String>(){
                @Override
                public void onResponse(String response) {

                    JSONArray array;
                    try {
                        array = new JSONArray(response.toString());
                        String json = array.getJSONObject(0).toString();
                        Log.i("Script", "SUCCESS: "+response);

                        //return response;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(contexto, "Error: "+error.getMessage(), Toast.LENGTH_LONG).show();
                }
            }){

    };

    request.setTag("tag");
    requisicao.add(request);

    return null;
}

Comment: Relacionado http://pt.stackoverflow.com/q/150458/2541
Answer: O primeiro passo para resolver o problema é entender como funciona a execução do código.
Você está passando um objeto listener cujo método onResponse será invocado como um callback quando a requisição for finalizada. A execução de tal método não é linear, mas de natureza assíncrona.
Isso significa que o método principal vai acabar a execução e somente em algum momento depois o onResponse vai executar. Portanto, é impossível querer retornar o valor abaixo.
Existem duas formas de resolver isto. Uma delas é forçando o método principal a aguardar pela finalização da requisição. Porém esta é uma péssima prática, pois vai bloquear todo o programa. A maioria das APIs do Android são de natureza assíncrona justamente para evitar bloqueios e permitir cancelar tais operações.
Portanto, meu conselho seria que você mudasse sua estratégia. Ao invés de retornar os dados, você deve passar para o método um método callback que vai receber os dados e ser executado quando a requisição completar.
Exemplo
Eu iria escrever um exemplo, mas encontrei algo que responde exatamente sua pergunta no SOen. Vou apenas adaptar o código.
Primeiro você cria uma interface para servir de callback:
public interface VolleyCallback {
    void onSuccess(String response);
}

Depois altera seu método para receber o callback:
public void getData(final VolleyCallback callback) {
    StringRequest request = new StringRequest(
            Request.Method.POST,
            Config.urlMaster,

            new Response.Listener<String>(){
                @Override
                public void onResponse(String response) {

                    JSONArray array;
                    try {
                        array = new JSONArray(response.toString());
                        String json = array.getJSONObject(0).toString();
                        Log.i("Script", "SUCCESS: "+response);

                        //passa o valor para o método callback
                        callback.onSuccess(response);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(contexto, "Error: "+error.getMessage(), Toast.LENGTH_LONG).show();
                }
            }){

    };

    request.setTag("tag");
    requisicao.add(request);

    return null;
}

Finalmente, você chama o método passando o callback onde faz o que precisa fazer com os dados:
getData(new VolleyCallback() {
     @Override
     public void onSuccess(String response) {
         //executa a ação aqui com o response obtido
     }
});

Opcionalmente, você pode mostrar um loader para informar ao usuário que está carregando os dados e também implementar outro callback para tratar erros.
Comment: Muito obrigado! Funcionou como uma luva para mim... Só modifiquei algumas coisas para que para que ele me retornasse já um objeto enviado por parâmetro, desse modo eu aumentei a reusabilidade do meu método que pode ser usado para buscar qualquer dado do meu banco e transformá lo em qualquer modelo da minha aplicação, desde que passados os parâmetros corretamente. Não estou no PC, mas mais tarde postarei a solução desenvolvida

Retornar dados obtidos no OnResponse


Hover-list in CSS Only

Question: I'm having some trouble with CSS rollover menus.
I've seen it a lot, and there are tutorials, but there is so much unnecessary code, and I find it hard to distinguish between which is the needed code, and which is just other CSS.
I'd like to have a hover menu on CSS only because the website I'm working on has a lot of users that intentionally have scripting disabled (JavaScript).
I don't understand, in CSS, how one can make a "sub menu" appear beneath its parent List item when the user hovers over the parent list item. Can someone please help me understand how this works in CSS?
Below is an image of what I am referring to:
Answer: The following will work, in its basic form, but style for your own tastes (position, borders, colours, etc):

Simple List item

sub menu item 1

sub menu item 2

sub menu item 3

With the CSS:
ul li {
    position: relative;
}

ul ul {
    position: absolute;
    top: 1em;
    left: 0;
    display: none;
}

ul > li:hover ul {
    display: block;
}

JS Fiddle demo.
Comment: Yeah, the problem was that I'd forgotten to set `position: relative;` on the parent `li`; `position: absolute` elements are positioned relative to the first ancestor element with a `position` other than `static` (I think), or, otherwise, relative to the `body` element.
Comment: Thank you. It does actually show and hide when hovered. But, no matter what top or left I set, or what position I set, the "sub" menu item only appears at the very top-left of the page (and the actual menu is on the right of the page and down a bit) -
Comment: Am I seeing things, or did some code in your answer just disappear?
Comment: Thank you @MiljanPuzović and thanks David Thomas - works just as I had hoped. So happy to finally understand how it's done! :-)

Hover-list in CSS Only


The odds of matching ages being the same day of the week for 2 people (father and daughter)

Question: What are the odds that (despite having different birthdays) my daughter (born November 16, 2006) and I (Feb 8, 1979) have had each consequestive birthday on the same day of the week, we were both born on a Thursday and every birthday thereafter has been the same day of the Week. My 18th was a Saturday, her's will be a Saturday, my 30th was a Sunday, her's will be a Sunday too. In fact every single year, her age and the day that her birthday lands on is an exact match for the day that my birthday was when I turned the same age.
I imagine the odds of knowing somebody who coincides this way with yourself are quite high, combined with the fact that we are parent and child. I'd like to get a statistical figure of the likelihood or a ratio of how many times this can occur in any given combination of years between two people, is there a formula that suggests the number of years apart for these coincidences to possibly occur? such as every 9 years or a number of years divisible by 9 (27 in this case)
Many thanks all.
Comment: Possible duplicate of [Determining statistical probability related to a string event of dates](https://stats.stackexchange.com/questions/296541/determining-statistical-probability-related-to-a-string-event-of-dates)
Comment: I don't think this is a duplicate, if you read the question carefully (on first reading, I did think it was a dupe). This one seems to me to have a very simple answer (see my answer) but perhaps I am the one who is misunderstanding things.
Answer: 1 in 7.
Your being related has nothing to do with it.


How to setup Hessian Kit in iPhone existing projects

Question: How can I set up Hessian Kit on existing iPhone project? What are the steps required to run a simple hello world program?
I have Hessian Kit (http://sourceforge.net/projects/hessiankit/) but don't know how I can include this in my existing project.
Answer: Ok, I just download it and had a quick look. The download is the source code of the project.

Download and open the project in XCode.
Build the static library target.
Goto the project you want to include the kit in.
Add a group under the frameworks.
Add into the group, the static lib (.a) and any header files (.h) that just got built by #2.

Thats the quick summary :-)
Comment: A word of warning, GCC compiler have a bug that will result in exceptions for unknown selectors if compiled as a static library, without using the -ObjC linker flag. I suggest to always use HessianKit from source.
Comment: thanks a lot, just one more question, how to declare @protocol for this (http://wiki.caucho.com/Hessian_-_Objective-C_2.0_Implementation)
Comment: I'll assume you are new to Objective C. A protocol is the equivalent of a Java interface. Simply create a header file (*.h) in your project and enter the @protocol there. Classes can implement the protocol and it's methods by declaring them in their header files:

    #import "myprotocol.h"

    @interface someclass : NSObject
    ...
    @end

Check the chapter in the Objective C manuals on Protocols and Categories.


Setting defaults in sudoers

Question: I'm trying to set the Defaults in an appropriate way for the pdebuild usage.
I've got the command alias defined:
Cmnd_Alias  PBUILDER = /usr/sbin/pbuilder, /usr/bin/pdebuild, /usr/bin/debuild-pbuilder

and I'm trying to set the defaults only for that one:
Defaults        env_reset
Defaults!PBUILDER       env_keep="DIST ARCH"

This fails with syntax error on the line with env_reset. When I comment out the Defaults!PBUILDER line, it works just fine. What should I update here to make it work?

Additional info:
$ sudo -V
Sudo version 1.6.9p17

The man page has information about the "Defaults!..." option so this should be ok in theory.
The whole file is:
Cmnd_Alias  PBUILDER = /usr/sbin/pbuilder, /usr/bin/pdebuild, /usr/bin/debuild-pbuilder

Defaults    env_reset
Defaults!PBUILDER   env_keep="DIST ARCH"

root    ALL=(ALL) ALL
stan ALL=(ALL) PBUILDER

%engineering    ALL=(ALL) ALL

Comment: Can you post the rest of your sudoers file?  What you've posted so far looks fine, and works in my sudoers configuration without a problem.  Also, what version of sudo are you using?
Comment: @larsks - Added the requested info. I'm using debian lenny.
Answer: I think your man page is out-of-sync with respect to the version of sudo that you're using.  I just checked out 1.6.9p23 [aka changeset 5429:f7398cfbac71] from the sudo repository, and the sudoers man page shows the following syntax:
    Default_Type ::= 'Defaults' |
                     'Defaults' '@' Host_List |
                     'Defaults' ':' User_List |
                     'Defaults' '>' Runas_List

There's no mention of the 'Defaults' '!' Cmnd_List syntax available in more recent version.  This appears to be an online version of the 1.6.9 man page which shows the same thing.
Comment: It's there in an example later on, but at the same time, yes, it's missing from the syntax description :/ Some documentation mistake seems to be the most reasonable explanation really.
Answer: Just to add to what larsks has said, I've tried your sudoers file in my sudo (1.7.4p5) and it parses fine, no errors.  It's possible that the version you're using doesn't have as sophisticated support for defaults as 1.7, or it may just be a bug.  Is upgrading sudo out of the question?
Comment: Yes, it is out of question. On the other hand, I don't think it's a not-supported option, since this example is in the manpage: `# Override built-in defaults {...} Defaults!PAGERS noexec` for the same version.

Setting defaults in sudoers


Como inserir registros ao iniciar o sistema JSF + JPA?

Question: Como faço para inserir registros pré-cadastrados no sistema com jsf e jpa. Quero que quando o sistema inicie o usuário administrador seja criado.
Comment: Por que não usar scripts SQL? eu penso que é uma péssima idéia fazer isso, muito provável que você só vai executar uma única vez, imagine que você estai criando algo dentro da aplicação que precisa sempre ficar verificando se foi criado, você poderia até mesmo usar uma ferramenta para gerenciar esses scripts como [flyway](https://flywaydb.org/getstarted/) ou [liquibase](http://www.liquibase.org/) onde você pode ter controle de versionamento dos scripts, é só uma dica, abração.
Comment: Como estou usando JPA, eu teria que acessar o sistema e depois voltar no servidor de bando de dados para executar o script
Answer: Você pode utilizar a anotação @PostConstruct no método do seu managedBean.
Essa anotação irá fazer com que o método seja invocado após o seu mBean ser instanciado.
Exemplo:
<code>@ManagedBean
@RequestScoped
public class TesteMBean{

    private UserAdm userAdm;

    @PostConstruct
    public void init(){
          userAdm = new UserAdm();
    }

    public UserAdm getUserAdm() {
        return userAdm;
    }

    public void setUserAdm(UserAdm userAdm) {
        this.userAdm = userAdm;
    }
}
</code>
Answer: Outra opção é implementar um ServletContextListener e inserir os registros no método contextInitialized, que é invocado quando o servidor inicializa o contexto da aplicação. Dessa forma não é preciso acessar a aplicação para que essa primeira ação (inserir os registros) seja executada.
E o ServletContextListener é gerenciado pelo servidor de aplicação, ou seja, é possível acessar recursos como EntityManager.
<code>@Inject
private EntityManager em;
</code>
Além disso, se utilizar um Managed Bean JSF, o método anotado com @PostConstruct será executado toda vez que a página jsf correspondente for carregada, enquanto o método contextInitialized será carregado apenas uma vez, quando o servidor iniciar a aplicação.
<code>@Override
public void contextInitialized(ServletContextEvent event) {

    StringBuilder sb = new StringBuilder();
    sb.append("Aplicação xyz iniciada: ");
    sb.append(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(Calendar.getInstance().getTime()));
    System.out.println(sb.toString());

    gravarRegistrosPreCadastrados(); //TODO
}
</code>
Comment: A questão é como executo este sql no meu sistema.
Answer: Daniel, complementando o que o Paulo Cardoso disse, vc pode usar o @PostConstruct em um determinado Managed Bean e aplicar o @ApplicationScoped, dessa forma, ele será executado somente um vez quando você acessar a aplicação.
<code>@Named(value = "tarefasBean")
@ApplicationScoped
public class TarefasBean implements Serializable {

public TarefasBean() {
    System.out.println("INICIANDO TAREFAS BEAM");
}

@PostConstruct
public void executarTarefas() {
    verificarConexão();
    iniciarQuartz();
}

private void iniciarQuartz() {
   //iniciando agenda de tarefas aki
}

public void verificarConexão() {
    //meu codigo aki
}

}
</code>
No método verifica conexão, caso haja um problema, o user será redirecionado, se estiver tudo certo, eu inicio minha "agenda de tarefas", e isso só vai acontecer o primeiro acesso da aplicação. Daí, vc pode fazer suas inserções e coisas do tipo no posconstruct.


Print Server Migration and Client Installs

Question: I am migrating to a new print server running Windows 2008R2. The hardware will be new, but I will use the old print server's IP, host name, printers and settings.
Will my clients using these printers need re-installation? Or can I just swap the servers and everything will run normally?  I want be sure the shared TCP/IP printers do not rely on the hardware spec or MAC of the print server.
Comment: Provided you keep "everything" the same on the server side, you won't need to re-install anything at the client.
Comment: Thank you  jscott   for helping newbie here  ^ ^

even google dont seem to get clear question
i know it stupid question but i dont know where to ask i dont Have Enough HW to test
Answer: You should be fine with your plan to just swap in the new print server. If you retain the old IP, hostname, ports, printers and queues your clients should not even notice the change.
Microsoft provides a tool printbrm.exe which can help with print server migrations.  They also provide a guide Mirgate Print Servers with additional information.


Runner missed bag on first and is tagged on second

Question: The ball is hit to right center field, the runner misses first base while rounding it and goes on to be safe at second.
We tell the umpire about the missed base, and instruct our player to tag them on second, which is done while at second.
The umpire calls safe, then later said if we went to the mound and then threw to first, it would be out. I know that is one way, but can we appeal and tag the runner at second as well?
Answer: What the umpire is referring to is the appeal play, which is the one correct way to put out a runner who misses a bag. However, they may, or may not, be confused as to what actions constitute an appeal play.
From the MLB Rulebook (2021), 5.09(c):

Appeal Plays

Any runner shall be called out, on appeal, when:

With the ball in play, while advancing or returning to a base, he fails to touch each base in order before he, or a missed base, is tagged;

From this article, it shows two methods of appeal - live ball and dead ball.  The rulebook does not specify when the appeal must happen; though dead ball is the more common method (and what is typically thought of as "appeal") for this kind of out, it is not the only one.  (In fact, probably the most common appeal play is that where the player does not tag up after a fly ball - lining into a double play, for example - and that certainly happens when the ball is live in most instances.) Not all leagues support "dead ball" appeals; MLB does not, for example, but it is more common to be permitted at lower levels to avoid complications. I will assume only "live ball" appeals are permitted here, as otherwise simply informing the umpire of the desire to appeal should have sufficed.
What your question does not make clear is whether or not this occurred before or after time was called on the previous play.  If it was a live ball situation and the play was still ongoing, then the player should simply have been ruled out so long as the umpire felt an appeal was being made (tagging a runner on a base should suffice, but the player could use the word "appeal" to make it more clear - but it should not be required).  If it were after time was called, the ball needed to go back to the mound first, and then be thrown to the missed base properly (meaning, without a balk).  The pitcher could also throw to a player who could then tag the runner who missed the base, if they are still on base; see for example this how-to.  The rules do explicitly state "he, or a missed base, is tagged", and so tagging the player should be sufficient.


MySQL table trouble: when one of two columns must be empty (in a row)

Question: I'm using MySQL and my tables are stored using innoDB for the purpose of referential integrity.
QUESTION
I'm building a sales order system.
My invoice table has tracking_code column and COD_place column

Customer deals with me using either one of these methods: shipping or COD (cash
  on delivery/meeting him up personally).
  Each parcel that is shipped has a tracking code, while for COD, there has to be a place to do that. Thus the column tracking_code and COD_place.

The problem is, if shipping is preferred, then the COD_place column should be NULL or left empty; otherwise, tracking_code must be NULL.
It's not elegant. What is the best way to represent this? Can you create a generalized entity, method in MySQL?
I really can't think of any elegant solution so I turned to your help here.
Thank you in advance!
Comment: An option is to store the details in separate tables. For example invoice table can have Enum(TRACKING, COD), reference_id. 'Tracking' table will have id, tracking_code. 'COD' table will have id, cod_place. both Tracking table and COD table will be related to Invoice table via the reference_id. Having said that, if you are going to heavily query the Invoice table frequently, perhaps your original design is better (in spite of null fields) because it is going to avoid joins which may become heavy after the tables have  millions of records.
Comment: yeah, thanks man. I don't like too many NULLs.
But I don't like reference_id in the invoice in that tracking and COD can have the same id (auto increment preferred over alphanum) value, although i can determine which table to join from the Enum column. But that will be done using PHP in fact I want it to be internal.
So i guess I'll stick back to original design.
Thaaanks!
Comment: What you need is a CHECK constraint. Unfortunately, these are not supported in MySQL. See here http://stackoverflow.com/questions/2115497/check-constraint-in-mysql-is-not-working and here http://stackoverflow.com/questions/5807231/mysql-check-constraint-alternative for approach using triggers.
Answer: You should introduce an additional column to specify which type of transaction is requested.  Do not try to implicitly assume this based on the other information.
It is acceptable to have fields for redundant information within a table (using NULL).
Alternatively you could have an additional table for each type of transaction, with only the relevant fields necessary for that type of transaction.  This has the added advantage of being able to represent those processes distinctly without interference from the others.
For example, you might have business logic which is supposed to handle COD transactions, which includes a state of "Driver collected payment" whereas your shipping transactions might have a column to handle "Payment pre-authorised transaction ID". There's no need for COD logic to care about shipping transactions, and vice-versa.
With an additional transaction_type field on the Invoice, you know which table to join to, in order to collect the additional information.  If you add a 3rd type in future, you're not going to end up with an ever-expanding Invoice table.
Comment: With the additional field on the invoice I know which table to join to. However determining which table to join to is done explicitly using PHP right? I mean, use PHP to get the value of transaction_type  and then JOIN with the corresponding table?
Comment: Yes, I'd do that @Chin-yangLee.  You could feasibly do a UNION of both tables in MySQL, but that almost defeats the purpose of splitting out the different fields into different tables.  You can tell which is which by just looking at the transaction_type field (or whatever you call it).


Como manter zero a esquerda em importação no Python?

Question: Olá
Tenho vários arquivos TXT com números de CPFs. O CPF tem 11 números, então pode ter zeros à esquerda para completar esse tamanho
Abri esses arquivos em Excel e os reuni em um só. Na coluna do CPF, antes de abrir cada arquivo, transformei no comando de importação do Excel para como Texto para manter os zeros. No formato xlsx deu certo
Mas quando gravei como CSV vi que os zeros da esquerda sumiram
Em Python 3 abri, para usar pandas depois, e vi que realmente perdeu o zero na esquerda e virou int64:
candidatos = pd.read_csv("candidatos_excel_cpfinteiro_csv.csv",sep=';',encoding = 'latin_1')

candidatos.info()

    <class 'pandas.core.frame.DataFrame'>
RangeIndex: 26245 entries, 0 to 26244
Data columns (total 9 columns):
UF                  26245 non-null object
Estado              26245 non-null object
Cargo               26245 non-null object
Nome_completo       26245 non-null object
CPF                 26245 non-null int64
Nome_urna           26245 non-null object
Partido             26245 non-null object
Partido_completo    26245 non-null object
Situacao            26245 non-null object
dtypes: int64(1), object(8)
memory usage: 1.0+ MB

Tentei abrir direto o arquivo de Excel, com o xlrd, mas ficou como número da mesma forma:
xlsx = pd.ExcelFile('candidatos_excel_cpfinteiro.xlsx')

candidatos = pd.read_excel(xlsx, 'Planilha1')

candidatos.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 26245 entries, 0 to 26244
Data columns (total 9 columns):
UF                  26245 non-null object
Estado              26245 non-null object
Cargo               26245 non-null object
Nome_completo       26245 non-null object
CPF                 26245 non-null int64
Nome_urna           26245 non-null object
Partido             26245 non-null object
Partido_completo    26245 non-null object
Situacao            26245 non-null object
dtypes: int64(1), object(8)
memory usage: 1.0+ MB

Por favor, alguém teria uma sugestão de como manter os zeros à esquerda? Ou manter como string essa coluna?
Comment: como os cpfs estão dentro do arquivo .csv? Pelo que entendi da pergunta, o excel já exporta eles sem os zeros.
Comment: Olá, obrigado. Estão sempre com 11 digítos ("99493713415", "02376606446", "16436105468", "02108363262"...). Sim, quando gravo como CSV ele perde o zero à esquerda
Comment: Olá, acho que expliquei errado. No TXT original está com 11 dígitos  ("99493713415", "02376606446", "16436105468", "02108363262"...). Mas quando transformo em CSV no Excel aí perde o zero à esquerda
Comment: Isto responde à sua pergunta? [Como ler um arquivo csv pelo pandas sem apagar o primeiro numero?](https://pt.stackoverflow.com/questions/508239/como-ler-um-arquivo-csv-pelo-pandas-sem-apagar-o-primeiro-numero)
Answer: Você pode definir o dtype no momento da importação. Por exemplo:
candidatos = pd.read_csv("candidatos_excel_cpfinteiro_csv.csv",sep=';',
                         encoding = 'latin_1', dtype=str)

Também é possível definir o dtype individualmente, por exemplo, {'a': np.float64, 'b': np.int32}.
Para maiores detalhes, recomendo a documentação.
Answer: Tenta importar direto do excel, usa essa linha de código que você não vai perder nenhum valor:
import pandas as pd

seu_dataframe = pd.read_excel('nome do seu arquivo .xlsx')

Comment: Obrigado, mas não funcionou. Também corta o zero a esquerda quando importo como você indicou acima: a coluna fica assim - CPF                 26245 non-null int64
Comment: Mas no arquivo do excel está com o zero à esquerda e a coluna formatada como texto
Answer: Solução
df = pd.read_csv("C:\\base\ATENDIMENTO_reduzido.txt", delimiter=',', encoding='latin-1', `dtype=str`)

Comment: Veja [Como devemos formatar perguntas e respostas?](https://pt.meta.stackoverflow.com/q/1084/137387). Existem sandboxes online aos montes, veja sites como https://ideone.com/, https://replit.com/, https://research.google.com/colaboratory/,... onde pode criar, testar e compartilhar links para código fonte escritos em Python e em várias outras linguagens. No site https://docs.python.org/pt-br/3/index.html você encontra a documentação Python para usar como referência. No site https://pandas.pydata.org/docs/ você encontra a documentação Pandas para usar como referência.
Comment: Veja um exemplo de como seria uma [resposta a uma pergunta similar](https://pt.stackoverflow.com/a/508243/137387). Aproveite e veja [answer] e faça o nosso [tour].


limsup in probability

Question: Consider a sequence of $n$ i.i.d. random variables $X_n$. We have the inequality:
$$P(\liminf{X_n\leq x})\leq \liminf P({X_n\leq x})\leq \limsup P({X_n\leq x})\leq P(\limsup{X_n≤x})$$
Is there any way to prove (or any conditions under which) that:
$$\log P({X_n ≤x}) \leq \limsup \frac 1n P({X_n \leq x})$$
Comment: Probabilities output values in $[0,1]$. Therefore, their logarithms output values in $[-\infty,0]$. Since $0\leq\frac{1}{n}P(X_n\leq x)$, then also $0\leq\limsup\frac{1}{n}P(X_n\leq x)$. Transitivity yields $\log P(X_n\leq x)\leq \limsup \frac{1}{n}P(X_n\leq x)$.
Comment: "a sequence of $n$ iid..." I think you want to remove the $n$.
Answer: $\log P(X_n \leq x) \leq 0$ and $ \lim \sup \frac 1 n P(X_n \leq x)=0$ so the inequality is always true.
Comment: Another, related question: Consider a sequence of i.i.d. random variables $X_n$. Is there any way to prove (or any conditions under which) that:

$\log P\left( X_n \geq x \right)$
$ \leq \limsup_{N\rightarrow \infty} \frac{1}{N} \log P\left(X_n \geq x \right)$

limsup in probability


Derivative of $f(u)=\sqrt{8} \;u+\sqrt{6u}$

Question:
$$f(u)=\sqrt{8} \;u+\sqrt{6u}$$

$f(u)=\sqrt{8}\;u+(6u)^{1/2}$
$f^{\prime}(u)=\sqrt{8}+\dfrac{1}{2}(6u)^{-1/2}$
$=\sqrt{8}+3u^{-1/2}$
This was marked wrong, though. What am I doing wrong? thanks.
Comment: Why is $\frac{1}{2}6^{-1/2} = 3$?
Answer: You are right when you differentiate the $\sqrt{8}u$ part.  As you wrote, that part just becomes $\sqrt{8}$.
For the $\sqrt{6u}$ part, first, as you did, we write it as $(6u)^{\frac{1}{2}}$, and then differentiating this and using the chain rule (which you forgot) gives $\frac{1}{2}(6u)^{-\frac{1}{2}}(6) = 3(6u)^{-\frac{1}{2}} = \frac{3}{\sqrt{6u}}$.
What you seemed to do was say $\frac{1}{2}(6u)^{-\frac{1}{2}} = 3u^{-\frac{1}{2}}$.  You can't multiply the $\frac{1}{2}$ and the $6$ together because the $6$ is being raised to the $-\frac{1}{2}$ power.  Also, you forgot the chain rule when differentiating.
So, $f'(u) = \sqrt{8} + \frac{3}{\sqrt{6u}}$.  Hope that helps.
Comment: @user437158 I'm not sure, but I don't think so.  You are trying to differentiate $\sqrt{6u}$.  This is a composition of functions, where $f(u) = \sqrt{u}$ and $g(u) = 6u$ (i.e., $f(g(u)) = \sqrt{6u}$).  To find the derivative of a composition of functions, you differentiate the outside function, then multiply that by the derivative of the inside function.  So, $(f(g(u)))' = f'(g(u)) g'(u)$ (this is the chain rule).  It's weird that they gave you this problem without teaching you the chain rule first.
Comment: +1 thanks, I solved it without the chain rule because we didn't learn the chain rule yet. Is there a way to solve it without the Chain rule? thanks


Displaying data from multiple tables in a view as a list - ASP.Net MVC

Question: I have the following two tables (basic outline):
Tbl_CategoryType
ID
LevelID
Description
Tbl_Levels
ID
Name
Basically, I want to present all of the information in the Tbl_CategoryType table while referencing the Tbl_Levels.Name data based on the Tbl_CategoryType.LevelID number.
I have tried using a join in my repository as below;
public IQueryable GetAllTypesInCategory(int CatID)
{
     return (from x in DBEntities.LU_LST_CategoryTypeSet
             where x.CategoryID == CatID && x.Enabled == 1
             join y in DBEntities.LU_LST_LevelSet on x.LevelID equals y.ID
             select new {x, y});
}

However, when I call that method there is no type I can assign it to as it doesn't fit into the type of either the Category or Level.
I'm assuming I need to do this through a custom viewmodel but can't figure out the steps.
Thanks in advance
Answer: By using this line in your linq statement:
select new {x, y}

you are creating a new anonymous type, which is a different type from your Entity types.
I'm guessing you're not using EntityFramework or some other heavy framework that will automatically resolve foreign key relationships to create linked entities.  If true, then yes, you will need to create a ViewModel.
Just create a simple wrapper class that contains one of each entity as a property.
public class MyViewModel
{
    public MyViewModel(LU_LST_CategoryTypeSet x, LU_LST_LevelSet y)
    {
        Category = x;
        Level = y;
    }

    public LU_LST_CategoryTypeSet Category { get; set;}
    public LU_LST_LevelSet Level { get; set; }
}

Then in your Linq statement, instead of creating anonymous types, create MyViewModel types:
public IQueryable GetAllTypesInCategory(int CatID)
{
     return (from x in DBEntities.LU_LST_CategoryTypeSet
             where x.CategoryID == CatID && x.Enabled == 1
             join y in DBEntities.LU_LST_LevelSet on x.LevelID equals y.ID
             select new {x, y});
}

Then copy the results into your model classes:
   var listOfTypes = GetAllTypesInCategory(catID);
   foreach (var item in listOfTypes)
   {
      var model = new MyViewModel(item.x, item.y);

      //Do whatever with the model to get it to the view.
   }

Make your View inherit from MyViewModel.
Comment: This will not work. You have to create anonymous type and then copy data to MyViewModel collection.
Comment: Oh, yeah looks like his method wants an IQueryable.  Thanks for the spot.
Comment: I'm sorry I forgot to mention I was using the Entity Framework.
Answer: If there is an association between the two entities you can access the second type using it. The only thing you need to do in that case is use the Include() method to load the association data.
       public List<LU_LST_CategoryType> GetAllTypesInCategory(int CatID)
         {
             return (from x in DBEntities.LU_LST_CategoryTypeSet.Include("LU_LST_LevelSet")
                     where x.CategoryID == CatID && x.Enabled == 1
                     select x).ToList();
         }

Than for every LU_LST_CategoryTypeSet category you can call category.LU_LST_Level


How to use views to filter specific workflow state in current month

Question: I have a system that is heavily workflow dependant. I have a content type called 'Profile' with 3 states :

Lead
Prospect
Customer

I would like to know how to create a views contextual filter of all Profiles that changed to the Customer state in a given month i.e. which Profiles Customer this month.
D6 Views 2.x has this option but I cannot find it in D7 Views 3.x
Thanks
Answer: You may want to check if using the Views Date Format SQL module could be a solution for you. Here are some quotes about it (from its project page):

... allows to format date fields using SQL.
The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE_FORMAT rather than PHP's format_date.
  This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views_handler_field_date.
The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

Your question is not about creating charts in Drupal, but you may want to refer to this comment also for an example of how we typically use it within the Charts module.


Evaluate $\underbrace{\idotsint}_n \exp\left(-\sum_{1\le i\le j\le n}^n x_i x_j\right) \mathrm{d}x_1\cdots\mathrm{d}x_n $

Question: I am currently studying V.I. Arnold's course, and I am stuck on this exercise:
Evaluate
$$
\underbrace{\idotsint}_{n}
\exp\left(-\sum_{1\le i\le j\le n}^n x_i x_j\right)
\mathrm{d}x_1\cdots\mathrm{d}x_n
$$
Can anyone suggest a hint? Thank you in advance!
Comment: Have you tried the small cases $n=1,2,3$; then tried to generalize?
Answer: Having read a lot of things by Arnold, I think his point of view was that "every student should know" the formula
$$\int\ldots\int_{\mathbb{R}^n}\exp\left\{-\frac12 x^TAx\right\}dx_1\ldots dx_n=\frac{(2\pi)^{n/2}}{\sqrt{\mathrm{det}\,A}},\tag{1}$$
where $x^T=(x_1,\ldots,x_n)$ and $A$ is a real symmetric positive definite $n\times n$ matrix. Actually, every physics student should know it indeed.
What remains is a simple linear algebra exercise.

Added: The gaussian integration formula (1) is obtained by noticing that the matrix $A$ can be brought to diagonal form by orthogonal transformation, characterized by unit jacobian. Then one is left with a product of gaussian integrals $\prod_{k=1}^n\int_{-\infty}^{\infty}\exp\{-\lambda_k x^2/2\}dx$, where $\lambda_{1\ldots n}$ denote the eigenvalues of $A$.
Answer: Hint: Diagonalize the symmetric matrix
$$
A=-\frac12\left(
\begin{array}{ccccc}
2&1&1&\cdots&1\\
1&2&1&\cdots&1\\
1&1&2&\cdots&1\\
\vdots&\vdots&\vdots&\ddots&\vdots\\
1&1&1&\cdots&2
\end{array}\right)?
$$
Diagonalization of a quadratic form in the exponential = separation of variables.
Comment: I worked it out. The diagonal matrix is $\left[
\begin{matrix}
1& & & & \\
 &1& & & \\
 & &\ddots& & \\
 & & &1& \\
 & & & & n+1
\end{matrix}\right]$. So by n-dimensional Gaussian integral the final result is $\frac{(2 \pi )^{n/2}}{\sqrt{n+1}}? $
Comment: @YorkTsang: That's what I got, too (don't forget that $-1/2$). Note that as $A$ is symmetric, it can be diagonalized with an orthogonal matrix, so the Jacobian of this linear change of variables is $=1$ (orthogonality not essential here, but sometimes else it is).
Comment: OOPS. Orthogonality IS essential. Diagonalization naturally uses the inverse of a matrix, but the quadratic form uses the transpose. Transpose = inverse, when the matrix is orthogonal. Sorry about that.
Comment: I changed what looked like a typo. Let me know.
Comment: Then the answer should be like $\displaystyle |A^{\frac{1}{2}}|\left(\int \exp(-x^2)dx\right)^n$ right?
Comment: @JyrkiLahtonen: Thank you for your hint!


Commerce Invoice Entity Print Styling

Question: I am using Commerce Invoice and Entity Print to generate .pdf-files of invoices. In Entity Print settings, I set the paper size to A4 and selected TCPDF as printing engine.
Then, I customized commerce-invoice.html.twig to my needs, which works fine.
But I cannot get rid of the two black borders that seperate the document header and footer I think.

Would be nice if anyone could give me a hint where these come from. I alread also tried to override entity-print.html.twig and remove the styles from there. Also I unchecked the checkbox in the entity-print settings.
But these borders still appear on every .pdf-generation.
Thank you very much in advance!
Comment: Inspect them with browser developer tools. I'm thinking they might be horizontal line elements (``) and not borders. They are probably separating printing header and footer, where you might add printing info (page numbers, date of printing, etc).
Comment: @BerryDingle When you have the time, pease summarize your findings as an answer to your own question, to help others in the future.
Comment: It can't be investigated remotely, you have to debug, test, and poke around to find out where it's coming from. Turn on the print stylesheets in your browser dev tools and inspect. Also turn twig debug on to get template suggestions, this will help in investigating which template might hold the hr elements, if that's what they are.
Comment: @prkos Thanks for the answer! I thought of that myself already. But I completely stripped down the commerce-invoice.html.twig (which contains all the HTML and TWIG of the actual print document), as well as the entity-print.html.twig, which is practically the "parent" wrapping commerce-invoice.html.twig. And in both there's no  as well as no css. But yes, it's possible these are s, but I cannot figure out where they come from. I assume they appear when the document is actually printed as .pdf and are "injected" in this process somewhere...
Comment: @prkos Yes, I know. I just thought someone might have wanted to remove them already. In the meanwhile, I switched to DOMpdf as printing-engine, and the "borders" are gone. So it has to be somewhere inside TCPDF rendering/converting. I'll have to dig deeper and more. But thanks man!
Comment: Haha woman! Have you checked all entity print templates? You have to find out if it really is hr element first. DOMpdf and TCPDF don't have equal CSS support, so it may be in the way they style hr elements. But it would still be useful to find them in the HTML.
Comment: @prkos Thanks again apache helicopter :) In fact, it has been the TCPDF rendering an empty header and footer element by default. I switched to DOMpdf now, which just ignores it if no header and footer is defined. And, DOMpdf also offers better CSS support which will make it less of a pain in the.... Thank you again!
Answer: What I found out is:
Every available printing engine has it's own requirements for the HTML-structure of the generatred invoice.
TCPDF needs a header and footer-tag inside the document. If you dont provide this elements, TCPDF will render them empty, but will in fact attach an hr-tag after the empty header and before the empty footer.
I switched to DOMpdf as printing engine, which also offers the possibility to define a page header and footer, but ignores them when empty and doesn't render any additional HTLM by default.
pro: DOMpdf supports more CSS rules and makes it easier to style the invoice with CSS
con: DOMpdf takes some seconds to render/print the document from the HTML, while TCPDF is very fast.

Commerce Invoice Entity Print Styling


For what values of $x$ does the series $\sum\limits_{n\geqslant 1}\sin(0.99\sin(0.99\dots\sin(0.99x)\dots))_{n-times}$ converge?

Question: For what values of $x$ does the series
$$\sum\limits_{n\geqslant 1}\sin(0.99\sin(0.99\dots\sin(0.99x)\dots))_{n-times}$$
converge, diverge and converge absolutely.
I'm stuck on how to approach this problem as clearly ratio test won't work and I can't see how I could use the comparison test. Clearly it converges when $sinx=0$; I've tried finding the progression of values after each $\sin(0.99...$ but it seems kind of random.
Answer: Should converge absolutely for all x. After all, $-1\le a_1=\sin(0.99x)\le1$, and then $|a_{n+1}|=|\sin(0.99a_n)|<0.99|a_n|$, so $|a_{n+1}|<0.99^n$.


Alguem pode me ajudar? Eu quero saber como faz para ter um looping while que não deixe prosseguir até a resposta estar correta

Question: Eu estou estudando programação sozinho e sou bem iniciante na programação de jogos e estou tentando fazer um mini joguinho de texto tipo um rpg de mesa onde o console faz uma pergunta ao jogador e o jogador responde a pergunta (exemplo se o jogador quer ir pra frente ou os lados), porém, eu não estou conseguindo fazer um looping que faz com que sempre que o jogador não escolha uma das opções, escreva sempre uma mensagem falando para ele escolher as opções certas e pedindo uma resposta no console, no meu código apenas pergunta uma vez e apenas deixa o jogador coloque a resposta uma vez e mesmo se a resposta esteja correta ou não ele finaliza o código e eu queria que sempre perguntasse para o jogador e sempre deixasse ele responder sem terminar até responder corretamente e prosseguir o código.
Meu código(está na IDE do Eclipse utilizando Java):
    Scanner in = new Scanner(System.in);
    Random rand = new Random();
    String nome;
    System.out.println("Seja bem-vindo ao jogo! Por favor insira seu nome:");
    nome = in.nextLine();
    System.out.println("Seja muito bem-vindo(a) " + nome);
    System.out.println("Você deseja avançar para qual direção?(w,a,s,d)");
    String comando = in.nextLine();

    if(comando.equals("w")) {
        System.out.println("Você avançou para frente");
        System.out.println("Surgiu um Inimigo! O que você deseja fazer?(a = atacar f = fugir)");
        comando = in.nextLine();
        while(!comando.equals("a") || !comando.equals("f")) {
            System.out.println("Escolha apenas as opções a ou f");
            comando = in.nextLine();
            return;}
            if(comando.equals("a")) {
                System.out.println("Você atacou o inimigo e o matou");
            }
            else if(comando.equals("f")) {
                System.out.println("Você foi um covarde e fugiu! ");
            }
    }

obs: Eu não coloquei outros códigos para o a,s,d porque estava testando primeiro com o w
Answer: Segue o código que executa conforme o esperado.
O return sai do while e não executa nenhum código abaixo dele saindo da função.
O seu while mesmo digitando "a" por exemplo continua o loop porque a segunda condição ainda é satisfeita !comando.equals("f").
Deixei os pontos anteriores comentados.
Como você esta começando a programação vai ser difícil, não desista, procure olhar o ponto que seu código falha e tente responder o por que ? Se você identificar uma tarefa específica procure na internet como resolver essa tarefa. No seu caso erra procurar um item em um Array de String.
import java.util.*;

class Help {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Random rand = new Random();
        String nome;
        System.out.println("Seja bem-vindo ao jogo! Por favor insira seu nome:");
        nome = in.nextLine();
        System.out.println("Seja muito bem-vindo(a) " + nome);
        System.out.println("Você deseja avançar para qual direção?(w,a,s,d)");
        String comando = in.nextLine();
        String [] optionsAF = { "a", "f" };

        if(comando.equals("w")) {
            System.out.println("Você avançou para frente");
            System.out.println("Surgiu um Inimigo! O que você deseja fazer?(a = atacar f = fugir)");
            comando = in.nextLine();
             //while(!comando.equals("a") || !comando.equals("f")) {
            // conforme a documentação [Arrays.binarySearch()][1] vai retornar um int >= 0 se achar o elemento
            while(Arrays.binarySearch(optionsAF, comando) < 0) {
                System.out.println("Escolha apenas as opções a ou f");
                comando = in.nextLine();
                // return; // nao deixa executar os codigo a baixo, saindo da função autal
            }
            if(comando.equals("a")) {
                System.out.println("Você atacou o inimigo e o matou");
            }
            else if(comando.equals("f")) {
                System.out.println("Você foi um covarde e fugiu! ");
            }
        }
    }
}