Distribution of the minimum of $ 5 $numbers drawn out of $ 1,...,13$ urn with returns

Question: An urn contains $10$ white balls, marked by the numbers $ 1, 2, . . . , 10$,
and $3$ blue balls, marked by $11, 12, 13$.
$5$ balls are drawn randomly
a) With replacement.
b) Without replacement.
Find the distribution of the minimum of the numbers marked on the balls.
I started a) by marking $\{x\}_{i=1}^5$ the result received at stage $i$.
As $ x= \min{\{x\}_{i=1}^5}$ and $k$ is the minimum number drawn, we could say that:
$P(x\le k) = P(\min{\{x\}_{i=1}^5} \ge k) =* $

Because $ {\{x\}_{i=1}^5} \ge \min{\{x\}_{i=1}^5} \ge k $ then $ {\{x\}_{i=1}^5} \ge k $

= $ P((x_1\ge k) \cap (x_2\ge k) \cap...\cap  (x_5\ge k)) = *$

The Balls are independent

= $ \prod_1^5P(x_i \ge k) = * $

$ P(x_i \ge k)= \frac{13-k}{13}$

$ (1- \frac{k}{13})^5. $
Am I on the right path?
Thanks in advance.
Answer: Clearly, the ball color is irrelevant as the problem is posed.  So let's look at the general case of draws from a discrete uniform distribution on the set $\{1, 2, \ldots, m\}$.  In this case, when draws are with replacement, the minimum number drawn is given by the order statistic $$X_{(1)} = \min(X_1, X_2, \ldots, X_k)$$ where each $X_i \sim \operatorname{DiscreteUniform}(1,m)$.  Then $$\Pr[X_{(1)} \ge x] = \prod_{i=1}^k \Pr[X_i \ge x] = \left(\frac{m-x+1}{m}\right)^k,$$ hence $$\Pr[X_{(1)} = x] = \Pr[X_{(1)} \ge x] - \Pr[X_{(1)} \ge x+1] = \frac{(m-x+1)^k-(m-x)^k}{m^k}, \quad x=1, 2, \ldots, m.$$
In the case without replacement, let $Y_k$ represent the minimum value observed from a sample of size $k$, with $1 \le k \le m$.  Clearly, there are $\binom{m}{k}$ possible distinct (irrespective of order) $k$-subsets that could be observed.  Suppose a randomly chosen $k$-subset has the form $$S_k = \{s_1, s_2, \ldots, s_k\}, \quad 1 \le s_1 < s_2 \ldots < s_k \le m.$$  Then $Y_k = s_1$ by construction.  How many subsets satisfy $s_1 = y$?  There is only one way to choose the first element.  Of the rest, there are $\binom{m-y-1}{k-1}$ ways to choose the others; therefore, $$\Pr[Y_k = y] = \frac{\binom{m-y}{k-1}}{\binom{m}{k}}, \quad y = 1, 2, \ldots, m-k+1.$$
Answer: Most of what you have in part (a) looks correct; however, I have a couple of points to correct. If $x=\min{X_i}$, then $\mathbb{P}(x\geq k)=\prod\mathbb{P}(X_i\geq k)$. Additionally, $\mathbb{P}(X_i\geq k)=1-\frac{k-1}{13}=\frac{14-k}{13}$, so $\mathbb{P}(x\geq k)=\left(\frac{14-k}{13}\right)^5$.
Do you have any thoughts on (b)? I have a few helpful computations (maybe more than helpful). I start by computing the highest possible value of $x=9$. The value $\binom{13}{5}=1287$ is useful here.
\begin{align*}
\mathbb{P}(x=9)&=\frac{1}{1287}\\
\mathbb{P}(x=8)&=\frac{1}{1287}\cdot\binom{5}{4}\\
\mathbb{P}(x=7)&=\frac{1}{1287}\cdot\binom{6}{4}\\
\mathbb{P}(x=6)&=\frac{1}{1287}\cdot\binom{7}{4}...
\end{align*}
If you continue in this pattern, you will have all of the outcomes! The binomial terms come from fixing the minimum value and allowing four free choices larger than the minimum.


Visualizing Multicollinearity: How does overlapping region of IVs contribute to R²?

Question: I have trouble understanding how R² in a regression analysis makes sense visually in Ballantine diagrams.
For instance:

Obviously the red region is ignored when estimating the coefficients for x on y and w on y. But the red region must still be in the model somehow, otherwise we lose information that is useful in predicting y.
The typical practical example is high multicollinearity, a large R², but non-significant predictors.
I assume that the red region is implicitly part of the model although it is not used when estimating the coefficients. But how exactly?
Comment: This is called a "Ballantine" (not a Venn diagram as some respondents and even authors claim).  The Cohens popularized it in the 1970's and 80's in the social sciences, but it did not become commonplace. I have found it to be less than useful. Some of its problems are described in [Hunt (1986)](https://link.springer.com/article/10.3758/BF03204399), who writes "there is an exact analogy between the percentage of one circle that intersects another and the squared correlations ... Unfortunately, the analogy ... does not hold for multiple, partial, and semipartial correlations."
Comment: To state the criticism briefly, the overlaps among *pairs* of circles graphically indicated *bivariate* correlations, but nothing here directly represents the *multivariate* correlations in which one is usually interested.
Comment: @whuber: Sure, Ballantine or Ballentine (as called by Kennedy) is more accurate, but I guess most people just call it Venn as this is better known. Linux is actually GNU/Linux but nobody calls it that way, there are thousands of such examples. Anyway, your answer is: the analogy does not hold, which is a good answer!
Comment: Because the relative areas (and even the actual shapes) in a Venn diagram are meaningless but are crucial in the Ballantine, it truly is important to distinguish the two kinds of diagram, even though superficially they might look similar.
Comment: Alright, you convinced me, I changed Venn to Ballantine.
Comment: Notice that the correlation matrix of any $k$ random variables, and therefore, the regression of any one of them against the remaining $k-1$ variables, is completely determined by the $k(k-1)/2$ correlation coefficients, represented by the actual areas of the intersections of pairs of circles. Consequently, the red area is a definite function of those three correlations. Whether it has some directly interpretable meaning could be established by geometrically working out a formula for that area.  (It's not appetizing.) You might be pushing the area analogy too hard... .
Comment: Actually I had thoughts going in this direction, but I did not know how to proceed. I am still missing the intuition on how exactly the red part as a definite function of the three correlations manifests in the regression. Anyway, I guess the analogy can be useful in certain cases, even when ignoring the red region. For instance, high R² with poor predictors makes sense with the Ballantine. The red region is not used to estimate the coefficients, but is somehow still part of the model. I can accept that for now.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/146374/discussion-between-johannes-titz-and-whuber).
Answer: I cover collinearity here where you'll see reasons why collinearity is usually not to be feared when looking at overall model properties such as $R^2$.  Collinearity comes into play when attempting to interpret an effect of a variable that is collinear with other variables.  Descriptive analyses that help include variable clustering and redundancy analysis.  Also, chunk tests are your friend.
Comment: Thanks, but that does not really answer my question.
Answer: From my experience, I have found the Venn diagram explanation for correlations (partial, semi-partial, etc.) to be somewhat confusing and not always an accurate model of what is actually happening (or might happen).
The key here is that there are two types of correlations that we could examine in the presence of another variable.  The first is the partial correlation.  This correlation removes all of the influence of the 2nd independent variable from both the predictor and the response.  Thus, using the Venn diagram, this would be $\frac{B}{Y+B}$ (for yellow and blue)...and technically, this is the square of the partial correlation (the "partial" coefficient of determination, if you will).
However, there is also the semi-partial correlation.  This correlation removes the influence only from the other predictor (but it does not remove the influence from the response variable).  Thus, this correlation would be represented as $\frac{B}{Y+B+G+R}$ (again, this is technically the square of the semi-partial correlation).
Now the tricky part is that there are two types of $R^2$ we might talk about here...and these depend on the way we choose to break down the variation of the response variable.  The first of these $R^2$ uses the semi-partial correlations, and as a consequence, that shared overlap is not actually ignored.  The second of these $R^2$ uses the partial correlations...and in this case, if you were to add up the corresponding "variability" estimates for the response variable, you actually would be missing some of it.  (Or weirder still, you can actually end up with more variability than you start with...and this is why I find these diagrams to not be the best model for explaining the partitioning process very well.)
Happy to clarify more if needed.
Comment: I am aware of partial and semipartial correlations. Obviously regression coefficients are similar to semipartial correlations (with the denominator being squared). This does not answer my question though. In your example B/(Y+B+G+R) the red part is still ignored because it is not treated as explained variance. Only blue and green are, right? That's what my question is about. How does the red region enter the model?
Comment: The red region would enter the model in the Type-I version of the decomposition of the sums of squares.  The first variable would be the only predictor in the model, and the red region would show up there.  The second variable would be the variable accounting for whatever is left over to be accounted for (no red region).  This process would continue until all variables have been entered into the model.
Comment: Are you sure? In your description high multicollinearity would lead to one predictor being significant, the other not. But this is not what usually happens. Imagine a correlation between predictors of close to 1 (e.g. 0.99). Almost no information is available to accurately estimate the coefficients so neither will be significant. Also: If both variables enter the regression, who decides what is the "first" one?
Comment: Your statement "one predictor being significant" suggests that you are focusing on Type-II sums of squares decomposition.  This is not the only way you can assess the variance decomposition components.  And your last query is moving into the realm of model building.  With Type-II analyses, you get the same results if you enter the variables in any order.  With Type-I analyses, you can get different results based on the order the variables are entered in the model.  So, the model builder must decide.


Semantic distance between excerpts of text

Question: I'm wondering how far along the natural language processing is in determining the semantic distance between two excerpts of text.
For instance, consider the following phrases

Early today, I got up and washed my car.
I cleaned my truck up this morning.
Bananas are an excellent source of potassium.

Clearly (to the human reader) the first two statements are much more similar to one another than they are to the third statement.  Does there exist any methodology that would allow a computer to draw the same conclusion?
(Ultimately I'm trying to group Twitter tweets according to semantic content.)
Answer: It is far from obvious, and indeed is highly task-specific, when two sentences are similar enough to, say, group together in a cluster.  The problem is not determining which of

I cleaned my truck up this morning.
Bananas are an excellent source of potassium.

is more similar to

Early today, I got up and washed my car.

It's determining which of these is more similar:

Early today, I got up.
Early today, I took a bath.
Yesterday I went to a car wash.
Today I'm going to look at new cars.
It rained on my car yesterday.
I do plenty of work around the house.
The kids got the car filthy today.  Why doesn't my husband discipline them more.
Jane's car, freshly washed, was hit by three of the eggs.

etc, etc. etc.
One can make up task contexts when any of the above, and many more are the most similar.  You want to think very carefully about your goals first, before you assume a particular general purpose technology (Wordnet, a particular unsupervised learner, whatever) will do what you want.
And it's a good idea to have someone not invested in the technology do a blind evaluation of it.
Answer: Check out the work by Jones & Mewhort (2007). This more recent work may also be of interest, particularly their online tool.
Comment: The link to `springerlink.com` is broken. I'm also unable to find any copy saved on the Wayback Machine.
Answer: Lets suppose we can calculate the distance from one noun to another in the following way. Use the Worldnet (which I guess you know), and utilize a function that exists, but you can build it yourself, that counts for how many points of the taxonomy of words you need to get from one word to another (for example from cat to dog you might have 4 but from nail to music you might have 25) Then using this numbers calculated among the nouns of the sentences just invent a metric (for example use simply the average of distance between the nouns, or use the minimum distance between the nouns) that will help you carry on your task.
Comment: I assume you mean http://wordnet.princeton.edu/?  I was not aware or this, but it might be useful.
Comment: You might be interested in my next question: http://stats.stackexchange.com/q/7313/1026
Comment: I strongly recommend you to check wordnet, and yes is the address you posted. And I am glad you posted that question, It looks like what I recommended worked.


How do we use LIKE operator or LIKE condition in DynamoDB?

Question: I would like to get the list of data / records, which are like '%JUICE%' in DynamoDB
is there any way to fetch the data like this?
Comment: did you read this https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SQLtoNoSQL.ReadData.Query.html
Comment: Is the field you are searching a primary key or a regular item attribute?
Answer: DynamoDB is not good at wildcard searches.  That being said, you do have a few options available to you:

You can use the begins_with operator with sort keys.  The docs say

begins_with (a, substr)— true if the value of attribute a begins with a particular substring

The contains operator can be used on FilterExpression of scan operations on data types STRING, SET or LIST.  More info in the docs.

Keep in mind that using the contains keyword on scan operations will be an inefficient way to implement wildcard searches in DynamoDB.  You may be better off implementing this type of search outside of DynamoDB.  A common pattern is to use DynamoDB streams and Elastic Search to implement a more full-featured search capability.
Comment: Scans are quite expensive in DynamoDB but will offer that flexibility.


What java classes are associated with these nutch commands?

Question: I have the following commands which I've batched together. It runs Nutch and sends the results to Solr. I have read that these match up to Java methods which I'd like to use to run programmatically.
Which Java classes do these match up to?
<code>bin/nutch inject crawl/crawldb urls(text file containing list of urls)
bin/nutch generate crawl/crawldb crawl/segments
export SEGMENT=crawl/segments/`ls -tr crawl/segments|tail -1`
bin/nutch fetch $SEGMENT -noParsing
bin/nutch parse $SEGMENT
bin/nutch updatedb crawl/crawldb $SEGMENT -filter -normalize
bin/nutch invertlinks crawl/linkdb -dir crawl/segments
bin/nutch solrindex http://localhost:8080/solr/ crawl/crawldb crawl/linkdb crawl/segments/*
</code>
Thanks
Comment: This repo may help you understand what's going on inside: https://github.com/yegor256/nutch-in-java
Answer: See: Nutch - Commandline Options
Click on the respective command for each of the commands you've listed and the destination page will outline which class is being used:
For example:

nutch inject - bin/nutch_inject
Answer: Follow this guide. The class names are generally same with the command names. Look for the classes with main in them.


Angular Erro ao mudar de estado, comunicação entre components via serviço

Question: podem me ajudar:
Error: ExpressionChangedAfterHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'attr.aria-describedby': 'msg-default'. Current value? 'id-0'
Estou usando um serviço para pegar o id do componente "app-msg-erro" e passar para o atributo do input do component "app-radio-button", esta passando OK, mas no console estou recebendo o erro a cima.
Segue cód:
erro.service
<code>``
    export class MsgErrorService {

    private _msgError = new BehaviorSubject<string>('msg-defaut');

    currentMsg = this._msgError.asObservable();

    constructor() {}

    changeError(msg: string) {
      this._msgError.next(msg);
    }

``
</code>
Cód do component
<code>``
        export class ErrorComponent implements OnInit {

        constructor(private msgErrorService: MsgErrorService) {}

        @Input()
        @HostBinding(attr.id)
        errorMsgId: `msg-erro-${id++}`
        }

    ngOnInit(){
     this.msgErrorService.changeError(this.errorMSgId);
    }

    ``
</code>
Answer: pesquisando encontrei duas soluções.
uma seria passar a linha abaixo dentro do constructor opção 1
<code> constructor(private msgErrorService: MsgErrorService) {
    this.msgErrorService.changeError(this.errorMSgId);
 }
</code>
E/ou usar um if e verificar a variavel que recebe o ID, opção 2
<code>export class ErrorComponent implements OnInit {

        constructor(private msgErrorService: MsgErrorService) {}

        @Input()
        @HostBinding(attr.id)
        errorMsgId: `msg-erro-${id++}`
        }

    ngOnInit(){
     if(this.errorMsgId) {
        this.msgErrorService.changeError(this.errorMSgId);
     }

    }
   }
</code>


Pass parameters to external JS file with drupal_add_js()

Question: My organization is using Eloqua, and to this point have been using the Eloqua module. The main point of this module is just to determine where the external tracking script should be loaded on the site, and then load the external script while passing it a couple of parameters. This call is creating a huge performance hit, and so after talking to Eloqua support, I copied the external file to the site so it could be cached. Since we need the file to be loaded for every page, we really don't need the module, and so all we really need to do is load the file and pass it the required parameters
The problem is determining how to pass the required parameters to the script. Here is the current eloqua.js:
var _elqQ = _elqQ || [];

(function ($) {

  Drupal.behaviors.eloquaTracking = {
    attach: function (context, settings) {

      _elqQ.push(['elqSetSiteId', Drupal.settings.eloqua.siteId]);
      _elqQ.push(['elqTrackPageView']);

      function async_load() {
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.async = true;
        s.src = '//img.en25.com/i/elqCfg.min.js';
        var x = document.getElementsByTagName('script')[0];
        x.parentNode.insertBefore(s, x);
      }
      if (window.addEventListener) {
        window.addEventListener('DOMContentLoaded', async_load, false);
      } else if (window.attachEvent) {
        window.attachEvent('onload', async_load);
      }
    }
  };
})(jQuery);

The _elqQ array is accessed by elqCfg.min.js, so I need to make it accessible to the script with the elqSetSiteId and elqTrackPageView parameters. Is there a way to do that while adding elqCfg.min.js via drupal_add_js() in template.php or somewhere else?
CLARIFICATION: What I'm looking for here is a way to include this file and pass the parameters to it without having to create a whole module. That seems like a lot of unnecessary overhead for this one file.
Comment: No, the way you have declared it makes it global. Make sure this script comes before the minified script you reference, and the _elqQ variable will already be accessible by your minified script.
Comment: I'm sorry, I've re-read your post a couple of times, but you lost me with everything you wrote after the code block. I can't tell what the problem is, how the scripts relate to each other, or what exactly the problem you are having is.
Comment: Sorry. I have copied the external file to my site, and I just need to 1) load that file on each page load and 2) pass it the two values that are stored in the `_elqQ` variable in the code above.
Comment: You can load that file on every page load by including it in a module or theme .info file. You can pass the variables by implementing hook_page_alter(), using drupal_add_js() and adding a JS setting.
Comment: Right, I get that. However, just adding it to `Drupal.settings` doesn't automatically make it available in the `_elqQ` array, which is what the script is looking for. Do I need to use a behavior as a wrapper to do that?
Comment: OK, I don't think you're understanding. I'll update the question itself to clarify, but what I'd like to do is include this file and pass the variables to it **without** having to create a whole module just for including this one file.
Comment: He's saying you just need to ensure that file is loaded first and then you should have access to that object.
Comment: _I'll update the question itself to clarify, but what I'd like to do is include this file and pass the variables to it without having to create a whole module just for including this one file._  <- Then you can do it in the theme.
Answer: I ended up just going with a modification of the current code. I modified the behavior above so that it just loads the variables:
var _elqQ = _elqQ || [];

(function ($) {

  Drupal.behaviors.eloquaTracking = {
    attach: function (context, settings) {

      _elqQ.push(['elqSetSiteId', Drupal.settings.eloqua.siteId]);
      _elqQ.push(['elqTrackPageView']);
    }
  };
})(jQuery);

and then used drupal_add_js() to load the tracking file in my module
drupal_add_js(drupal_get_path('module', 'eloqua') . '/elqCfg.min.js');


What's the optimal way to check multiple columns for a single record?

Question: How do I create a select all statement that checks multiple columns in a single row for one value and if it doesn't have the value then exclude it from the query?
Comment: Do all columns have to have that value or at least one?
Comment: Can you share some sample data and the result you're trying to achieve? It's a bit hard to follow what you're trying to do.
Comment: Possible duplicate: [questions/13916400/checking-multiple-columns-for-one-value](https://stackoverflow.com/questions/13916400/checking-multiple-columns-for-one-value).
Answer: You can do this pretty simply by reversing the normal in operator: value in (column1, column2, column3)
Comment: Ah this got it! Thanks Allan! Yeah I haven't used sql in awhile, still a little rusty!
Answer: Use a "reversed" IN():
select ....
from ...
where someValue in ( col1, col2, col3, ...)


Drawing a conclusion from data without a correlation to other supporting data

Question: I am looking for the word/phrase that is used to say that a (potential) erroneous conclusion has been drawn from data without having a correlation to other supporting data points.
For example, if someone has the dataset of the number of red cars sold in the US per month as Jan: 10, Feb: 10, Mar: 9, Apr: 8, May: 7, etc. and draws the conclusion of "Red cars are going out of style" without correlating this data to total car sales for the same time period, or the number of other color cars sold, etc.
This conclusion might be correct if there was data showing that car sales as a whole have not declined, but this conclusion could be false if car sales as a whole have declined, etc, etc.
Is this called "Sampling Bias" or something else?
Answer: I am not clear that you need a technical term here. In your example, someone is jumping to a conclusion based on looking at some of the data only.
We often do that in real life, as when we judge something or someone by first or brief acquaintance. Sometimes it works; sometimes it doesn't. When we judge the temperature of a bath or the sea by dipping in a toe, or check whether some cooking is ready by tasting a small amount, that usually works. When we judge someone on a first date by something embarrassing, that might be right and it might be wrong.
Note also that correlation has a very specific meaning in statistics, which you are not following here. Informally, it does have a broad sense of comparison, but within statistics, there is a precise defined meaning.
Answer: What you're describing can be summarized as "no control or comparison condition."


How to add data toggle to link tag if ul is present in the li

Question: Please see the below code i have for my main menu on my website.
I want to add a data-toggle to the link tag for the dropdown but when the li doesnt contain ul I dont want the data-toggle added to the a tag. Would jquery be able to do this?
I am using bootstrap for this but in my menu I have menu links with no dropdown and the link url i add doesnt work as its expecting a dropdown to appear, if there a way around this?

        Menu 1

Menu Item

        Menu 2

        Menu 3

        Menu 4

        Menu 5

Comment: Hey Paddy, what have you got so far? It sounds like you are trying to dynamically generate the `data-toggle` but you've only shown us some static HTML. Are you rendering things server side or client side? Is your HTML static? In general we need more information.
Answer: Try this:
$('.dropdown').each(function() {
    if ($(this).find('UL').length === 0) {
        $(this).find('A').data('toggle', true);
    }
});

Answer: This is better, any li inside the ul.nav that has a child ul will have data-toggle added.
$("ul.nav li ul").parent().attr("data-toggle","")

Answer: You could also use the :has selector
$(function() {
    $(".dropdown:has(ul) a").attr("data-toggle", /*value here*/);
});

Answer: Both answers are correct, this is just another option using the :has selector. It's also a one-liner :)
$("ul.nav > li:has(ul) a").attr("data-toggle","");


Downloading with U-Boot's tftp randomly times out

Question: I have a custom board with TI OMAP SoC. I'm trying to download uImage from linux machine
via U-Boot's tftp. It fails with timeouts (most of the tries timeout limit exceeds and very rarely it gets through) on several, but
succeeds on others. However any other combination not involving U-Boot is flawless. Even
when the board in question has booted kernel. Comparing network settings (incl. sysctl)
gave no significant difference between serving machines, which run Linux.
Following tests were taken:

u-boot <-> i686-pae Linux
u-boot <-> i686-pae Linux kvm guest
u-boot <-> x86_64 windows 7

Results are as follows:

u-boot <-> i686-pae Linux

Using DaVinci-EMAC device
TFTP from server 192.168.100.254; our IP address is 192.168.100.88
Filename 'uImage'.
Load address: 0xc0700000
Loading: ############T ###############################T ##########T ############
              #######T ################################################T ##########
              ##########################T #######################################
              ###########################T ######################################
              ################################T #################################
    #################################################################
              ########T #########################################################
              ##################
              11.7 KiB/s
done
Bytes transferred = 2418464 (24e720 hex)
Corresponding traffic dump can be found here:
http://pastebin.com/hBBwe9bL

u-boot <-> i686-pae Linux kvm guest

Using DaVinci-EMAC device
TFTP from server 192.168.100.112; our IP address is 192.168.100.88
Filename 'uImage'.
Load address: 0xc0700000
Loading: #################################################################
#################################################################
#################################################################
#################################################################
#################################################################
#################################################################
#################################################################
          ##################
          795.9 KiB/s
done
Bytes transferred = 2418464 (24e720 hex)
Corresponding traffic dump can be found here:
http://pastebin.com/ZXYdpmSe

u-boot <-> x86_64 windows 7

Using DaVinci-EMAC device
TFTP from server 192.168.100.86; our IP address is 192.168.100.88
Filename 'uImage'.
Load address: 0xc0700000
Loading: #################################################################
#################################################################
          ###################################
          173.8 KiB/s
done
Bytes transferred = 2418464 (24e720 hex)
Corresponding traffic dump can be found here:
http://pastebin.com/UWFEZjTz
At this point I have no idea, what could cause timeouts for u-boot and I have no more
clues on how to solve this. Any help greatly appreciated.
It certainly has something to do with U-Boot network stack, but I believe this is the right place to ask this question.
I have read this article: http://www.denx.de/wiki/view/DULG/TFTPTimeout, however what is described there is not related to my situation since results do not depend on switches in-between.
What I have tried already: tftpd / tftpd-hpa; tftpblocksize=512; x86_64 linux kernel (tftp server); changing switch port settings to not aneg, but explicit full-duplex; as well as half-; adding/removing switches in-between; changing MTU at the serving machine; building latest U-Boot from source; varying server IP-address within /24; changing sysctl net. mem settings; sent a message to U-Boot mailing list, but got no reply; made static arp for U-Boot MAC.
Answer: As further experiments showed, the problem in this particular case was because of u-boot losing incoming packets coincidentally with --- NetLoop timeout handler set and --- NetLoop timeout, which I suppose is caused by either mac driver implementation in u-boot or u-boot networking handling itself. High pps of upstream Cisco switch might contribute to this because of rapid packet processing.
Successful transfers from Windows host are manifested by the fact that chosen tftp implementation has timeouts less than those of u-boot and as a consequence resending packets again, which happen to be captured by u-boot within its time limits.
Tests also show that setting #define TIMEOUT     8000UL at compile time or tftptimeout 1000 at run time allow for enough time for tftp server to retransmit lost packet allowing transmission to proceed. This is exactly what's observed with downloading from Windows host.
More testing showed that setting upstream switch port (not the same port, facing u-boot with the board in question) to 10 Mbit/s half-duplex solves transmission issue, however this significantly reduces the bandwidth available.
Answer: The problem:

The board betwork capabilities sure are way slower than the host counterpart.
Then the TFTP client after sending ACK N might immediately receive Data Packet N+1 when the board probably is not able to receive the packet yet (i.e. no full duplex)
After the missed packet both parties enter in a "waiting for timeout" mode.

Things to do:

Try your test on a very light network or even better a back-to-back connection
If your link is 1Gb/100Mb try slower if possible.
Try setting lower timeouts on the "server side"; this will force the server to wait less time before to resend the missed packet probably avoiding the client timeout.
If you have a TFTP Server able to control the "inter packet delay" make it higher.

If you still in trouble try capturing traffic with Wireshark and analyze the timeout traffic sequence
Comment: As per "(i.e. no full duplex)" it is also clear from the question itself, that I've tried different settings to no avail, so this assumption is also wrong. In the end your answer does not provide any clue on why transfers from Windows host succeed.
Now that I've made my point clear, care to elaborate on your downvote and provide some proofs for your satatements, namely: "you have no idea what you are talking about" and ""my" answer is in fact right"
Comment: How is your statement `Linux network driver and the u-boot network driver are completely different` related to `Your assumption of "board betwork capabilities sure are way slower" is in contradiction`?
Comment: When your board is driven by U-boot its network driver has a very poor performance, if you manage to run the "same" hardware under Linux its network driver will show a much higher performance. That's why when a bootloader/manager drives the NIC timing issues are very common.
Comment: Please refer to point 2 of the question. Do you consider `795.9 KiB/s` as `very poor performance`? I doubt it. Besides `The board betwork capabilities sure are way slower than the host counterpart.` does not mention neither U-Boot, nor Linux. Also, please explain what timings you are talking about. As you can see "T" timeouts do not happen at regular intervals, they are random.
Comment: Sorry, but point 1 in your answer is wrong as I mentioned no problems with networking when the board in question runs Linux kernel rather than u-boot. Quote: "However any other combination not involving U-Boot is flawless. Even when the board in question has booted kernel."
Comment: Since you insist I'd like to clarify this a little bit in more detail. Your assumption of "board betwork capabilities sure are way slower" is in contradiction with the fact that Linux kernel is fine with network capabilities of the board as it is clear from the question itself, as well as this assumption does not account for successful transfers from Windows host. With regard of "the board probably is not able to receive the packet yet" I must say that this does not hold true since board has enough capabilities for processing network packets as I've already mentioned,


Monotone one-way hash function

Question: I am sitting on a contradictory requirement in which I would need a function that is a one-way hash, but that is also monotone.
One-way: if $y=h(x)$, then computing $x=h^{-1}(y)$ is intractable, or at least, difficult. A textbook example could be SHA-2.
monotone: if $x_1 < x_2$, then $h(x_1) < h(x_2)$. In other words, the hashing would also preserve the order.
With these requirements a bit contradictory, does such function exist already? Would it still be possible to design one, or if not, would it conceivably be possible to construct an impossibility proof that such function cannot possibly exist?
Answer: If the order is preserved, then if we are given $h(x)$, we can find $x$ easily by doing binary search.
Therefore, such function cannot exist.
Comment: Where is the button for that? I cannot find one that says "accept". There is just: share, cite, edit.
Comment: @erik It is the little check mark below the upvote count.
Comment: There isn't one! Maybe that is a setting that the site admin has to switch on per user or so?
Comment: @erik See [this](http://meta.stackexchange.com/a/5235/320686).

Monotone one-way hash function


Weibull distribution parameterization

Question: I have the following Weibull distribution:
$f(x;\lambda,\beta) = (\lambda\beta)x^{(\beta-1)}e^{(-\lambda x^b)} $ where $\lambda$ is scale parameter and $\beta$ is shape parameter.
I have an alternative parameterization for Weibull in r link:
$f(x;a,b) = \frac{a}{b} (\frac{x}{b})^{(a-1)} e^{(- (x/b)^a)} $ where $a$ is shape parameter and $b$ is scale parameter.
How do you equate the shape and scale parameters from above distributions. Below is my solution. Clearly, I'm wrong.
> l=0.5
> b=2.5
>
> dwei <- function(x,l,b){
+   l*b*x^(b-1)*exp(-l*(x^b))
+ }
>
> dwei(x=2,l,b)
[1] 0.2089704
> dweibull(x=2, shape=b, scale = 1/l)
[1] 0.4598493

Answer: I think your order of operations is wrong. As a simplified example, $$\left(\frac{x}{2}\right)^2 = \frac{x^2}{4},$$ so in your pdf, you need $$(\lambda x)^{\beta - 1}=\lambda ^{\beta -1}x^{\beta - 1}$$ in the first product, and likewise inside the exponential function.
Putting it all together:
$$
f(x;\lambda,\beta)= \lambda \beta (\lambda x)^{\beta - 1}\exp\left(-(\lambda x)^\beta\right)
$$
and implemented in R to double-check:
dwei <- function(x,l,b){
   l * b * (l * x) ^ (b - 1) * exp( - (l * x) ^ b)
 }
dwei(x=2, l=0.5, b=2.5)
[1] 0.4598493

Which matches the R function output.

Weibull distribution parameterization


PHP MySQL multiple search word using array for word to word translation

Question: Pretty new to php and currently making a multiple array search word to word translator using MySQL database as source of the translation. Im using 1 table that has 2 column. The first column is language 1, and the second column is language 2. Language 2 is the translation of language 1. The process is i want to search multiple translation form language 1 and shows tho output of translation 2. Lets say for example user input "word3 word2 word5 word4 word1" from language 1 and the output of language 2 should be the same order by input like "translation3 translation2 translation5 translation4 translation1". But after splitting the string to array the problem by using OR in my sql query makes the result display in database order. If im not using OR the result will not be displayed. So the problem i want to solve is:

Shows the result of translation in order to what user input
Using the exact input word by user to find the translation
Show the result of translation with the repeated input word like word1 word1 word1 = translation1 translation1 translation1 if possible.

Please help if you have any solution as i cant seem to find any solution on the internet. Thanks. This is my code
<?php
if(isset($_POST['transl']))
{
$keyword = mysqli_real_escape_string($con, $_POST['input_text']);
$keys = explode(" ",$keyword);

$sql = "SELECT * FROM language WHERE language_1 = '".$keyword."' " ;

foreach($keys as $k){

    $sql .= " OR language_1 = '".$k."' ";

}
$result = mysqli_query($con, $sql);
if($result){

    while($row = mysqli_fetch_assoc($result)){

        echo $row['language_2'];
    }
}

echo $sql;
}
?>

Comment: Translating text isn't as straight forward as that. Grammar is different and some languages add words before prior to words, like `the`. Some languages change the word order so that it's word1 word3 word2.
Comment: this translator does not require grammar, its just a direct translator
Comment: @Bezman Did my post helped you? do you have other constrains?
Answer: You can load the words from your SQL with the OR query as you did and save as associative array - but when translate it I recommend you use 2 arrays with language_1 and language_2 and then use str-replace to swap the words.
Consider the following:
$dic = array();
while($row = mysqli_fetch_assoc($result)){
    $dic[$row['language_1']] = $row['language_2'];
}

Now you can take the keys (language_1) and the values (language_2) and use as:
$newSentence = str_replace(array_keys($dic), array_values($dic), $input);


Memorizing modes on guitar fretboard

Question: I'm comfortable with all 5 basic box positions and 7 3-note-per-string patterns for diatonic scale. I can switch among these positions fairly well. Problem is, when I try to emphasize on a mode, it feels like I'm drawing on a blank sheet. E.g., let's say I'm trying to play dorian. If I think of it as an independent scale, i.e. not relating it to its parent ionian, but using the intervals to define it, then I need to memorize all of its position from scratch. As the starting/ending note of this mode is different than that of the ionian, my existing knowledge of scale shapes doesn't help me. This is true for any of the modes.
So, at this point I've started to think if I'm missing something. Because memorizing all 7 mode would require memorizing 7*(5+7) = 84 shapes. I'm not very sure if that is the optimal way to do it. Any help is appreciated.
Comment: When I was learning the modes, I found it easiest to think of them as they compare to either a major or a minor scale.  Lydian is major with #4, Mixolydian is major with b7, Dorian is minor with Major 6, Phrygian is minor with b2 and Locrian is minor with b2 and b5.  There's still some memorization there but not necessarily having to consider every note, assuming you know major and natural minor well. It can also be helpful to connect them to songs/bands/genres. For example, Tool writes in Phrygian a lot, Grateful Dead's Fire on the Mountain is in Mixolydian and a lot of funk songs are Dorian.
Answer: I think there are three approaches complementing each other that work for most people:

See the modes as "filled up" pentatonic patterns (assuming you can dream those): ionian, mixolydian, lydian => major pentatonic; dorian, phrygian, aeolian => minor pentatonic (doesn't work with locrian because it lacks a perfect fifth, but who wants to play locrian anyway? :)
By the way, relying on pentatonic boxes and filling them up will be a nice addition to your 3-notes-per-string patterns, because you'll be able to play a mode in one position, without moving up the neck as you play on all 6 strings, as happens with 3-notes-per-string patterns.
You can use your knowledge of (7-note) scale patterns (e.g., ionian, if you know that one well). You'll learn to see the patterns just as patterns, without necessarily relating them to a root note (a mode). So there is only one diatonic pattern for all modes, just the roots are different. I know that you know that, but try to see it on the fretboard.
Also try to learn to play more intuitively, by ear. In order for that to work you need to learn two things: first, you need to be able to hear each mode (try to sing them); second, you need to be able to play what you hear. It's important to realize that after having learned both, you wouldn't need any patterns at all. You might not get there quickly, but work on it and you'll see that you get more and more independent of visual cues. (Exercise: close your eyes and play a mode up and down the neck).
Comment: @Bitswazsky: I think your formulation "the tonics as floating (pivot) points" is right to the point, that'll help you a lot. As for the 3rd point, just start working on it, it's fun and really necessary for becoming a better musician; it's indeed a never-ending journey, but even after a few weeks of practice you'll notice the difference in your playing.
Comment: Thank you for such a comprehensive answer. I'm aware of the 1st point, but never really thought it would help my understanding of modes. I'll surely explore it to greater detail. Your 2nd point basically hit the nail on the head. I was associating each pattern with ionian mode. I guess now I've to re-imagine each pattern as a container with the tonics as floating (pivot) points. And regarding the 3rd point, well I'd have to be at-least level 49 to reach there, but hey, better late than never.
Comment: It's useful to learn locrian so that if you want to move up or down the neck while improvising in one key you can change between the different modes as you move. Of course, you could jump from Aolian to Ionian while ascending, but that's just a patch that covers the gap.
Answer: Understanding modes really took my playing to the next level and introduced me to a bunch of different sound flavors. Playing different modes over pieces really changes the mood, and gives way to a lot of experimentation while in the home studio.
Of all the modes explanations, I found the approach offered at this link to be the best:
http://www.justinguitar.com/en/SC-501-ModesIntro.php
The reason it is the best is because this course actually teaches you to understand the parent scale for each mode in a certain key. Not just pick a scale and play from a certain note, like most teachers try to approach the subject. By sitting down and going through these lessons, when somebody says they are playing C Dorian, you will be able to quickly understand that he/she is playing the A# major scale and starting on the C note.
I studied scales at Berklee and really struggled with the modes part of that course. That required memorization of the various sharps and flats without a system. Also, sit down to a backing track in a certain key, and play all the modes across that track to understand the type of sounds that are produced.
Comment: Thanks for sharing that link, certainly a lot of good information there. Although this question was more about being able to play modes throughout the entire fret-board, assuming one has the ability to invoke a specific modal sound, It surely helps to come across different views on the subject.
Comment: I learned five different major scales at Berklee then mapped those scales to the relevant pentatonic scales as outlined in the CAGED system. That is outlined here:
http://www.groovenue.com/wp-content/uploads/2016/01/Berklee-Major-Mapped-CAGED-Pentatonic.pdf
Now I can play either pentatonic, major, or minor scale in five different keys in the same position. This knowledge and combined with that modes understanding, makes five different modes accessible from a single position in any given key-mode.
Comment: I might be nitpicking, but shouldn't C Dorian be rather be described as as having the notes of a Bb major scale than those of a A# major scale? A Dorian scale starts on the second note of the major scale, and the second note of the A# major scale is a B#. Sure B# and C are enharmonic in ET, but I still think it's much better. Using only sharps and exploiting enharmonics would render the scale as "A# C D D# F G A #A", which I think is very confusing compared to "A# B# Cx D# E# Fx Gx A#" (or "Bb C D Eb F G A Bb"). (I use x to denote double sharp)
Answer: There are way more than 84 shapes to learn.  They are worth practicing but if you are having trouble making melodic patterns that respect the mode then you don't have it in your ear and that's where it counts.  The guitar can become a very "pattern oriented" pursuit but at the end of the day you ear has to lead you.
One thing that helps is learning how the various patterns connect.  Starting with the major scale, it is just two tetra chords separated by a whole step (2 frets).  The beauty of the symmetry is that it's the same 4 notes.  SO you learn the 4 note lick, shift a whole step and play the same 4 note lick.  After some time you start to realize that there aren't really that many patterns.  Also, many of the scales have common patterns on 2 string pairs (E, A), (D, G) and (B, e).  This is a common shredder trick, play the following finger patterns shifting appropriately.  For example play (1, 2, 4) on (E, A), shift a whole step and repeat on (D, G) shift again then play on (B, e).  This is just Locrian minus one note (which is right under your index finger when you change string groups).  There are similar patterns.  My point is that in terms of finger dexterity once you get the basic patterns (1, 2, 4) + (1, 2, 4), (1, 3, 4) + (1, 3, 4), (1, 2, 4) + (1, 3, 4), (1, 3, 4) + (1, 2, 4) and a few others down all the patterns you are discussing fall into place without memorization.
As for learning to hear modes it would help to listen to good examples of music played on modes.  You mentioned Dorian.  Have you completely digested So What by Miles Davis?  Try transcribing the solos on that tune.  You can find plenty of examples of tune in all genres of music in various modes.  Another trick I teach my students is to take a simple common melody and play it in the different modes.  A simple example is the opening line to Joy To The World since it's just a descending major scale from 8 to 1, it is distinguished by the rhythm.  Play it in all the modes to hear the difference.  You can do this with any tune.
Comment: Side-note: If a 4-note lick is used and played as 2-notes-per-string (to ascend the major scale for example),
then it will also produce a rotatable 7-strings tall pattern where a unique mode can be associated with each of those
seven strings. Modes/degrees would then appear in the order 1,3,5,7,2,4,6,1. Also kinda neat, the first notes of each string spell out 'the' diatonic progression.

N-note-per-string patterns where N=1,2,3,4,5,6 also work, as they're all coprime to 7... they all make 7-strings tall patterns with a unique mode on each string.
Answer: The easiest way to visualise them on the guitar is to have you basic Major shape and then just begin and start on different notes on the scale.
If you, for instance, have you natural minor / Aeolian mode you can use your A major scale shape and just begin and end on F#. After all Aeolian mode is the one where you have C major beginning on A note.
You don't have to learn new scale shapes. Use the basic ones you already know and just start on the correct note.
Comment: Yes, but that is the approach that I warn against and gets most players no where to start with. I do agree that it is simple, but almost useless. With that understanding, if I look at a guitarist and tell him to play in F# Aeolian, then he will not know the parent scale. Or, he sits there staring into the air with his fingers moving up and down. Learn how to get the parent scale quickly FTW!!
Answer: Was going to elaborate in comment, but was way too long... elaborating because noticed the question was about 'around the fretboard'.
In reference to this link (and comment):
I learned five different major scales at Berklee then mapped those scales to the relevant pentatonic scales as outlined in the CAGED system. That is outlined here:
http://www.groovenue.com/wp-content/uploads/2016/01/Berklee-Major-Mapped-CAGED-Pentatonic.pdf
Now I can play either pentatonic, major, or minor scale in five different keys in the same position. This knowledge and combined with that modes understanding, makes five different modes accessible from a single position in any given key-mode.
Pattern 4 root is the pinky on the 1st or 6th string.
Pattern 3 root is the pinky on the 5th string.
Pattern 2 root is the pinky on the 4th string (or middle finger on 1st or 6th string).
Pattern 1 root is the pinky on the 3rd string.
Pattern 1A root is the pinky stretched one half step up on the second string. Or, the index finger stretched one whole step down on the first string (same note).
Beyond that the pattern starts all over. This gets me up and down and sideways on the fretboard in patterns, but also (usually) know what note I am hitting at the same time. That last part is just a matter of time and speed recognition, hearing...
So, if I am playing C-Dorian, then play an A# (and focus on the C note and iii-V-VII, etc...) major scale with any of the given patterns and connect sideways or play up-down the fretboard, connecting the patterns that follow. They connect just like C-A-G-E-D - 3-1-4-2-1A.
Answer: A little necro, but maybe future readers will be interested...
You could try rotating a single vertical 3-note-per-string pattern (that is 7 strings tall) when you go to play your modes. This might emphasize the modes as all being part of a single structure (an equivalence class defined using rotation equivalence) with relative relationships, rather than as separate independent things.
For example, on a 14-string guitar (to see the pattern twice) and tuned as [B, E, A, D, G, C, F, Bb, Eb, Ab, Db, Gb, B, E] (i.e. tuned in fourths, to ignore the standard tuning's +1 semitone correction on the B-string), the pattern for the major scale and all of its modes goes as (in C major)...
<code>--F-G-A- // String: 14, Pattern: W-W, Mode: Lydian,     Numeral: 4
--C-D-E- // String: 13, Pattern: W-W, Mode: Ionian,     Numeral: 1
--G-A-B- // String: 12, Pattern: W-W, Mode: Mixolydian, Numeral: 5
--D-EF-- // String: 11, Pattern: W-S, Mode: Dorian,     Numeral: 2
--A-BC-- // String: 10, Pattern: W-S, Mode: Aeolian,    Numeral: 6
--EF-G-- // String: 09, Pattern: S-W, Mode: Phrygian,   Numeral: 3
--BC-D-- // String: 08, Pattern: S-W, Mode: Locrian,    Numeral: 7
-F-G-A-- // String: 07, Pattern: W-W, Mode: Lydian,     Numeral: 4
-C-D-E-- // String: 06, Pattern: W-W, Mode: Ionian,     Numeral: 1
-G-A-B-- // String: 05, Pattern: W-W, Mode: Mixolydian, Numeral: 5
-D-EF--- // String: 04, Pattern: W-S, Mode: Dorian,     Numeral: 2
-A-BC--- // String: 03, Pattern: W-S, Mode: Aeolian,    Numeral: 6
-EF-G--- // String: 02, Pattern: S-W, Mode: Phrygian,   Numeral: 3
-BC-D--- // String: 01, Pattern: S-W, Mode: Locrian,    Numeral: 7
</code>
Each '-' is a fret/semitone and I used notes to show where your fingers go as well as the direction of ascension. Strings 01-07 are one instance of the pattern. Strings 08-14 are a second instance of the pattern.
You can vocalize the pattern as "two 1-2's, then two 2-1's, then three 2-2's", where 1-2 is in reference to S-W, etc... So, relatively cheap to memorize.
To play it on a standard tuned guitar, you need to "sharpen" the whole pattern when you ascend into the B-string, or "flatten" it when you descend from the B-string. Also, "sharpen" (or "flatten") the pattern when you restart it (for example, see the transition going from string 07 to string 08).
The B-string isn't too problematic, so I tend to think of the pattern as effectively transposable both vertically and horizontally (and I just auto-correct the B-string, like I do when tuning my guitar).
Additional Notes:

Similar patterns can be made for any heptatonic grouping of
rotationally equivalent scales. Again, similarly so for pentatonic groupings,
but I think it's often nicer to use 2-note-per-string patterns there.
For a pentatonic example, the pattern will only be 5 strings
tall, so you will see the full pattern on a guitar fretboard. Just
look at and/or try rotating the 2-note-per-string minor pentatonic
scale. (e.g. Play A minor pentatonic, then key change so that you
play it's third mode in the key of A, meaning just rotate the pattern
down one string... note: you'll need to first deduce the pattern and then
account for the B-string to do this correctly.)
The reason things work out well for heptatonic and
pentatonic scales is because they have prime numbers of notes.
N-note-per-string patterns are essentially in correspondence with different circles of
modes, and we can make full circles as long as
our 'delta' N is coprime to this total number of notes. (The numerals in the
"major grouping" above spell out a modal circle of thirds, roughly x+3 mod 7...
1, 4, 7, 3, 6, 2, 5, 1... and since all 7 degrees are present this circle is
full/complete, meaning all the modes are represented in the pattern.)
One "can" work out patterns for non-prime things like octatonic scales,
but the coprime condition still needs to be satisifed. To keep the
horizontal motion down, one can do something like use a
5-notes-per-2-strings pattern (5 being coprime to 8), but then the
string height is 2x8=16, so it may be more practical to try and view
such things as heptatonic scales with an additional chromatic passing
(and hence not care about representing the mode/degree of the chromatic
passing in the pattern). Going the other way, a similar argument could
likely be made for identifying the hexatonic blues scale with a
pentatonic scale (which we kinda do anyways), for example.

Edit: An Example Application Of Naming Notes On The Fretboard:

Naming notes on the fretboard can be seen as an instance of these
ideas. The pattern is 1-note-per-string and also follows a 'modal
circle', with the underlying scale being the chromatic scale.
The circle of course is the Circle of Fourths. So, you just pick a
note, then start going vertically up (e.g. along a fret), vocalizing
the Circle of Fourths to name all the notes in that "line" (you'll
also need to correct when you get to the B-string, but otherwise the
pattern won't shift like the major grouping did when going from string
07 to string 08).
The coprime condition applied to the chromatic scale means only 4 full
circles can be made (using a fixed 'delta'), because there are only 4
numbers less than 12 that are coprime to it. These numbers are 1, 11,
5, and 7, which are the circles of Minor Seconds, Major Sevenths,
Perfect Fourths, and Perfect Fifths, respectively. In mod 12 (roughly), 5 and 7
are inverses (as are 1 and 11).
This means that, up to clock-direction/handedness, there are essentially only
2 different circles for the chromatic grouping. On guitar, one of those circles
is what is travelled when you move horizontally (along a string) and the other
is what is travelled when you move vertically (along a fret).
(I say 'roughly' in mod 12 because I'm counting the modes/intervals/degrees
starting at 1 instead of 0 and doing that translation in my head.
For example, 12 mod 12 = 0, but I 've been calling it 1 in various places.
So rather than saying "x-1 mod N = Y => Degree=Y+1", I've just been saying
'roughly'.)

Memorizing modes on guitar fretboard


Count total posts related to a forum - PHP Logic

Question: I need some help with figuring out the logic for this, because in the most tutorials i saw, they just had to store a topics_count int in the database and every time a topic was created in that specific forum they would increase the topics_count +1 for the forum they were created in;
however can't we achieve this by getting a value using mysqli_num_rows instead? This would return the total rows (topics) in relation with a forum. But then the problem is how can i create that relation when the forums are inside an array.
Both forums and topics have an:

id
title
description

I am aware of the security problems. This example is just a practice.
This is how i display the forums from the database and echo a href to each forum.
                $array_forums = mysqli_fetch_assoc($res_forums);
                    echo "
";
                        echo "

";
                        echo "
";
                            echo "

";
                            echo "
";
                                    echo "";
                                        echo "
{$array_forums["forum_title"]}
";
                                    echo "";
                                echo "
{$array_forums["forum_description"]}
";
                            echo "
";
                        echo "
";
                        echo "
Topics
";
                        echo "
Replies
";
                        echo "
Lastposter
";
                    echo "
";
                }

This is how i display the topics in each forum, after a link is clicked.
            $forum_id = $_GET['forum'];

            //1. Perform database query for topics
            $sql_topic = "SELECT * FROM topics WHERE topic_forum_id = {$forum_id}";
            $res_topic = mysqli_query($conn, $sql_topic);
            //2. Display returned data from topics
            if (mysqli_num_rows($res_topic) >= 1) {
                $array_topic = mysqli_fetch_assoc($res_topic);
                echo "
{$array_topic["topic_title"]}";
                echo "
";
            } else {
                echo "Return To Forum Index";
                echo "
There are no topics in this forum yet.
";
            }

Comment: I am not being able to understand you requirement can you explain it
Comment: Basically this is the code i use to display the forums and the topics related to them, now i wonder how to implement a topic counter, to count how many topics there are inside a forum.
Comment: $sql_topic = "SELECT * FROM topics WHERE topic_forum_id = {$forum_id} COUNT(id) as count"; change id to something else if you dont  use id in your database. When you var_dump your $sql_topic, you'll notice 'count' as key and a value next to it. Can you try and let me know?
Answer: You can use count to count the number of rows
$sql_topic = "SELECT count(*) FROM topics WHERE topic_forum_id = {$forum_id}";
$row = mysqli_fetch_row($sql_topic);
$num = $row[0];

$num will return the number of topics in specific forum
Comment: great job, with your help i managed to do it. However i made a small tweak, because this needed to work in the same page as the forums, and i was getting the {$forum_id} once i click inside the forum, from the URL.
Answer: With the help of @Anil Shrestha , $num will serve as the topic counter.
                    $sql_topic = "SELECT count(*) FROM topics WHERE topic_forum_id = {$array_forums["forum_id"]}";
                    $res_topic = mysqli_query($conn, $sql_topic);
                    $row = mysqli_fetch_row($res_topic);
                    $num = $row[0];

Comment: Great keep it on bro


Satisfying one simple inequality

Question: I have the following inequality $$t^2 + 2t(B-1) \leq M/2.$$
Now I know that $t:=\sqrt{M/2+B^2}-B$ will satisfy it, I don't quite understand how the author came up with this definition of $t$.
How can one derive the above definition of $t$ from the inequality? I'm wondering why the author defined $t$ this way?
If someone asked you to define $t$ such that the inequality is satisfied, how would you answer?
Comment: Hmm, if you replace $B$ in the definition of $t$ by $B-1$, then RHS = LHS.
Answer: To solve the inequality
$$t^2+2t(B-1)-\frac{M}{2}\leq 0,$$
we must first solve $t^2+2t(B-1)-\frac{M}{2}= 0$. This has solutions
$$t=\frac{2(1-B)\pm\sqrt{4(B-1)^2+2M}}{2}=1-B\pm\sqrt{(B-1)^2+M/2}\,.$$
The solution to the inequality is therefore
$$1-B-\sqrt{(B-1)^2+M/2}\leq t \leq 1-B+\sqrt{(B-1)^2+M/2}\,.$$
However, the given value of $t$ only lies in this interval if $M>0$. This is because
$$\begin{aligned}
\left(\sqrt{M/2+B^2}-B\right)^2 +2\left(\sqrt{M/2+B^2}-B\right)(B-1)
&=\frac{M}{2}+2B-2\sqrt{M/2+B^2}\\
&\leq \frac{M}{2} \text{ only if } M>0 \\
\end{aligned}$$
Comment: I understand that the definition of $t$ satisfies the inequality. I'm wondering why the author defined $t$ this way? If I asked you to define $t$ such that the inequality is satisfied, how would you approach this problem?
Comment: I've edited my answer
Answer: Assuming $t > 0$,
$$
t^2 + 2t(B-1) \leq t^2 + 2tB.
$$
And if latter simply equals to $M/2$, by solving quadratic equation we get that value, $\sqrt{B^2 + M/2} - B$.
Note that's true only for $M > 0$.
Comment: For $M > 0$ you can also pick $t=0$.

Satisfying one simple inequality


$8y(t+2)-6y(t+1)+y(t)=2^t$ via Annihilator Method

Question: This question is taken directly from "Difference Equations: An Introduction with Applications",second edition,  by Walter G. Kelley and Allan C. Peterson:
Solve
$$8y(t+2)-6y(t+1)+y(t)=2^t$$
via the annihilator method.
Could someone show this in great detail, especially finding the homogenous equation solution for $2^t$?
Comment: Walt Kelley is also famous for the comic strip Pogo.
Answer: With constant coefficients these are similar to differential equations.
The roots of $ 8 \lambda^2 - 6 \lambda + 1 = 0$ are $\lambda = 1/2, 1/4.$ Instead of $e^{\lambda t},$ you just take $\lambda^t.$ So our general solution with a $0$ on the right hand side is
$$ A \left( \frac{1}{2} \right)^t +  B \left( \frac{1}{4} \right)^t.  $$
Furthermore, any two solutions to the problem with $2^t$ on the right hand side differ precisely by such a sum.
Next, we get some good luck with $2^t.$ As we can check (and have already shown in general) the number 2 is not one of the $\lambda.$ As a result, if we add in $C \cdot 2^t$ to $y(t),$ we get something nonzero, in particular
$$ C \cdot 8 \cdot 4 \cdot 2^t - C \cdot  6 \cdot 2 \cdot 2^t + C \cdot  2^t = C \cdot  ( 32 - 12 + 1 ) \cdot 2^t = 21 \cdot C \cdot 2^t. $$ We then need $21 C = 1.$ So, with completely general constants $A,B,$ we get
$$ y(t) =  A \cdot \left( \frac{1}{2} \right)^t +  B \cdot \left( \frac{1}{4} \right)^t + \left( \frac{1}{21} \right) \cdot 2^t  $$
Comment: Very clean and nice, + 1!
Comment: @WillJagy: According to the book, the annihilator method first puts the equation in operator form; so I get $(8E^2-6E+1)y(t)=2^t$. Then we are supposed to solve $2^t$ in operator form again, which is where I'm confused. For example, another problem is $y(t+2)-7y(t+1)+6y(t)=t$. The book has this restated as $(E^2-7E+6)y(t)=t$. Then it says $t$ satisfies the homogeneous equation $(E-1)^2t=0$. I'm having troubles now finding what $2^t$ satisfies in this form. Could you walk me through this with explanation?
Answer: Three standard operators. Identity
$$  If(t) = f(t).   $$
Translation
$$ Ef(t) = f(t+1) $$
Difference
$$ \Delta f(t) = f(t+1) - f(t).   $$
Relation
$$  \Delta = E - I.  $$
Your book is using $1$ instead of $I,$ no real problem.
$$  E 2^t = 2^{t+1} = 2 \cdot 2^t  $$
In general,
$$  E \lambda^t = \lambda^{t+1} = \lambda \cdot \lambda^t.  $$
$$  \Delta \lambda^t = ( \lambda - 1) \cdot \lambda^t.  $$
For a constant funtion of $t,$
$$   E 1 = 1,$$
$$ I 1 = 1.$$
$$  \Delta 1 = E1 - I1 = 0.$$
$$ Et = t+1,   $$
$$ It = t,$$
$$ \Delta t = t+1 - t = 1.$$
So
$$ \Delta^2 t = 0.$$
Comment: Excellent!  I found it on my own, but this is what I was looking for.  So not to take away from your answer, +1.  Their "annihilator method" uses your translation operator to transform the rhs into an equation.  They then combine two equations with shift operators.  Anyways, thank you very much!
Answer: Just in case anyone's wondering, here's what I get via Kelley and Peterson's "Annihilator Method":
The equation gives us an equation in shift operators (i.e. Jagy's translation operator):
$$(8E^2-6E+I)y(t)=0$$.
$$8(E-1/2)(E-1/4)=0$$
which is similar to Dr. Jagy's answer.
Then $2^t$ satisfies the equation:
$$(E-2)(2^t)=0$$
So now we have, combining the two results:
$$8(E-1/2)(E-1/4)(E-2)y(t)=0$$
...which leads to...
$$y(t)=c_1(1/2)^t+c_2(1/4)^t+c_3(2)^t$$
We then see that $c_1(1/2)^t+c_2(1/4)^t$ satisfies the homogeneous portion of the equation.  So we substitute $y(t)=c_3(2)^t$ into the original equation/question:
$$8c_3(2)^{t+2}-6c_3(2)^{t+1}+c_3(2)^t=2^t$$
$$c_3=1/21$$
Then we plug this in:
$$y(t)=c_1(1/2)^t+c_2(1/4)^t+\frac{1}{21}(2)^t$$


Programação Funcional e Programação Orientada a Objetos. O que são e quais suas principais diferenças?

Question: O que são e quais as principais diferenças entre Programação Funcional e Programação Orientada a Objetos?
Comment: @CarlosCinelli Tentei responder da forma mais sucinta que pude, mas também senti que na forma como está ela está muito ampla. Uma forma de melhorá-la seria colocar parâmetros que guiem as respostas (em vez de deixar segundo a interpretação de cada um). Pois se várias boas respostas surgirem - cada uma abordando a pergunta por um ângulo diferente - como você vai escolher uma como "certa"? E isso - a *possibilidade* que seja de se aceitar uma resposta - é o que diferencia uma "pergunta" de uma discussão aberta (o que, mesmo que frutífera, não se adequa ao formato do site).
Comment: @mgibsonbr não sei se o problema aqui seria ter várias respostas certas e não saber qual escolher! Por exemplo, uma questão bem simples e direta como esta ( http://pt.stackoverflow.com/questions/7527/como-consolidar-agregar-ou-agrupar-os-valores-em-uma-base-de-dados) teve 4 respostas corretas e escolher uma delas foi arbitrário, pois nenhuma é intrinsecamente melhor! Concordo que a pergunta está um pouco aberta, mas penso que, apesar de a pergunta pode ser vista ângulos diferentes, existe um noção de completude para julgar uma resposta como mais completa e as outras como complementares!
Comment: Concordo com o @mgibsonbr (e a resposta dele me ganhou na primeira frase). O que te interessa mais na pergunta, programação funcional ou orientação a (ok, *por*) objetos? Não são dois conceitos diretamente comparáveis.
Answer: Na teoria, comparar esses dois paradigmas não faz sentido: a programação funcional, a programação imperativa e a programação em lógica (dentre outras) referem-se à maneira como uma determinada computação é descrita - respectivamente, em forma de funções matemáticas (cálculo lambda), em forma de instruções explícitas para a máquina (arquitetura de Von Neumann), e em forma de predicados lógicos a serem provados por indução (resolução em lógica de primeira ordem com retrocesso). Já a programação orientada por objetos tem mais a ver com a forma que as estruturas de dados de um programa são combinadas/unidas com as subrotinas que lidram com essas estruturas (i.e. junta-se os dados e o comportamento numa mesma estrutura lógica).
Ou seja, pode-se ter uma linguagem que é ao mesmo tempo funcional e orientada por objetos - da mesma forma que pode-se ter uma que não segue nenhum dos dois paradigmas.
Na prática, a maioria das linguagens orientadas por objeto seguem o paradigma imperativo, e da mesma forma muitas linguagens funcionais (como Lisp) incluem características não funcionais - como variáveis de estado. Por essa razão, no restante da resposta vou considerar a orientação por objetos num contexto imperativo - ainda que em princípio seja possível aplicá-lo a outros contextos.
Programação Funcional
A programação funcional baseia-se no conceito matemático de função, em que para cada elemento do seu conjunto domínio (entrada) há apenas um elemento no seu conjunto contra-domínio (saída). Além disso, as funções são normalmente expressas por meio de outras funções - de modo que obter o valor da função para um determinado conjunto de parâmetros envolve não só aplicar as regras daquela função, mas também fazer uso de outras funções.
Por essa razão, a programação funcional não possui o conceito de "variáveis de estado"; se um valor qualquer (seja ele numérico, textual, um vetor, matriz, ou algo mais complexo) aparece num momento qualquer da computação, considera-se que aquele valor é único e imutável durante todo o processo. Pode-se estabelecer relações entre valores - como dizer que 2 é a metade de 4 - mas o valor 2 sempre será um 2 e o 4 sempre será um 4.
Programação Orientada por Objetos
Na programação imperativa considera-se que as estruturas de dados (de novo, números, texto, vetores, matrizes, etc) existem em um determinado estado, e que através de comandos específicos para o computador esse estado vai sendo alterado no decorrer do programa, de modo que ao final da execução ele represente as consequências de um processo lógico. Os comandos disponíveis são fixos pela linguagem, e normalmente há comandos distintos para tratar de tipos de dados distintos.
O conceito de "objeto" é uma extensão desse comportamento para além dos tipos de dados da própria linguagem, aplicando-os também aos tipos definidos pelo usuário: para cada estrutura de dados definida, define-se também uma série de operações que podem ser aplicadas a esse estrutura - em geral influenciadas pelo seu estado interno - e a partir de então permite-se usar essas estruturas como tipos distintos, e não como estruturas de dados genéricas. Some-se a isso o conceito de "tipos mais genéricos" e "tipos mais específicos" (i.e. herança), e temos a possibilidade de criar uma taxonomia rica de tipos cada um com suas operações - de modo que os programas possam ser expressos num nível de abstração mais alto do que aqueles que utilizem somente os tipos fornecidos pela linguagem de programação em si.
Quando os objetos e suas relações são o ponto central de uma linguagem de proramação, diz-se que ela é "orientada por objetos" (ou, no popular, orientada a objetos) - pois todo o fluxo lógico do programa se baseia em quais objetos existem e como eles interagem entre si. Ou seja, inicialmente esses objetos estão lá - em seu estado inicial - e à medida que o programa interage com o seu ambiente (seja atraves de uma entrada, ou através da interação com o usuário) esse objetos vão mudando de estado.
Semelhanças

Da mesma forma que uma função possui domínio e contra-domínio, um objeto possui operações que somente são aplicáveis a ele em particular.
Assim como um conjunto pode possuir subconjuntos, um objeto pode ter subtipos; e tal como um elemento do subconjunto pode ser usado como parâmetro para uma função que tem o conjunto principal como domínio, um objeto do subtipo herda todas as operações do seu tipo base (i.e. elas se aplicam igualmente e ele).
Não ha [necessariamente] um ponto de entrada nem de saída num programa funcional: a princípio, qualquer uma de suas funções poderia ser chamada a partir de uma entrada interativa, por exemplo. Da mesma forma, um sistema orientado por objetos não estabelece um "início" nem um "fim" para o programa: cada "mensagem" enviada para um objeto causará uma série de efeitos (e talvez uma resposta), mas não há ordem predefinida para que mensagens serão enviadas.

Diferenças

A principal diferença é a questão do estado: uma função por definição não possui efeitos colaterais, ela apenas retorna um resultado a partir de um determinado conjunto de parâmetros. Consequentemente, duas ou mais chamadas da mesma função passando os mesmos parâmetros devem produzir resultados iguais - enquanto na POO o resultado pode variar conforme o estado do objeto no momento em que a mensagen foi enviada.
Como consequência disso, enquanto na POO um objeto pode ser ignorante em relação aos demais objetos que compõem o sistema (bastando ele conhecer seus vizinhos mais próximos e enviar mensagens a eles) - reduzindo o acoplamento - isso é mais difícil de ser atingido na programação funcional (e pela minha experiência, também na lógica) por conta da imutabilidade das estruturas de dados.

Exemplificando, se a entidade A possui uma referência para a entidade B, e o estado interno de B muda, não é preciso notificar A pois as mensagens subsequentes que elas trocarem serão influenciadas pela mudança de estado (em POO). Já no paradigma funcional, A e B são resultados de uma computação - válida agora e pra todo o sempre; se uma outra computação produziu um B', então é necessário se produzir também um A' de modo que a relação desejada entre o B "novo" e o A se adeque à sua nova configuração.

Por outro lado, essa independência em relação a um estado torna bem mais simples avaliar e depurar programas funcionais - pois eles podem ser testados parte-a-parte e o resultado do todo será idêntico à soma das partes. Enquanto que no POO às vezes é difícil reproduzir - ou mesmo descobrir - o estado em que um conjunto de objetos estava quando um comportamento inesperado ocorreu, de modo a inspecionar seu comportamento.
Comment: O conceito de função em programação funcional é **diferente** do que é usado no resto da matemática. Linguagens funcionais em geral contém [funções parciais](http://pt.wikipedia.org/wiki/Fun%C3%A7%C3%A3o_parcial): para um dado `X`, ou `f(X)` é um valor do contra-domínio ou a função não retorna (devido a um loop infinito, exceção, etc), o que não acontece com funções da teoria dos conjuntos.
Comment: @darque Imagino que você se refere ao fato dessas linguagens não verificarem se o parâmetro pertence estritamente ao domínio da função, certo? Ex.: em `f(x) = 1/x` o domínio é `ℕ*`, não `ℕ`; mas se a função foi definida para receber um `int`, ela poderia a princípio receber um `0` (causando uma exceção).
Answer: A resposta do mgibsonbr é excelente e eu não poderia ter feito melhor. Vou apenas colocar algo um pouco diferente:

Funcional
OOP

Baseada em funções matemáticas
Baseada em formas e comportamentos de objetos através de campos e métodos

Lambda Calculus
Baseada em formas e comportamentos de objetos através de campos e métodos

Princípio da Composicionalidade
Herança e Abstração

Recursão
Polimorfismo

Transparência referencial
Encapsulamento

Pureza computacional (sem efeitos colaterais)
Efeitos colaterais

Lazy evaluation (execução atrasada)
Eager evaluation (execução imediata)

Imutabilidade
Dados são mutáveis

Linhagem baseada em "macros" (Lisp) ou "pattern matching" (ML)
Linhagem baseada em "classes" (C++) ou "protótipos" (Javascript)

Coisas definidas com muitos comportamentos
Muitas coisas e comportamentos definidos

Fórmulas/ações em primeiro lugar
Dados/substantivos em primeiro lugar

Procura a correção do código
Procura o reuso de código

Ordem de execução não importa (paralelismo)
Ordem de execução é importante

Dados vagamente acoplados a funções
Dados e funções fortemente acoplados

Concisão (opinião?)
Explicitude (opinião?)

Lisp, Scheme, ML, Scala, F#, Haskell, Erlang
Smalltalk, C++, Java, Python, Ruby, JS

Claro que aí estão alguns pontos que ajudam entender as diferenças entre elas. Não vou entrar em detalhes sobre cada ponto, daria um livro. O assunto é um pouco mais complexo que isso e há algumas imprecisões para simplificar a exposição. A tabela não deve ser interpretada como um comparativo definitivo das diferenças. Nem tão pouco que seja um "ou você escolhe um ou outro aspecto de cada lado da tabela".
Um dos pontos mais importantes é que linguagens puras em um paradigma costumam ser menos úteis na maioria das aplicações do mundo real e não alcançam grande sucesso. Por razões técnicas ou por cultura, linguagens mais próximas do paradigma imperativo são mais populares.
Na verdade em OOP, as únicas linguagens populares são essencialmente imperativas com características de orientação a objetos e implementam vários conceitos de programação funcional. E o principal conceito do paradigma, que é a herança, é frequentemente desencorajado. Algumas pessoas colocam outro conceito como principal, mas outros conceitos sequer são exclusivos da orientação a objeto.
Linguagens funcionais que não permitem nenhum tipo de mudança de estado, ou efeitos colaterais (mesmo que controlados) têm utilidade extremamente prejudicada para a maioria dos problemas.
Não se deixe enganar quando tentam vender pureza de paradigma. Isso é ótimo na academia. Nenhum paradigma é panaceia para qualquer coisa.
Ambos paradigmas fornecem abstrações, portanto ineficiências estarão presentes, cada um com sua característica. Para reduzir as ineficiências a pureza de paradigma deve ser deixada de lado; e quanto mais se aproximam do imperativo, mais próximos estão do processamento concreto.
Complementando de acordo com os comentários abaixo, os conceitos são ortogonais, e se não ficou claro, em linguagens do "mundo real" ou elas são funcionais ou são imperativas com características orientadas a objeto.

Orientação a objetos é tema tão complicado que ninguém tem uma definição clara do que seja. Para cada pessoa que você perguntar ela vai dar sua definição. Então se alguém disser que você está errado, provavelmente você está mesmo, mas não da forma que a pessoa está dizendo :) E o Alan Kay, criador do termo, admite mais recentemente que Smalltalk, sua linguagem, é na verdade orientada à mensagens e não objetos (veja outra polêmica).
E é triste que muitas pessoas acham que estão programando orientado a objeto e não estão, é como escrever um livro tendo tomando pau nas aulas de comunicação e expressão. Chegam ao ponto de se discutir qual linguagem é mais orientada a objeto que a outra, Java ou C# (entre outras). Ambas são bem pouco orientadas a objeto (aaahhhh, o marketing), e recomenda-se usar pouco as características desse paradigma. Isto ocorre porque cada um acha que determinada característica é mais importante que outra e nenhuma implementa todas as características do paradigma puramente. Ainda bem!
E linguagens funcionais estão longe da polêmica? Não, muitas pessoas consideram que Lisp, que foi a primeira linguagem funcional, não é puramente funcional e só as baseadas em ML é que são. E mais, há quem diga que Lisp é uma das linguagens mais orientadas a objeto que existem (o próprio criador do termo).
Alguns dizem que orientação sequer é paradigma, e este é só mais um motivo para mostrar que eles são ortogonais.
Hoje as linguagens novas e as que estão querendo estar atualizadas aderem cada vez mais ao paradigma funcional. Claro, não puramente, apenas de forma pragmática. Coloquei na tabela Scala e F# no funcional porque elas se vendem assim, mas são bem imperativas também, e implementam tudo de importante da orientação a objetos. Então até imperativo e funcional podem ser usados juntos, ainda que aí existe um paradigma que seja forte e o outro só auxiliar. C# é um exemplo de linguagem imperativa que está cada dia mais funcional, mas nunca deixará de ser predominantemente imperativa, e manterá sua orientação a objeto (mas que tem papel cada vez menos importante, desde o 2.0 isso vem caindo).
Na organização do código, em sua estrutura de dados que tem mais a ver com OOP, o imperativo procedural/modular e até o funcional se mostra mais útil que o orientado a objeto puro. Muitos não percebem isto e seguem fazendo sempre igual seguindo a receita de bolo que aprendeu. As pessoas usam OOP como uma "boa prática" (pesquise aqui o que acho disto). Boa prática é saber o que está fazendo e adotar o que é melhor para cada caso. Composição é o segredo para fazer boa manutenção e hoje quem não desgruda de OOP cria objetos que nada tem a ver com a ideia inicial do paradigma e é comum modularizarem tanto que beira o funcional, modular e até procedural, mas como está dentro de uma classe, acham que não.

Expus alguns fatos e dei algumas opiniões, até porque este é um assunto ainda não tão bem definido e entendido por todos.
Coloquei no GitHub para referência futura.
Comment: @Bacco Exato, a ideia da tabela é tornar os conceitos acessíveis para as pessoas. Ela não é uma tese. Ela pode ter até algumas incorreções e certamente não está completa. Se há informações que podem ajudar melhorá-la, estou ouvindo a todos. E eu falei sobre a simplificação feita, falei que os paradigmas se complementam. Mas vou clarificar ainda mais.
Comment: Em negrito: "linguagens populares são essencialmente imperativas com características de orientação a objetos e implementam vários conceitos de programação funcional.". Além disso, orientada a objetos e **usando** objetos não me parecem sinônimos, então creio que a tabela não tem problema nenhum como forma de distiguir as diferenças perceptíveis nos conceitos.
Comment: @dcastro Então leia todo o texto, você repetiu o que eu disse em outras palavras. E o que eu não disse, fiz referência a resposta que o mgibsonbr com a qual concordo 100%. Se eu fizesse uma comparação diferente, eu não estaria respondendo o que foi perguntado. Depois eu complemento para deixar mais explícito. Eu entendi o que você disse, não estou questionando, mas se for para ser absolutamente preciso, Scala ou F# não são 100% OOP, elas podem ser tanto quanto Java, C#, C++ ou outras linguagens OOP populares, e nenhuma é 100% OOP.
Comment: Eu acho que você não está dizendo que que 100% da linguagem OOP, afinal você mesmo disse que essas linguagens também são funcionais (e complemento que são também pelo menos imperativas, há outros paradigmas), mesmo que fosse 1% funcional (e é muito mais) a aritmética já não bateria. Se você diz que ela implementa 100% do conceitos OOP, então, bem, o Alan Kay discorda de você. De qualquer forma você pode argumentar de outra forma se eu não entendi algo. Só gostaria que enfatizar, que entendi o que você disse e concordo com tudo. Apenas estou dizendo que ser 100% preciso não ajuda o entendimento
Comment: Nao sei em relacao a F#, mas Scala e' 100% orientada a objectos, no sentido em que todos os valores sao objectos, e todos as operacoes sao chamadas a metodos de objectos. C# nao e' 100%, porque os metodos/operadores estaticos nao pertecem a nenhum objecto. O mesmo acontece em Java, onde existem tipos primitivos, que tambem nao sao objectos (tanto quanto sei). Eu so' quiz dizer que os dois conceitos nao sao opostos, nao sao preto e branco, por isso achei que uma tabela de comparacao nao faz muito sentido. Eu concordei com o resto do texto, mas acho que este ponto e' central e nao ficou claro.
Comment: @Maniero, eu, como a grande maioria dos programadores (imagino), tenho zero de experiência com linguagens funcionais. Então, quando você diz "*C# é um exemplo de linguagem imperativa que está cada dia mais funcional*", que aspectos da linguagem são esses que você diz que são funcionais?
Comment: Acho que essa tabela nao faz muito sentido - functional programming e OOP sao conceitos ortogonais, e podem coexistir. Nao faz sentido comparar um versus o outro. Scala, por exemplo, promove functional programming *e* e' 100% orientada a objectos - de tal modo, que substitui metodos/classes estaticos por companion objects. F# tambem e' orientado a objectos. Creio que a comparacao devia ser imperative programming vs functional programming.
Comment: Posto de outra forma: E' possivel escrever um programa usando apenas objectos, e escrito completamente num estilo funcional. A tabela de comparacao leva a crer que tenho que optar por um dos dois.
Comment: @PedroGaspar Fica complicado listar tudo isso em comentários.
Answer: A orientação a objetos tem por objetivo espelhar o mundo real. Por exemplo: um carro, podemos inserir ele no sistema, o que transformaria ele em objeto.
       Este objeto possui atributos (como cor, marca de fabricante, potência e etc) que o distingue de outros objetos.
É uma disciplina e tipo de programação que gosto e prefiro, mas fiz um resumo pois a matéria é muito extensa.
Espero que minha resposta tenha ajudado(a).


Does disable log error for MySQL increasing it's performance ? How disable it?

Question: Does disabling error logging for MySQL increase its performance? How can I disable it?
Here is my server's load:
Server load     0.63 (8 CPUs)
Memory Used     23.38% (957,600 of 4,096,000)
Swap Used       0% (0 of 1)

And here is a screenshot of the process manager
http://elnhrda.com/promgr.jpg
The contents of my.cnf:
[mysqld]
query_cache_size=64M
skip-name-resolve
#innodb_file_per_table=1
query_cache_limit=2M
read_buffer_size = 2M
read_rnd_buffer_size = 16M
sort_buffer_size = 8M
join_buffer_size = 8M
thread_cache_size = 8
thread_concurrency = 8
innodb_buffer_pool_size = 2G

I am looking for any suggestion that could increase my website's speed.
I have VPS, 4GB RAM, CENTOS 6, X86_64.
Please note: these statistics were calculated now with no queries executed, and the site had no visitors in the same time.
Answer: Error logging should not have significant impact on your MySQL performance, as there shouldn't be many of them. If you've got enough errors for logging to impact performance, the solution is to fix the errors, not ignore them.
You have relatively low CPU load and low memory usage. Do some benchmarking to find out what's making your site slow instead of selecting possible optimizations at random.
Comment: MySQL will attempt to load as much into cache as it can, in order to speed up queries. A MySQL database with zero queries **should** still be taking up a lot of RAM if it's properly configured.
Comment: That's one insertion every 30 seconds or so - hardly significant load if it's coded well. You're going to have to do some digging. Don't "think", **know**. Enabling the slow query log is easy and very useful.
Comment: Does 23.38% is low when no any visitors or any operations on the databse?
Comment: Well, Could you please suggest any ideas to improve MySQL performance?
Comment: Have you benchmarked it to confirm that MySQL performance *is* your problem? Have you done `EXPLAIN` queries to evaluate your queries? Do you have MySQL's slow query log enabled to find which ones to optimize?
Comment: i think i don't have any slow queries, the problem is when the site publish posts MySQL slowdown it because i have a lot of daily posts about 3K dialy
Comment: My website is using RSS aggregation feature with auto publish it via cronjob


Sorting rows and return the value as a simple array using EntityFieldQuery

Question: I have a drupal custom entity_type. I am trying to do to things, find the row that is the oldest and return with a simple array. I currently have the following:
<code>function oldestTicket(){
   $query = new EntityFieldQuery;
   $ticketTime = $query
  ->entityCondition('entity_type', 'as_ticket')
  ->propertyCondition('status','new')
  ->fieldOrderBy('updated', 'value', 'ASC')
  ->pager(1)
  ->execute();
  $entities = entity_load('as_ticket', array_keys($ticketTime['as_ticket']));
  return $entities;
}
</code>
This results with an error saying that updated is not a valid column field (it is in the db) and the return array is a complex multidimensional array. I would prefer something a little simple. In fact I would prefer that the returning result was just a string with updated timestamp value.
Answer: fieldOrderBy is for ordering by a Field API field.
You want propertyOrderBy('updated' 'ASC').
And the return structure can't be changed, it's always the same (a stub entity in technical terms). You use the id from that return structure to load your entity and get the data you want. I see you've already figured that one out, judging by your code.


Logic proof using contrapositive

Question: If n=ab is the product of two integers $a$ and $b$, then either $a\leq n^{(1/2)}$ or $b\leq n^{(1/2)}$. Use the proof by contrapositive method.
The new statement is: if $a>n^{(1/2)}$ or $b>n^{(1/2)}$, then $n\neq ab$ where $a$ and $b$ are positive integers.
I split this into three cases. One, where $a>n^{(1/2)}$, $b>n^{(1/2)}$. I had no problem with this case, multiplying the inequalities together gives $ab>n$, so $ab\neq n$.
Two and three are where I am having problems. In both cases, a statement like $a>n^{(1/2)}$, $b\ngtr n^{(1/2)}$ or $a\ngtr n^{(1/2)}$, $b>n^{(1/2)}$. To demonstrate the problem, which is almost identical for both, I will use the first only.
This statement is split up into two parts: $a>n^{(1/2)}$, $b<n^{(1/2)}$ or $a>n^{(1/2)}$, $b=n^{(1/2)}$. The second of these two is clearly simple to show, but the first not so much.
So, how should I go about concluding $ab\neq n$ from $a>n^{(1/2)}$, $b<n^{(1/2)}$.
Answer: Unfortunately your contrapositive statement is not correct. Your statement is in the form $p \rightarrow (q \lor r)$, whose contrapositive is $\neg(q\lor r) \rightarrow \neg p$. Using DeMorgan's Law: $\neg (q \lor r) \iff \neg q \land \neg r$, our original statement is equivalent to:
If $a > n^{1/2}$ and $b > n^{1/2},$ then $n \not = ab.$
This should be easier!
Comment: Yes! Thank you!
Comment: So we only use DeMorgan's law on the or statement as the equality is much easier to negate?
Comment: @Anon I'm not entirely sure what you mean. We use the contrapositive when it's easier to prove than the original statement. In this case, it **is** easier to prove since our premise allows us to assume more, i.e. that $a>n^{1/2}$ **and** $b>n^{1/2}$. When to consider the contrapositive is a whole other story, as it usually involves intuition acquired from solving many problems.

Logic proof using contrapositive


HTML rendered incorrectly for dynamic HTML content using master page

Question: I have a content page which has some dynamic HTML and some static HTML. This dynamic HTML is assigned to a hidden variable in page load.
Content page HTML
<asp:HiddenField id = "hid"  runat="server"></asp>

CS of content page
protected void Page_Load(object sender, EventArgs e)
{
  hid.Value = node1.InnerText;
}

This content page has master page. Below is its page directive
<%@ Page Title="" Language="C#" MasterPageFile="~/log.Master"
  AutoEventWireup="true" CodeBehind="Log.aspx.cs" Inherits="s.Log"
  ValidateRequest="false" %>`

Below is snippet of Content page
<%@ Page Title="" Language="C#" MasterPageFile="~/log.Master"
  AutoEventWireup="true"  CodeBehind="Log.aspx.cs" Inherits="s.Log"
  ValidateRequest="false" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
  <asp:HiddenField id = "hid"  runat="server"/>
</asp:Content>`

Now when content page loads, static HTML is loaded inside master page, but dynamic contents are rendered outside master page hence shows wrong rendering.
Comment: Sorry, your question makes little sense with the information you've provided. What are you doing with `hid`, where it is being displayed, please provide more information
Comment: @freefaller hid is hidden variable in Content page which is used to hold dynamic HTML created during Content page load. The HTML in hid variable is suppose to be rendered in Master form but it is shown outside the Master form. I have edited code snippet in above question.
Comment: Please learn to format your questions correctly (please [see here for more information](http://stackoverflow.com/editing-help))
Answer: The point of <asp:HiddenField> is that it is hidden - therefore any information contained within it should be definition never be rendered on the page.
If the contents of the field contain any HTML code that could cause it to break (such as HTML code that hasn't been encoded)... then it's possible that it will show something, but it is highly likely to be incorrect.  I think this is what you are seeing.
I'm not entirely sure exactly why you're using the HiddenField, or what you're trying to do with the contents of it, but I would suggest you change the following line...
hid.Value = node1.InnerText;

With...
hid.Value = Server.HtmlEncode(node1.InnerText);


Difference between Tensorflow convolution and numpy convolution

Question: import numpy as np
import tensorflow as tf

X_node    = tf.placeholder('float',[1,10,1])
filter_tf = tf.Variable( tf.truncated_normal([3,1,1],stddev=0.1) )

Xconv_tf_tensor = tf.nn.conv1d(X_node, filter_tf,1,'SAME')

X = np.random.normal(0,1,[1,10,1])
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    feed_dict = {X_node: X}
    filter_np = filter_tf.eval()
    Xconv_tf = sess.run(Xconv_tf_tensor,feed_dict)
    Xconv_np = np.convolve(X[0,:,0],filter_np[:,0,0],'SAME')

I am trying to see the results of convolutions from Tensorflow to check if it is behaving as I intended.
When I run the numpy convolution and compare it to the Tensorflow convolution, the answer is different.
The above code is how I ran the test.
I was hoping the Xconv_tf and Xconv_np would be equal.
My final goal is the run 2D convolution on a matrix with a 1 dimensional filter that runs 1d-convolution on each row with the same filter. In order to make this work (which will be basically a loop of 1d convolution over the rows) I need to figure out why my np.convolve and tf.conv1d give me different answers.
Comment: Completely different numbers. Some elements even differ in signs. The difference is definitely significant
Answer: The problem that you see is because TF does not really calculate the convolution. If you will take a look at the explanation of what convolution actually does (check for Visual explanations of convolution), you will see that the second function is flipped:

Express each function in terms of a dummy variable
Reflect one of the functions (this is the flip)
..... Some other stuff which I will not copy here.

TF does everything except of that flip. So all you need to do is to flip the kernel either in TF or in numpy. Flipping for 1d case is just kernel in a reverse order, for 2d you will need to flip both axis (rotate the kernel 2 times).
import tensorflow as tf
import numpy as np

I = [1, 0, 2, 3, 0, 1, 1]
K = [2, 1, 3]

i = tf.constant(I, dtype=tf.float32, name='i')
k = tf.constant(K, dtype=tf.float32, name='k')

data   = tf.reshape(i, [1, int(i.shape[0]), 1], name='data')
kernel = tf.reshape(k, [int(k.shape[0]), 1, 1], name='kernel')

res = tf.squeeze(tf.nn.conv1d(data, kernel, 1, 'VALID'))
with tf.Session() as sess:
    print sess.run(res)
    print np.convolve(I, K[::-1], 'VALID')

Comment: What happens in the backpropagation in TF? Does it flip the kernel there?
Answer: The order of filter is reversed. TensorFlow convolution is actually correlation. Numpy gets notation from math, TF gets notation from machine learning papers and somewhere the order got reversed.
This prints True
filter_np2=filter_np[::-1,0,0]
np.allclose(np.convolve(X[0,:,0],filter_np2,'SAME'),  Xconv_tf.flatten())    np.convolve(X[0,:,0],filter_np2,'SAME')