How to solve $x^3-x^2-8x+12$ with Cardano's formula?

Question: I'm trying to solve this and I have a mistake somewhere, but I don't know where. I calculated the rational roots with Rolle's theorem, so I know, that I should get $-3$ and $2$ somehow.
So, first of all. I tried to write $x^3-x^2-8x+12$ as the polynomial of $x-1$. I used Horner's method to divide the original polynomial with $x-1$.
So my result is $(x-1)^3-8(x-1)-4$. Which doesn't seem to be equal to the first polynomial.
Could you help me, please?
Comment: use wolfram alpha without hesitation or shame
Comment: I suggest that _if_ you want to write your polynomial as a polynomial of $x-1$, then insert $x+1$ in your original polynomial and expand. You get $(x+1)^3-(x+1)^2-8(x+1)+12=x^3+2x^2-7x+4$, and hence your original polynomial is $(x-1)^3+2(x-1)^2-7(x-1)+4$.
Comment: wtf is a Horner table and why do you guys confuse "dividing by $(x-1)$" with  "rewriting the polynomial in terms of $(x-1)$"
Comment: Maybe, you don't want to write your polynomial in terms of $(x-1)$, but in terms of $(x-1/3)$? And, @mercio, why so upset? :)
Answer: Instead of using the cubic formula, it's easier to derive the result from first principles. When the equation is specified with numerical values for the coefficients, this is easier because numerical values can be added up, multiplied etc.. But if the coefficients are symbols then the expressions are going to grow in size by some factor in each step. This is why the general solution for N linear equations with N unknowns is unwieldy for N larger than 3, yet you won't find it a big deal to solve ten equations with ten unknowns using Gaussian elimination, if the coefficients are numerical quantities.
To solve 3rd degree equation, you should get rid of the quadratic term by putting$ x = y + 1/3$:
$$x^3 - x^2 - 8 x + 12 = y^3  -\frac{25}{3}y + \frac{250}{27}$$
Then we invoke the identity:
$$(A+B)^3 = A^3+ 3 A^2B +3 AB^3 + B^3$$
which we can write as:
$$(A+B)^3 - 3 AB (A+B) - (A^3 + B^3)$$
So, if we can find and $A$ and a $B$ such that
$$A B = \frac{25}{9}$$
and
$$A^3 + B^3 = - \frac{250}{27}$$
Then $A + B$ will satisfy the equation.
If we put $A^3 = a$ and $B^3 = b$, then we have:
$$a b = \left(\frac{25}{9}\right)^3$$
and
$$a + b = - \frac{250}{27} $$
This then gives rise to a quadratic equation for e.g. $a$:
$$a^2 +  \frac{250}{27} a +  \left(\frac{25}{9}\right)^3 = 0$$
The solution for $a$ is:
$$a = -\frac{125}{27}$$
And $b$ has the same solution:
$$b = -\frac{125}{27}$$
$A$ and $B$ are the cube roots of $a$ and $b$, respectively, but such that the product of $A$ and $B$ equals $ \frac{25}{9}$, so if we choose one of the 3 possible a cube root for $A$, the cube root we need to choose for $B$ is fixed.
The solution are thus given by:
$$y_n = A_n + B_n$$
for $n = 0,1,2$
where:
$$A_n = -\frac{5}{3}\exp\left(\frac{2 \pi i n}{3}\right)$$
$$B_n = -\frac{5}{3}\exp\left(\frac{-2 \pi i n}{3}\right)$$
We can simplify this as:
$$y_n = -\frac{10}{3}\cos\left(\frac{2 \pi n}{3}\right)$$
Therefore:
$$x_n = \frac{1}{3} -\frac{10}{3}\cos\left(\frac{2 \pi n}{3}\right)$$
The solutions are thus $x = -3$ and $x = 2$, the latter having a multiplicity of 2.
Comment: Getting rid of the quadratic term  by putting $ x=y+1/3$ is the first step of Cardano's method for this Q. In general, for $x^3+a x^2+b x+c=0$, substitute $x=y-a/3$.
Answer: If you already know $-3$ and $2$ as roots, all that remains is to perform polynomial division for the corresponding linear factors:
$$
(x^3-x^2-8x+12):(x-2) = x^2+x-6
$$
and
$$
(x^2+x-6):(x+3)=x-2
$$
so that the third root is a repeat of the root $2$, giving it multiplicity $2$.


Is A Network Copy Timeout Likely To Show Up In Event Viewer Logs?

Question: I am trying to copy a 1.2Gb file between a Windows 7 workstation and a Windows Server 2003 system. That same server also hosts our enterprise's shares, most of them anyway.
The copy from the workstation to the server times out. If not in the event logs, where might this timeout event be recorded? Furthermore, what tools exist, other than doing something like running Wireshark, that would let me see the details of the failure?
Answer: No, this sort of thing won't be in the event logs; however, if the root cause was something (like a NIC losing connection or failing hard drive) that would be recorded, you could see if there's anything correlated.
If the problem is being caused by the network, and if you have managed switches (assuming this is all on the same LAN), then you might see some errors on the port(s). That might be similar to what you could see in Wireshark from one host or the other, if you know how to read its output.
How are you doing the copy? Explorer drag-n-drop, or copy, xcopy, robocopy? I prefer to use the last one, because it has decent error codes, retry options, and logging. Try it with robocopy and see what results you get.
Comment: Um, dude, FTP isn't a native protocol on Windows unless you've installed IIS. Drag-and-drop, and all the other commands that I listed, use CIFS (SMB) which is the native way of moving files between Windows servers.
Comment: I am just dragging from a hard disk to a share. You've given me a bunch of info, though. I need to look at the logs from our managed switch. We've got the equipment; I just need to know how to get to it.
Comment: Never move big files, that you care about, on the network, from within the GUI. Always use a command-line tool. Start with that - if you have a repeatable problem, then start worrying about the cause.
Comment: Good to know. I'm used to the command line on Linux, but less so on Windows. I'll try ftp next time.
Answer: Use Powershell for instead of a drag and drop. It's quite easy to log events with Powershell that your monitoring system can then pick up. And Copy-Item can use UNC paths.
<code>$LOG=new-object System.Diagnostics.EventLog("Application")
$LOG.Source="Lawson Export Copy Script"

$EVENT=[System.Diagnostics.EventLogEntryType]::Information

$VAL="Copied virtual machine exports from $SOURCE to $DEST successfully."
$LOG.WriteEntry($VAL,$EVENT,0)
</code>


Nginx reverse proxy with variable names for docker container returns wrong files

Question: I read a lot and tried a lot, but in the end, nothing worked. I hope, you can help me.
So here is my setup:
I have a Docker-compose file which contains a phpmyadmin container. My problem is not limited to phpmyadmin, this is just a good example.
Below the docker-file (important parts). As you can see, I want phpmyadmin to be available at https://www.example.com/phpmyadmin/. I think my setup would be much easier, if I used https://phpmyadmin.example.com/ (a subdomain instead of a sub path, but this is not what I want.)
The phpmyadmin container itself works perfectly well.
phpmyadmin:
  image: phpmyadmin/phpmyadmin:latest
  container_name: k3633970_phpmyadmin
  restart: always
  environment:
    MYSQL_ROOT_PASSWORD: xxx
    PMA_HOST: xxx
    PMA_ABSOLUTE_URI: https://www.example.com/phpmyadmin/
  networks:
   - frontproxy_default
   - backend

Then, I have a SECOND docker-compose file which starts an Nginx. Nothing fancy here:
nginx:
  image: nginx:alpine
  restart: unless-stopped
  volumes:
    - ./data/nginx:/etc/nginx/conf.d
  ports:
    - "80:80"
    - "443:443"
  networks:
    - frontproxy_default

Third, I have a Nginx config file for my vHost. I try to proxy all requests to /phpmyadmin/ to the phpmyadmin container and everything else "/" to another container running apache+php.
As you can see below, I do a proxy pass to the phpmyadmin container. When I use a docker container name, everything works proxy_pass http://k3633970_phpmyadmin/;(see the commented part).
But when I use variables like proxy_pass $target; it does not work any more. (I am describing the related problem as future reference for me and for others, so the post is a little bit longer).
What happens is, the start page of phpmyadmin is loaded which includes some JS/CSS files like "js/phpmyadmin.js" or "css/phpmyadmin.css". The web browser loades the files, but the Nginx-reverse proxy does not deliver the CSS/JS files but the start page again. The browser displays warnings that it cannot include the CSS/JS files because of the wrong mime type, because the start page is delivered as "text/html".
This lead me to the wrong trace first, that the mime types are false, when in fact the mime types are correct, but the wrong files are delivered.
Do you understand what I mean?
I try to explain it again:
I am loading
www.example.com/phpmyadmin --> the phpmyadmin html start page with mime type text/html is returned (which is correct).
This start page includes includes www.example.com/phpmyadmin/js/phpmyadmin.js and www.example.com/phpmyadmin/css/phpmyadmin.css but this is what is returned:
www.example.com/phpmyadmin/js/phpmyadmin.js --> the phpmyadmin html start page with mime type text/html is returned.
www.example.com/phpmyadmin/css/phpmyadmin.css --> the phpmyadmin html start page with mime type text/html is returned.
This is my nginx config file.
server {
    listen 443 ssl;
    server_name www.example.com;
    server_tokens off;
    ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

   location /phpmyadmin/ {
        resolver 127.0.0.11 valid=30s;
        set $target http://k3633970_phpmyadmin/; #Notice the trailing slash!
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass $target;
    }

# This works, without variables, but this is not what I want
#   location /phpmyadmin/ {
#        resolver 127.0.0.11 valid=30s;
#        set $upstreamx k3633970_phpmyadmin;
#        proxy_set_header Host $host;
#        proxy_set_header X-Real-IP $remote_addr;
#        proxy_pass http://k3633970_phpmyadmin/;
#         gzip  on;
#    }

    location / {
        resolver 127.0.0.11 valid=30s;
        set $upstream k3633970_vhost_1000303;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://$upstream:80;
    }
}

So the reason is, from the Nginx docs:

If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive.

Okay, understood. But how can I solve that now?
I tried every combination I can think of with set $target http://k3633970_phpmyadmin$uri; set $target http://k3633970_phpmyadmin$request_uri; set $target http://k3633970_phpmyadmin/$uri; etc.
I did not find a working combination.
Please help, I am stuck - thank you!
Last note: Why do I need variables in the proxy pass?
The whole reason is: I have like 10 docker-compose files with 10 wordpress stacks with 3 containers each (apache+php / mariabdb / phpmyadmin) and one nginx reverse proxy.
If I use the docker hostnames, all 10 docker-compose stacks must be up and running before I start nginx. This is not possible, sometimes one-two stacks are down for testing/maintenance.
The approach with variables allows to start nginx also if only 8 of 10 docker stacks are up and running.
Thank you!
Answer: Your nginx service must resolve the phpmyadmin container ip by using the "service name", not the "container name".
Also, you must keep the /phpmyadmin path in the URL when you proxy the request to the phpmyadmin container, and if you put a trailing slash, it removes that part, so you must NOT put a trailing slash. Or you can also rebuild the full URL with regex parsing.
So something like this should work:
location ~* ^/phpmyadmin/(.*)$ {
  set $query $1;
  set $phpmyadmin phpmyadmin; # Service name in docker-compose file
  proxy_pass http://$phpmyadmin/phpmyadmin/$query$is_args$args; # Rebuild the URL
}

Comment: Thank you for your reply, it works now, that is the solution:

   location ~* ^/phpmyadmin/(.*)$ {
        resolver 127.0.0.11 valid=30s;
        set $query $1;
        set $target http://k3633970_phpmyadmin/$query$is_args$args;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass $target;
    }
Comment: You wrote: "Also, you must keep the /phpmyadmin path in the URL when you proxy the request to the phpmyadmin container". I don't think so, the container has phpmyadmin installed at "/" and not at "/phpmyadmin".
Comment: You also wrote "Your nginx service must resolve the phpmyadmin container ip by using the "service name", not the "container name"." This is the service name. At least, that is the name, that `docker ps` shows in the `NAMES`-column.
Comment: You've set this envvar for the phpmyadmin service: PMA_ABSOLUTE_URI: https://www.example.com/phpmyadmin/
Comment: Just for clarification: The envvar is used for proper absolute URLs in phpmyadmin I guess and from the outside world  example.com/phpmyadmin is correct, but the phpmyadmin container self serves phpmyadmin from "/" (and not from /phpmyadmin). Thanks
Answer: With the help of @jonathan-rioux this is the working config now:
location ~* ^/phpmyadmin/(.*)$ {
    resolver 127.0.0.11 valid=30s;
    set $query $1;
    set $target http://k3633970_phpmyadmin/$query$is_args$args;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass $target;
}

Thank you!


Where to find information about tunings?

Question: When the Web was young I was on a mailing list called The Tunings List where you could discuss tunings and ask the experts. It closed and the members switched to Yahoo Groups. That too is coming to an end. So...
Answer: I had a couple of emails recently from ex-members of the mailing-list telling me where everyone had gone. The information below is taken from those.
.....................................................................................................................
Yahoo Groups! is shutting down permanently on December 15, 2020, meaning that even email functionality will be broken.
At this point, virtually all of the online microtonal/xenharmonic presence is at Facebook's "Xenharmonic Alliance," "Xenharmonic Alliance - Mathematical Theory", and "Microtonal Music and Tuning Theory" groups, all of which you can join.
The messages from this group were all archived. The archive is at: https://yahootuninggroupsultimatebackup.github.io/
You can also always get the Xenharmonic Wiki at: https://en.xen.wiki/w/Main_Page
There's also a group on MeWe https://mewe.com/group/5c9c1bc3d71e3023f90fe123
....and an email list run by Aaron Krister Johnson at email@example.com. You should be able to sign up here: http://lists.untwelve.org/listinfo.cgi/tuning-discuss-untwelve.org


If ruby encourages duck typing so much, why don't we have Hash.count instead of Hash.length?

Question: This is something that really confuses me, it seems like time and time again I run into methods in ruby native data types that do the same thing (essentially), and yet have different names.  If duck typing is so strongly encouraged by ruby and the ruby community, why aren't these methods named consistently across types?
Answer: You seem to imply that Hash does not have a length method and/or that other enumerables don't have a count method. That is not true.
count is a method defined in the Enumerable module and thus available on all enumerables. It differs from size and length in the following ways:

It (optionally) takes a block specifying which kind of elements to count.
It's available on all enumerables - not just those that keep track of their size - however it has a runtime in O(n) for those that don't (and always when given a block of course).

length and size (which are synonyms) are methods defined on all enumerable classes that keep track of their size (including Hash). They differ from count in that they always return the length in O(1) time and don't take a block.
In summary: You can call length or size on any object that keeps track of its size and you can call count on any enumerable. So duck typing is not hampered in any way.
Comment: Do you have a citation that `count` is `O(n)` in hashes when no block is supplied, or are you assuming it isn't optimized?
Comment: @Andrew: I don't have a citation, but I'm not just assuming either. I did `{}.method(:count)` in irb and it displayed as `Hash(Enumerable)#count`, which means that `Hash` does not override `count`. And `Enumerable#count` definitely is `O(n)`.
Comment: From [RDoc](http://www.ruby-doc.org/core/classes/Enumerable.html#M001483): "Returns the number of items in enum, where `size` is called if it responds to it ...". Duck typing FTW!
Comment: @Andrew: Ah, damn. Didn't think of that possibility. Anyway I've that bit in my answer now, thanks.


Show that if $\Gamma \models^v \varphi$ then $\Gamma^{\forall} \cup \{ \neg(\varphi^{\forall}) \}$ is not satisfiable

Question: Assuming $\varphi$ is a formula, $\Gamma$ is a set of formulas, $\varphi^{\forall} = \forall x_1 \forall x_2 \dots \forall x_n \varphi$ where $x_1,x_2, \dots, x_n$ are the free variables in $\varphi$ and $\Gamma^{\forall} = \{ \varphi^{\forall} | \varphi \in \Gamma \}$
Using the facts I know
$M \models \varphi $ if and only if $M \models \varphi^{\forall}$
$M \models \Gamma $ if and only if $M \models \Gamma^{\forall}$
I've tried the following:
If $M \models \Gamma$ then $M \models \varphi$ hence $M \models \varphi^{\forall}$ hence for all valuation $v$ $M,v \models \varphi^{\forall}$ then by $TT_{\neg}$ $M,v \not\models \neg(\varphi^{\forall})$ hence indeed for all valuation $v$ we have $M,v \not\models \Gamma^{\forall} \cup \{ \neg(\varphi^{\forall}) \}$
The second case doesn't seem to work out, if $M \not\models \Gamma$ then i know $M \not\models \Gamma^{\forall}$ but that still doesn't mean there is no valuation $v$ such that $M,v \models \Gamma^{\forall}$.
I will be happy for any help with the second case, or somehow proving it differently.
Comment: What second case ?
Comment: I need to show that for all $M,v$: $M,v \not\models \Gamma^{\forall} \cup \{ \neg (\varphi^{\forall}) \} $. I can show (as described) that if $M \models \Gamma$ then for all $v$ $M,v \not\models \Gamma^{\forall} \cup \{ \neg (\varphi^{\forall}) \} $. but for $M \not\models \Gamma$ i still can't find the proof that for all $v$: $M,v \not\models \Gamma^{\forall} \cup \{ \neg (\varphi^{\forall}) \} $. something doesn't add up.
Comment: But why the case $M \nvDash \Gamma$ ? You want to prove an "iff" ?
Comment: If $M \nvDash \Gamma$, by your known result above you have $M \nvDash \Gamma^{\forall}$ and thus, for sure: $M \nvDash \Gamma^{\forall} \cup \{ \lnot (\varphi^{\forall}) \}$
Comment: Yes, doesn't that means that there exists $v$ such that $M,v \not\models \Gamma^{\forall}$? i.e, it doesn't imply that for all $v$: $M,v \not\models \Gamma^{\forall}$ i.e, doesn't imply unsatisfiability?
Comment: **NO** (regarding also your answer below): to say that for some $v$ we have $M,v \nvDash \Gamma^{\forall}$ means that  (assuming for simplicity that the closure of $\Gamma$ regards only a single variable $x$) there is some $x$-variant $v'$ of $v$ such that $M,v' \nvDash \Gamma$.
Comment: Having said that, I repeat that it is not clear your approach... you are trying to conclude that "for all $v, M,v \nvDash \Gamma^{\forall}$, i.e. implying its unsatisfiability". But you are not asked to prove that $\Gamma^{\forall}$ is unsatisfiable.
Answer: $M \not\models \Gamma^{\forall}$ implies there exist $v_0$ such that $M,v_0 \not\models \Gamma^{\forall}$ but $\Gamma^{\forall}$ contains formulas without any free variables hence a different valuation doesn't change anything (no assignment is made). i.e, for all valuations $v(\psi) = v_0(\psi)$ for all $\psi \in \Gamma^{\forall}$ hence for all $v$ we have $M,v \not\models \Gamma^{\forall}$ finishing the proof.
Comment: No! You should check the definition of $M, v_0 \models \varphi$. Even if there is no free variable in $\varphi$, the valuation has an impact.
Comment: I used a theorem stating: If $v_1(x) = v_2(x)$ for all $x \in FV(\varphi)$ then $v_1(\varphi) = v_2(\varphi)$. so if $M,v_0 \not\models \varphi$ then by what i learned it means $v_0(\varphi) = F$ hence by the theorem $v(\varphi) = v_0(\varphi) = F$ for all $v$ since they agree on all the free variables (as there are none) which means $M,v \not\models \Gamma^{\forall}$. I hope this is correct.
Comment: you should check your theorem (stated as you wrote it, it is false)
Comment: What is a counter example?


how can i access a node variable inside of theme_preprocess_page function?

Question: I'm trying to access a node variable, the id of a taxonomy term but i have to do it at the page level in theme_prepocess_page function. i did it in preprocess node like this
$libStatus = $vars['field_feature_library_status']['und'][0]['tid'];

in preprocess_page i tried this:
$libStatus = $vars['node']['field_feature_library_status']['und'][0]['tid'];

but i get this error...  Cannot use object of type stdClass as array in….
can someone explain how i can access this node variable in theme_preprocess_page function?
Answer: Have you tried field_view_values() and field_get_items()
function mytheme_preprocess_page(&$variables) {
    if (!empty($variables['node'])) {
      $output = '';
      $node = $variables['node'];
      $items = field_get_items('node', $node, 'field name');
      foreach ($items as $item) {
        $field_output = field_view_value('node', $node, 'field name', $item);
        $output .= render($field_output);
      }
      // Set $variables with the value you need.
    }
  }

Explained in here how to access node variables in region preprocess function?
I think you should also be able to use entity_metadata_wrapper as follow
$node = $variables['node'];
$wrapper = entity_metadata_wrapper('node',$node);
$libStatus = $wrapper->field_feature_library_status->value();

Comment: $field_output = field_view_value('node', $node, 'field name', $item);
Comment: but i see it if i do a var_dump($items);
Comment: correction, no error. sorry, had a typo.
Answer: As reported in node.tpl.php, the field field_feature_library_status is available as raw value as $field_feature_library_status,  in the preprocess/process functions.

Field variables: for each field instance attached to the node a corresponding variable is defined; for example, $node->body becomes $body. When needing to access a field's raw values, developers/themers are strongly encouraged to use these variables. Otherwise they will have to explicitly specify the desired field language; for example, $node->body['en'], thus overriding any language negotiation rule that was previously applied.
Comment: ??? i don't understand
Comment: $field_feature_library_status, just says undefined variable when used in preprocess node


What is a general solution to a differential equation?

Question: I understand how to find the general solution of a differential equation, for complex roots, simple roots, nonhomogeneous equations etc... but I still don't really know what the general solution is?
As in, what is the purpose of it? What is it used for? thanks...
Answer:
To say that you have found the general homogeneous solution means that this function solves the homogeneous equation for every choice of the constant $C_1$ and every solution of the
homogeneous equation is of this form for some choice of $C_1$.
You can actually have more than one particular solution to a DEQ. The difference between any two particular solutions is always a homogeneous solution.

Example:
$$y' + \left(\frac{a}{t}\right)y = t^3$$
The homogeneous solution is:
$$\displaystyle y_H = c_1 t^{-a}$$
Here are two particular solutions:
$$\displaystyle y_{1P} = \frac{t^4}{4+ a}$$
$$y_{2P} = \displaystyle \frac{t^4}{4+ a} + c_1 t^{-a}$$
What is the difference between these two particular solutions?

To say you have a unique solution  means that this is the ONLY function that satisfies both the differential equation and the initial condition. The graph of this function is the only solution curve that passes through the initial point.

For this, we obviously need to be given an initial condition.
Comment: really well-answered!
Comment: indeed it was! thanks Amzoti


twitter block module

Question: I am trying to embed a timeline of tweets to my website's sidebar. I am using Drupal 8. The module "Twitter Block" requires a widget ID but Twitter has stopped providing widget ids and only generates html code but I don't know at which file should I embed this code to. Is there any other way? Any suggestions?
Thank you.
Comment: Is there a big number in the HTML code? Big chance that is your ID.
Comment: It will work, just set your twitter id in the configuration
Comment: It works! A million thanks !It didn't require any Widget Id just the Twitter username. Thanks again!
Answer: Sorry for this late reply... but here is the module you are looking for:
Twitter API Block
As explained in its README file, you need to download it and the required library with composer, as follow:
<code>composer require drupal/twitter_api_block drupal/j7mbo/twitter-api-php
</code>
Then go create a new app in Twitter and finally, place the block in your Drupal site.
Simple :) Enjoy!

twitter block module


Subquery not working the way i want it to

Question: This is my first ever post here on stackoverflow.
I would like to see what the min, average and max salary is per education level per marital_status.
I've tried this code but it only shows the same value for min, average and max for all the different education levels:
Select distinct education, (select min(convert(int, income))
                            from [dbo].[marketing_campaign] where marital_status = 'Married' and year_birth > 1980 and income <> 0) Min_Married,
                            (select avg(convert(int, income))
                            from [dbo].[marketing_campaign] where marital_status = 'Married' and year_birth > 1980 and income <> 0) Avg_Married,
                            (select max(convert(int, income))
                            from [dbo].[marketing_campaign] where marital_status = 'Married' and year_birth > 1980 and income <> 0) Max_Married,
                            (select min(convert(int, income))
                            from [dbo].[marketing_campaign] where marital_status = 'Single' and year_birth > 1980 and income <> 0) Min_Single,
                            (select avg(convert(int, income))
                            from [dbo].[marketing_campaign] where marital_status = 'Single' and year_birth > 1980 and income <> 0) Avg_Single,
                            (select max(convert(int, income))
                            from [dbo].[marketing_campaign] where marital_status = 'Single' and year_birth > 1980 and income <> 0) Max_Single,
                            (select min(convert(int, income))
                            from [dbo].[marketing_campaign] where marital_status = 'together' and year_birth > 1980 and income <> 0) Min_together,
                            (select avg(convert(int, income))
                            from [dbo].[marketing_campaign] where marital_status = 'together' and year_birth > 1980 and income <> 0) Avg_together,
                            (select max(convert(int, income))
                            from [dbo].[marketing_campaign] where marital_status = 'together' and year_birth > 1980 and income <> 0) Max_together
from [dbo].[marketing_campaign]
where  education in ('master', 'Graduation', 'phd', 'basic')
group by education
order by education desc

Thanks in advance!
Answer: There is no correlation with education in your sub-queries, neither is there any need for repeatedly using a sub-query when I suspect what you need is the following:
with i as (
    select education,
        Iif(marital_status = 'Married' , Convert(int, income),0) Income_Married,
        Iif(marital_status = 'Single'  , Convert(int, income),0) Income_Single,
        Iif(marital_status = 'together', Convert(int, income),0) Income_Together,
    from dbo.marketing_campaign
    where education in ('master', 'Graduation', 'phd', 'basic')
    and year_birth > 1980 and income != 0
)
select education,
    Min(Income_Married) Min_Married,
    Avg(Income_Married) Avg_Married,
    Max(Income_Married) Max_Married,
    Min(Income_Single) Min_Single,
    Avg(Income_Single) Avg_Single,
    Max(Income_Single) Max_Single,
    Min(Income_Together) Min_Together,
    Avg(Income_Together) Avg_Together,
    Max(Income_Together) Max_Together
from i
group by education
order by education desc;

Comment: Thank you so much for the answer.
I realize now that i wasn't clear in my explanation/question.
The reason why i did a subquery is because i want to check for all the different marital status min, avg and max as columns. I.e. i i want 9 subqueries, min, avg and max for 'single', 'married' and 'together'.
Comment: It's not clear to me what you are expecting- the above gives the same columns as your example query. If the above is not what you require then it would be helpful to supply some example data and show what your desired results are.
Comment: I've updated the post.
With the code i've written the output gives me the same values for all different education levels. For example:
education Min_Married
PhD 7500
Master 7500
Graduation 7500
Basic 7500
Comment: @MartinNordinSundberg Based on your edited question I have revised above - there are a few ways to conditionally `case` the agregations, you can also use the essentially the same but more terse *inline if*, and separating the conditional case logic from the aggregations makes for a slightly cleaner (imho) approach.
Comment: Thank you so much Stu, the CTE version did the work!
Answer: You can simply do this as follow. I tried to make the same environment as you describe in my DB, so hope this will help you.
SELECT   DISTINCT C.education,
         MIN(income) OVER(PARTITION BY education) AS MIN_Married,
         AVG(income) OVER(PARTITION BY education) AS AVG_Married,
         MAX(income) OVER(PARTITION BY education) AS MAX_Married
FROM     [dbo].[marketing_campaign] C
WHERE    education IN ('master', 'Graduation', 'phd', 'basic')
         AND marital_status = 'Married'
         AND year_birth > 1980
ORDER BY education DESC

Comment: Thank you so much for the answer. I realize now that i wasn't clear in my explanation/question. The reason why i did a subquery is because i want to check for all the different marital status min, avg and max as columns. I.e. i i want 9 subqueries, min, avg and max for 'single', 'married' and 'together'.
Answer: Use conditional aggregation:
SELECT education,
       MIN(CASE WHEN marital_status = 'Married' AND year_birth > 1980 AND income <> 0) THEN CONVERT(INT, income) END) Min_Married,
       AVG(CASE WHEN marital_status = 'Married' AND year_birth > 1980 AND income <> 0) THEN CONVERT(INT, income) END) Avg_Married,
       MAX(CASE WHEN marital_status = 'Married' AND year_birth > 1980 AND income <> 0) THEN CONVERT(INT, income) END)  Max_Married,
       MIN(CASE WHEN marital_status = 'Single' AND year_birth > 1980 AND income <> 0) THEN CONVERT(INT, income) END) Min_Single,
       AVG(CASE WHEN marital_status = 'Single' AND year_birth > 1980 AND income <> 0) THEN CONVERT(INT, income) END) Avg_Single,
       MAX(CASE WHEN marital_status = 'Single' AND year_birth > 1980 AND income <> 0) THEN CONVERT(INT, income) END) Max_Single,
       MIN(CASE WHEN marital_status = 'together' AND year_birth > 1980 AND income <> 0) THEN CONVERT(INT, income) END) Min_together,
       AVG(CASE WHEN marital_status = 'together' AND year_birth > 1980 AND income <> 0) THEN CONVERT(INT, income) END) Avg_together,
       MAX(CASE WHEN marital_status = 'together' AND year_birth > 1980 AND income <> 0) THEN CONVERT(INT, income) END) Max_together
FROM [dbo].[marketing_campaign]
WHERE education IN ('master', 'Graduation', 'phd', 'basic')
GROUP BY education
ORDER BY education DESC;

Or, move the common conditions in the WHERE clause:
SELECT education,
       MIN(CASE WHEN marital_status = 'Married' THEN CONVERT(INT, income) END) Min_Married,
       AVG(CASE WHEN marital_status = 'Married' THEN CONVERT(INT, income) END) Avg_Married,
       MAX(CASE WHEN marital_status = 'Married' THEN CONVERT(INT, income) END)  Max_Married,
       MIN(CASE WHEN marital_status = 'Single' THEN CONVERT(INT, income) END) Min_Single,
       AVG(CASE WHEN marital_status = 'Single' THEN CONVERT(INT, income) END) Avg_Single,
       MAX(CASE WHEN marital_status = 'Single' THEN CONVERT(INT, income) END) Max_Single,
       MIN(CASE WHEN marital_status = 'together' THEN CONVERT(INT, income) END) Min_together,
       AVG(CASE WHEN marital_status = 'together' THEN CONVERT(INT, income) END) Avg_together,
       MAX(CASE WHEN marital_status = 'together' THEN CONVERT(INT, income) END) Max_together
FROM [dbo].[marketing_campaign]
WHERE education IN ('master', 'Graduation', 'phd', 'basic')
  AND year_birth > 1980 AND income <> 0
GROUP BY education
ORDER BY education DESC;

Comment: @MartinNordinSundberg and it was posted before the answer that you accepted was edited.


Vue 2: Pegar valor do input sem usar v-model

Question: Já estou detectando quando é pressionado o enter no input, como posso fazer para pegar o atual value desse input também? Não pode ser com v-model, pois preciso deixar um valor default, como mostra o exemplo abaixo:
HTML

     @foreach($listas as $lista)
          <input type="text" value="{{$lista->descricao}}" v-on:keyup.13="editName">
     @endforeach

JS
var listasPage = new Vue({
    el: '#listas-page',

    methods: {
        editName(event) {
            console.log(event);
        }
    }
});

Comment: Porque não podes usar v-model? Dá perfeitamente para colocares um valor default: https://jsfiddle.net/50wL7mdz/92446/
Comment: É que estou trazendo vários inputs com seus respectivos valores do banco. E estou fazendo isso com um foreach em php.
Answer: Não recomendo de forma alguma essa mesclagem de php puro com vue, existem soluções melhores, mas é possível pegar o value pelo event.target.value, exemplo...

new Vue({
  el: '#app',
  data : {
   value : ''
  },
  methods : {
    editName(event) {
      this.value = event.target.value;
    }
  }
})

  <input value="default" v-on:keyup.13="editName">
  {{value}}


Struggling with how test a method with several steps

Question: I have a MVC web site with a user registration function and I have one layer that I can't wrap my head around how to test. Basically the method does this...
1) Checks the database to see if the user is already registered
2) Maps a view model into an entity framework model
3) Saves the user to the database
4) Send the user a confirmation email
5) Performs a web service post to a 3rd party API
6) Updates the user (created in step #3) with a value returned from the 3rd party
I am struggling with how or should I test this. I have abstracted all the steps into separate services and I have tests for those so really tests for this method would be testing the flow. Is that valid?
In a TDD world, and I'm trying to think that way, should I have a method like this? Or is there a design issue I am not seeing?
I can write the tests and I understand how to mock but when I write the test for step #6 I have mock setups that return data for steps #1, #2 and #5 to ensure the code gets that far and to ensure the object saved in step #6 has the correct state. My test setups get long quickly.
If this is how it's supposed to be then great! But I feel like I am missing my light bulb moment.
My Lightbulb Moment
I liked Keith Payne's answer and looking at his interfaces made me see things from a new perspective. I also watched a TDD Play by Play course (http://www.pluralsight.com/courses/play-by-play-wilson-tdd) and that really helped me understand the process. I was thinking about the process from the inside out and not from the outside in.
This is definitely a new way of thinking about software development.
Answer: Difficult test setups are a code-smell and I think you see this already. The answer is more cowbell (abstraction).
This is a common fault in controller methods acting as both controller of the UI and orchestrating the business process. Steps 5 & 6 probably belong together, steps 1, 3 & 4 similarly should be abstracted away to another method. Really the only thing a controller method should do is to receive data from the view, hand it off to an application- or business- layer service, and compile the results into a new view to display back to the user (mapping).
EDIT:
The AccountManager class that you mention in the comment is a good step towards good abstraction. It lives in the same namespace as the rest of the MVC code, which unfortunately makes it easier to crisscross the dependencies. For instance, passing a view model to the AccountManager is a dependency in the "wrong" direction.
Imagine this idealized architecture for a web application:

Application Layer

UI (JavaScript/HTML/CSS)
Model-View-Controller (Razor/ViewModel/Navigation)
Application Services (Orchestration/Application Logic)

Business Layer

Domain Services (Domain [EF] Models/Unit Of Work/Transactions)
WCF/Third Party API's (Adapters/Client Proxies/Messages)

Data Layer

Database

In this architecture, each item references the item below it.

Inferring some things about your code, AccountManager is at highest an application service (in the referencing hierarchy). I do not think that it is logically part of the MVC or UI components. Now, if those architecture items were in different dlls, the IDE would not allow you to pass a view model into a method of the AccountManager. It would cause a circular dependency.
Outside of the architectural concerns, it is also apparent that the view model is not appropriate to pass along because it will invariably include data that support view rendering that is useless to the AccountManager. It also means that AccountManager must have knowledge of the meaning of properties in the view model. Both the view model class and AccountManager are now dependent on each other. This introduces unnecessary brittleness and fragility to the code.
A better option is to pass along simple parameters, or if you prefer, to package them into a new Data-Transfer-Object (DTO) which would be defined by contract in the same place as the AccountManager.
Some example interfaces:
namespace MyApp.Application.Services
{
    // This component lives in the Application Service layer and is responsible for orchestrating calls into the
    // business layer services and anything else that is specific to the application but not the overall business domain.

    // For instance, sending of a confirmation email is probably a requirement in some application process flows, but not
    // necessarily applicable to every instance of adding a user to the system from every source. Perhaps there is an admin back-end
    // application which may or may not send the email when an administrator registers a new user. So that back-end
    // application would have a different orchestration component that included a parameter to indicate whether to
    // send the email, or to send it to more than one recipient, etc.

    interface IAccountManager
    {
        bool RegisterNewUser(string username, string password, string confirmationEmailAddress, ...);
    }
}

namespace MyApp.Domain.Services
{
    // This is the business-layer component for registering a new user. It will orchestrate the
    // mapping to EF models, calling into the database, and calls out to the third-party API.

    // This is the public-facing interface. Implementation of this interface will make calls
    // to a INewUserRegistrator and IExternalNewUserRegistrator components.

    public interface IUserRegistrationService
    {
        NewUserRegistrationResult RegisterNewUser(string username, string password, ...);
    }

    public class NewUserRegistrationResult
    {
        public bool IsUserRegistered { get; set; }
        public int? NewUserId { get; set; }

        // Add additional properties for data that is available after
        // the user is registered. This includes all available relevant information
        // which serves a distinctly different purpose than that of the data returned
        // from the adapter (see below).
    }

    internal interface INewUserRegistrator
    {
        // The implementation of this interface will add the user to the database (or DbContext)
        // Alternatively, this could be a repository
        User RegisterNewUser(User newUser) ;
    }

    internal interface IExternalNewUserRegistrator
    {
        // Call the adapter for the API and update the user registration (steps 5 & 6)
        // Replace the return type with a class if more detailed information is required

        bool UpdateUserRegistrationFromExternalSystem(User newUser);
    }

    // Note: This is an adapter, the purpose of which is to isolate details of the third-party API
    // from yor application. This means that what comes out from the adapter is determined not by what
    // is provided by the third party API but rather what is needed by the consumer. Oftentimes these
    // are similar.

    // An example of a difference can be some mundance detail. For instance, say that the API
    // returns -1 for some non-nullable int value when the intent is to indicate lack of a match.
    // The adapter would protect the application from that detail by using some logic to interpret
    // the -1 value and set a bool to indicate that no match was found, and to use int?
    // with a null value instead of propagating the magic number (-1) throughout your application.

    internal interface IThirdPartyUserRegistrationAdapter
    {
        // Call the API and interpret the response from the API.
        // Also perform any logging, exception handling, etc.
        AdapterResult RegisterUser(...);
    }

    internal class AdapterResult
    {
        public bool IsSuccessful { get; set; }

        // Additional properties for the response data that is needed by your application only.
        // Do not include data provided by the API response that is not used.
    }
}

Something to keep in mind is that this kind of design-all-at-once is the opposite of TDD. In TDD, the need for these abstractions become apparent as you test and write code from the outside-in. What I've done here is to skip all of that and jump directly to designing the innerworks based on what I picture in my head. In almost all cases this leads to over-design and over-abstraction, which TDD naturally prevents.
Comment: I added the interfaces and a slightly more extensive explanation
Comment: My AccountController checks the modelstate and if all is good passes the view model to the my AccountManager and that guy orchestrates everything I have a writer's block when it comes to names. Would you please edit your response and include some interface signatures so I could get a better idea?
Answer: In my opinion you are thinking things right. Although you encapsulate all different tasks on separated modules you'll need a piece of code to coordinate all that stuff.
These tests on charge of evaluating complex flows are really a nightmare since you end up having a bunch of mocks and setups. I don't think you have many ways to escape.
Since testing behavior is very fragil provided it heavily relies on internal implementation, my advice is not to spend too much time writing tests for this method.
When I face this situation I try to add tests for the more relevant scenarios and omit the obvious to reduce test suit complexity. Avoid having 100 tests for this since you will likely need to change the flow at some point and that will cause 100 complex tests to be changed.
It's not ideal but I believe is a trade off decision.
Comment: The relevant scenarios are easy to test :)
Answer:
In a TDD world, and I'm trying to think that way, should I have a method like this? Or is there a design issue I am not seeing?

Your method is fine and TDD has little to say here. It's more about design. After writing single responsibility-oriented components (as you seem to have done) there comes a point where you have to use them together to implement an use case. Doing that you'll often end up with facade classes just like yours (but they should be in minority).
As for testing, there is no easy way around (if at all). Your setups might be longer than usual. It often helps to distinguish which dependencies will serve as stubs (providing data for tested method - setup) and which as mocks (which you'll assert against). As you noticed, steps 1, 2, 5 will be used for setups only.
To make your work easier and tests more readable, consider wrapping certain setup configurations in methods:
[Test] public void UserIsSavedToDatabase()
{
    UserIsNotRegistered();
    ViewModelIsMappedToEntity();

    ...
}

Comment: You say they should be in a minority but if I have a logical operation (such as I described) and an application tends to have a lot of logical operations I would have a lot of these type of methods. What is the alternative?
Comment: @oliwa: applications tend to have lot of business cases, this is where you'll need such facades. If your user can run entire process in single click, then there's no alternative. You can add layers, group things, extract to other components but in the end you'll always need a place to wire things up together. If you have too many of such classes then perhaps you are not abstracting enough and components that should not be facade classes (i.e. can be easily abstracted) are parading as such.


How can I measure precisely the resources consumed by each Web site on my server?

Question: We are having performance issues on our server which may or may not be the inevitable result of high traffic to our sites.  We would like to optimize each site for performance so that we can be sure we're getting the most "bang for our buck" before purchasing additional hardware.
I was wondering if anyone knew of some creative ways to measure the resources (memory, bandwidth, CPU time, etc) consumed by each Web site.  This could allow us to spot the biggest "offenders" and start working on those first.
We are running Red Hat Enterprise Linux Server release 5.6 (Tikanga)
Comment: are these sites running CGIs?  php?  serving static files?
Comment: PHP/Apache and the usual static files.  Most of these sites are running either Wordpress or Magento.
Answer: I would start with mod_log_config. Define one or more LogFormat/CustomLog setups in httpd.conf with just the stats you're interested in and any metadata about the requests you care to filter by and then you can quickly generate comparative stats from those log files. For example:
LogFormat "%t %v %B %D %h %r" statlog
CustomLog "|/usr/bin/cronolog logs/stat.log.%Y-%m-%d" statlog

%t is the timestamp, %v is the virtual server hostname, %B is bytes sent (excluding headers), %D is microseconds elapsed, %h is client IP address, and %r is the first line of the actual HTTP request sent by the client. So you can leave in or out any of that other information, depending on what you're looking for, or have one log for each stat, or whatever you want. (I like using cronolog to rotate logs on a daily basis. Tack on -%H if you want hourly rotation.)
Then you can run the appropriate columns through whatever number-crunching you want to get totals, averages, identify particularly slow or abusive pages, or what-have-you.
Additionally, if you have mod_logio enabled, you can get exact byte counts (after encryption/compression/everything) for incoming and outgoing bandwidth for each request using %I and %O respectively in your LogFormat string.
Answer: Running suexec would make it easier to see what users are using more resources, as their php processes would appear to be running as their users instead of as the system user running apache, such as www-data or nobody.
In my experience, magento is a HUGE resource hog, especially if you are just running it as it comes out of the box.  We used to perhaps put a couple moderately busy sites on a single box.  With magento we find ourselves putting one site on multiple boxes.
You certainly don't want to run magento without trying to make some adjustments for performance.  I'd strongly encourage you to setup memcached as a cache for magento (instructions here). and store your sessions in memcache, and turn on block caching. (This will take the html which is generated by individual blocks and store it in memcache, so that the next time the same block is accessed, the phtml files don't have to be run again).
You may want to run an opcode accellerator like APC for caching PHP opcodes.
Update:
You definitely want to make sure mysql is tuned, especially that you have enough in the innodb buffer pool. (magento's tables are all innodb).  I think a good place for reading about mysql performance tuning is the the mysql performance tuning blog.  I'd start with tuning the innodb_buffer_pool_size.  Note that they are typically talking about running mysql on a server that does nothing but run mysql, so when they say "dedicate 12 gigs on a 16 gig box to innodb_buffer_pool" you should adjust that way down, as  your box is doing more than just mysql.
Comment: Thanks stew - we've actually done all of those things - minus the "mysql tuning."  Would like to know more about that.  Do you know anyone who specializes in this?  (And would like to also share some of their knowledge with me? :)
Comment: updated with more clues about mysql
Comment: Thanks - actually we do have a dedicated MySQL server as well.
Comment: The tuning-primer.sh script is a great starting point for MySQL tuning. http://www.day32.com/MySQL/tuning-primer.sh
Answer: You're starting from the wrong end.
Traditionally (and also sanely!), you START by identifying an actual problem; then you progress to diagnosing its causes, and only THEN do you add hardware or change software configurations.
If there is an actual, observable problem occurring right now, that is the place to start: try to identify exactly under which circumstances it occurs, whether it is precisely reproducible, and guesstimate what the impact is on the business.
Next up, start collecting performance data from your application stack; this may involve but is probably not limited to : OS resource utilization, web server metrics, PHP caching, databases, disk I/O and latency.
I'm sorry if the answer seems vague or generic - so was the question.
Comment: I appreciate your opinion.  But I think that wanting to make sure I am getting the maximum performance from my current configuration is valid on its own - that's just my opinion.  I know it must be possible, for example, to determine the total amount of bandwidth consumed by a single Web site in a 24 hour period - I am just not sure exactly how to go about this.  Surely there are tools out there that can help.
Answer: Use a Metric Collection System like Cacti or Munin.
Answer: I always run collectl on all servers.  It samples tons of metrics every 10 seconds and slab/process data every minute and writes it all to a file you can playback OR plot with colplot (part of collectl-utils).  You can also run it in real-time at any sampling interval of your choice.
Based on what you see over several hours or even days, you can then begin to take the approach  very clearly stated by apaptr, of first figuring out if there even is a problem and then taking steps to correct it.  Having collectl data at each step in the process makes it very easy to tell if things have improved or gotten worse.
-mark


org.springframework.beans.factory.BeanCreationException: Error creating bean

Question: I am trying to configure Spring Framework 2.5.6.SEC01 + JPA using Hibernate, but I am getting an exception while spring tries to create a Bean ,  my xml and the error stack trace below:
Note :
in my project I need use Spring  ver 2.5.6 not Spring ver 3.x.x
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:component-scan base-package="restodeskapp.dao , restodeskapp.service.impl"/>
<context:annotation-config/>
<tx:annotation-driven/>
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driver}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
    p:dataSource-ref="dataSource"
    p:configLocation="classpath:hibernate.cfg.xml"/>

<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
</beans>

hibernate.cfg
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialec</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/resto</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping class="restodeskapp.model.Makanan"/>

</session-factory>
</hibernate-configuration>

example.java
@Service("makananService")
@Transactional(readOnly=true)

public class MakananServiceImpl implements MakananService{
@Autowired private MakananDao personDao;
@Transactional(readOnly=false)

public void save(Makanan person) {
personDao.save(person);
}
@Transactional(readOnly=false)

public void delete(Makanan person) {
personDao.delete(person);
}
public Long count() {
return personDao.count();
}
public Makanan getMakan(Long id) {
return personDao.getById(id);
}
public List<Makanan> getMakan() {
return personDao.getAll();
}
public List<Makanan> getMakan(int start, int num) {
return personDao.getAll(start, num);
}

}
error log
debug:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.interceptor.TransactionInterceptor#0': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Could not parse configuration: file:/C:/Users/Hallaz/Documents/NetBeansProjects/RestoDeskApp/build/classes/hibernate.cfg.xml
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1245)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at restodeskapp.MainSpring.main(MainSpring.java:19)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Could not parse configuration: file:/C:/Users/Hallaz/Documents/NetBeansProjects/RestoDeskApp/build/classes/hibernate.cfg.xml
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1245)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:269)
    ... 18 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Could not parse configuration: file:/C:/Users/Hallaz/Documents/NetBeansProjects/RestoDeskApp/build/classes/hibernate.cfg.xml
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:269)
    ... 31 more
Caused by: org.hibernate.HibernateException: Could not parse configuration: file:/C:/Users/Hallaz/Documents/NetBeansProjects/RestoDeskApp/build/classes/hibernate.cfg.xml
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1494)
    at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:990)
    at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:69)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1443)
    at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:978)
    at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:69)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:601)
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335)
    ... 41 more
Caused by: org.dom4j.DocumentException: Error on line 1 of document  : Content is not allowed in prolog. Nested exception: Content is not allowed in prolog.
    at org.dom4j.io.SAXReader.read(SAXReader.java:482)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1484)
    ... 50 more
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

Please help me...
Solution
XML file content is probably prefixed with a BOM as @Sotirios Delimanolis answer
CTRL + A delete and write manual again :)
thanks so much :)
Comment: Do you have `` ending `hibernate.cfg.xml` ?
Answer: Your XML file content is probably prefixed with a BOM.
The sax parser expects a normal < to begin an XML document but finds the Byte Order Mark instead.
You have to remove it. An example for doing that can be found here.
Comment: @Hallaz plz tell the solution
Answer: I changed the Spring jdbc jar version from 3.2.0.RELEASE
To
3.0.4.RELEASE
and it has started working


Erro de definição do método ExecuteSQL

Question: Ao criar o método execute gera erro neste ponto  rs = stm.executeQuery(sql) o que posso fazer
public void excutaSQL(String sql){
        try {
            stm=(Statement) conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);

            rs = stm.executeQuery(sql);// o erro está neste linha
        } catch (SQLException ex) {
            Logger.getLogger(Conection.class.getName()).log(Level.SEVERE, null, ex);
        }

     }

error: cannot find symbol
              rs = stm.executeQuery(sql);
    symbol:   method executeQuery(String)
    location: variable stm of type Statement
  1 error

import java.beans.Statement;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

Comment: Onde esta o valor da tua variavel `SQL`
Comment: Qual é o error?
Comment: Provavelmente você está importando a biblioteca `Statement` da `java.beans` ao invés da `java.sql`. Coloca o `import` pra conferirmos
Answer: Você está importando a classe Statement errada. Altere o import da classe Statement para o seguinte:
import java.sql.Statement;

Ou apenas remova a linha abaixo, afinal você já está fazendo o import para todas as classes (com import java.sql.*):
import java.beans.Statement;

Documentação da classe java.sql.Statement

Erro de definição do método ExecuteSQL


Find differential relation by eliminating $\phi$

Question: A meridian $z$ vs $r$  in cylindrical coordinates of a surface of revolution makes angle $\psi$ with an arc $s$ drawn on it and tangent angle $\phi$ to axis of symmetry.
Constant $c_1$ and two relations
$$ \cos \phi \cos \psi   = r^2 c_1 \tag1 $$
$$ - \phi^{'}+ \frac{\cos \phi \sin^2 {\psi}}{r.\cos \psi  }= 2 c_1\cdot r \tag2 $$
( primed w.r.t. arc), please help in showing that:
$$ r \cdot \sin \psi= c_2 $$
where $c_2$ is a new constant.
Answer: Self answering the question.
Numerical integration yielded results with an image shown quite convincing to intuition although proof appeared tough at time of posting .. however kept on at it...
The result follows by eliminating $\phi^{'}$ between the given equations (1),(2) and differentials:
$$ r^{'}=\sin \phi \cos \psi; z^{'}=\cos \phi \cos \psi;\,r \theta ^{'}=\sin \psi; $$
Take logs Differentiate (1)
$$ \phi^{'}= \frac{\tan \psi^{'}}{r}-\frac{2\cos \phi \cos \psi}{ r^2 }\tag 3$$
Inserting $c_1$ from (1) into (2) and simplify
$$ \phi^{'}=\frac{ \cos\phi} {r \cos\psi} (1-3 \cos^{2}\psi) \tag4 $$
Equating RHS of (3) and (4) and simplifying we arrive at
$$\sin \phi - \cos \psi^2 \sin \phi + r \cos \psi \tan \psi \,\psi^{'}=0 \tag5$$
further simplifying,
$$ \sin \phi \sin \psi + r \psi^{'}=0;\,(r\sin \psi)^{'} = 0 \tag6 $$
$$ \rightarrow r\sin \psi = c_2 \tag7 $$


Find the value of $C$ such that $f(x)$ is... proper?

Question:
Let us build a customized Beta-typed random variable $X$ with the corresponding density function $$f(x) = C(1+x)^{g_1}(1-x)^{g_2}, \enspace \left|x\right|\leq1, \enspace g_1,g_2 \in \mathbb{Z^+}$$
  Find the value of C such that $f(x)$ is proper.

I'm not entirely sure what is meant by proper here but I assume it refers to the fact that the integral of the density function must  be equal to 1. So I set up the following equation in order to find C:
$$C\int_{-1}^{+1}(1+x)^{g_1}(1-x)^{g_2}dx = 1$$
(The limits are -1 and +1 rather than pos. and neg. infinity since x is only defined between them)
I'm struggling to integrate that expression. I tried integration by parts but ended up with an even harder integral. Am I integrating incorrectly?
Thanks
Answer: Just doing it by parts isn't going to get you far. I assume you know of the Beta function. To do this integral we have to sub in the incomplete Beta function, defined as $$B(x;a,b) = \int_{0}^{z} t^{a-1} (1-t)^{b-1} dt$$ This of course is just the regular Beta function for $x= 1$. Using this substitution we achieve: $$\left[ 2^{1 + g_1 + g_2} \beta_{\frac{(1 + x)}{2}}( 1 + g_1, 1 + g_2)\right] \Biggr|_{-1}^{1} = \frac{1}{C}$$
Which I'll leave to you to evaluate.
Answer: Conrad's answer is perfectly good, but I thought you might like something a little more elementary.
Integration by parts shows that:
$$\int_{-1}^{1} (1+x)^{g_{1}}(1-x)^{g_{2}}\,\mathrm{d}x = \frac{g_{2}}{g_{1}+1}\int_{-1}^{1} (1+x)^{g_{1}+1}(1-x)^{g_{2}-1}\,\mathrm{d}x$$
By induction, we then get
$$\ldots = \frac{g_{2}(g_{2}-1) \ldots 1}{(g_{1}+1)\ldots (g_{1}+g_{2})}\int_{-1}^{1} (1+x)^{g_{1}+g_{2}}\,\mathrm{d}x$$
which I'm sure you can show is equal to
$$2^{g_{1}+g_{2}+1} \bigg/(g_{1}+g_{2}+1)\binom{g_{1}+g_{2}}{g_{1}}.$$
Comment: Oops! Nothing happens to it, I just forgot to write it. I'll edit the answer.
Comment: What happens to the $g_1 + g_2 + 1$ in the denominator of the evaluated integral? It doesn't cancel for me...


Using adply in data.table

Question: I have a big data.table that looks like:
dt<-data.table(start=c("2012-07-13 23:45:00", "2012-07-14 15:30:00",
                       "2012-07-14 23:57:00"),
               end=c("2012-07-14 00:02:00", "2012-07-14 15:35:00",
                     "2012-07-15 00:05:00"), id=c(1,2,1),cat=c("a","b","a"))
dt
                 start                 end id cat
1: 2012-07-13 23:45:00 2012-07-14 00:02:00  1   a
2: 2012-07-14 15:30:00 2012-07-14 15:35:00  2   b
3: 2012-07-14 23:57:00 2012-07-15 00:05:00  1   a

I need to get an output that shows total minutes of event on each calendar day by id and category. Using the example above the output should be:
          day id cat V1
1: 13.07.2012  1   a 15
2: 14.07.2012  1   a  5
3: 14.07.2012  2   b  5
4: 15.07.2012  1   a  5

I used adply function from plyr package to split duration in intervals by minute:
fn<-function(x){
  s<-seq(from = as.POSIXct(x$start),
         to = as.POSIXct(x$end)-1,by = "mins")
# here s is a sequence of all minutes in the given interval
  df<-data.table(x$id,x$cat,s)

# return new data.table that contains each calendar minute for each id
# and categoryy of the original data
  df
}
# run the function above for each row in the data.table
dd<-adply(dt,1,fn)

# extract the date from calendar minutes
dd[,day:=format(as.POSIXct(s,"%d.%m.%Y %H:%M%:%S"), "%d.%m.%Y")]

#calculate sum of all minutes of event for each day, id and category
dd[,.N,by=c("day","id","cat")][order(day,id,cat)]

The solution above perfectly suits my needs except the time it takes for calculation. When adply is run in a very big data and several categories defined in fn function, it feels like CPU runs forever.
I will highly appreciate any hint on how to use pure data.table functionality in this problem.
Comment: I totally agree with that, but I couldn't come up with better solution :(
Comment: Am I reading this wrong but aren't you simply taking the difference of two datetime columns?
Comment: For starters, your whole prcedure will run a lot faster if you will convert `start` and `end` to `POSIXct` class only once using ```dt[, `:=`(start = as.POSIXct(start), end = as.POSIXct(end))]``` instead of doing it per each row. Then `s` would be just `s <- seq(start, end, by = "min")`. I'm guessing this is your main bottle neck
Answer: I would suggest a few things

Convert to as.POSIXct only once instead of per each row.
instead of adply which creates a whole data.table in each iteration, just use by within the data.table scope.
In order to do so, simple create an row index using .I

Here's a quick attempt (I've used substr because it will be probably faster than as.Date or as.POSIXct. If you want it to be Date class again, use res[, Date := as.IDate(Date)] on the result istead of doing it by group).
dt[, `:=`(start = as.POSIXct(start), end = as.POSIXct(end), indx = .I)]
dt[, seq(start, end - 1L, by = "mins"), by = .(indx, id, cat)
   ][, .N, by = .(Date = substr(V1, 1L, 10L), id, cat)]
#          Date id cat  N
# 1: 2012-07-13  1   a 15
# 2: 2012-07-14  1   a  5
# 3: 2012-07-14  2   b  5
# 4: 2012-07-15  1   a  5

Answer: Try to see if this is faster.
It's still data.table in the background, but I'm using a dplyr syntax for the process.
library(data.table)

dt<-data.table(start=c("2012-07-13 23:45:00", "2012-07-14 15:30:00",
                       "2012-07-14 23:57:00"),
               end=c("2012-07-14 00:02:00", "2012-07-14 15:35:00",
                     "2012-07-15 00:05:00"), id=c(1,2,1),cat=c("a","b","a"))

fn<-function(x){
  s<-seq(from = as.POSIXct(x$start),
         to = as.POSIXct(x$end)-1,by = "mins")
  # here s is a sequence of all minutes in the given interval
  df<-data.table(x$id,x$cat,s)

  # return new data.table that contains each calendar minute for each id
  # and categoryy of the original data
  df
}

library(dplyr)

dt %>%
  rowwise() %>%                        # for each row
  do(fn(.)) %>%                        # apply your function
  select(day=s, id=V1, cat=V2) %>%     # rename columns
  mutate(day = substr(day,1,10)) %>%   # keep only the day
  ungroup %>%
  group_by(day,id,cat) %>%
  summarise(N=n()) %>%
  ungroup

# Source: local data frame [4 x 4]
#
#           day    id   cat     N
#         (chr) (dbl) (chr) (int)
# 1 2012-07-13     1     a    15
# 2 2012-07-14     1     a     5
# 3 2012-07-14     2     b     5
# 4 2012-07-15     1     a     5

Using adply in data.table


How do I programmatically set a content reference by name for a node?

Question: Hi team i have some isssues.
I'm creating a node and i would like to set a content reference by name not by id, i'm doing this but this is not working:
'field_content_type_items' is referenced to another content type
$node = \Drupal\node\Entity\Node::create([
    'type' => 'items',
    'status' => $status,
    'title' => $title,
    'field_content_type_items' =>  "CUN",
]);

Also i tried with this example 'field_content_type_items' => [['target_id' => 12]], but i dont know the id for CUN so i cant use target_id
also i've tried:
$node->set('field_content_type_items', 'CUN');

could you please help me?
How can i set a content name when i create a node?
Regards
Mario
Answer: Entity reference fields expect an entity ID, so unless you want to extend the field type (which could get unnecessarily messy), you'll need to get the ID of the target content.
One method to do this is EntityStorageBase::loadByProperties(), e.g.
$target_nodes = \Drupal::entityTypeManager()->getStorage('node')
  ->loadByProperties(['title' => 'CUN', 'type' => 'foo']);

if (count($target_nodes)) {
  // For the sake of example assume the first node is the right one.
  $target_id = reset($target_nodes)->id();

  // ...
}

Bear in mind that node titles aren't unique, so you might need to add some extra filtering logic to get the exact node you need.
Comment: yes that's what i thought, to get id node using some query and then using in target_id, thanks


Deploying multiple applications on an application server(weblogic/websphere)

Question: When multiple applications are deployed to an application server, do they all share the same JVM?
If not, is each application targeted to a different JVM?
If yes, then will it not become a performance issue - ex: multiple applications using same heap space which means more frequent garbage collection etc?
Is it not a good idea to deploy these applications as self contained Sprinboot with tomcat?
I know we have an option of using different domains to have separate JVM's for each application - but still having many application servers up and running could also consume more resources?
Comment: With Tomcat you can either arrange it to share the same Tomcat or to have different Tomcat bases
Comment: I understand, but my question is which is better ( using springboot+tomcat as opposed to weblogic/websphere and targeting multiple applications to the same instance of application server vs each application having its own container). Tomcat is light weight compared to weblogic/websphere.
Comment: As it stands this question is off topic for several reasons: [1] It is far too broad, and contains multiple questions. [2] It invites opinion based answers. [3] [Questions on professional server, networking, or related infrastructure administration are off-topic for Stack Overflow unless they directly involve programming or programming tools](https://stackoverflow.com/help/on-topic). In general questions on application server architecture are off topic here unless there is a programming related aspect.
Answer: Talking for weblogic server, all deployed applications share same JVM. Frequency of garbage collection is related with Min/Max Heap sizes that you set. Setting the minimum heap size (-Xms) smaller or the maximum heap size (-Xmx) larger affects how often garbage collection will occur and determines the approximate amount of live data an application can have.
For further information: https://docs.oracle.com/cd/E13221_01/wlrt/docs11/intro_wlrt/tuning.html
https://docs.oracle.com/cd/E12529_01/wlss31/configwlss/jvmgc.html
https://blogs.oracle.com/imc/weblogic-server-performance-and-tuning:-part-i-tuning-jvm
Comment: Clustering does not affect the answer for this question. When you cluster your servers, it doesn't mean that you provide seperate JVMs to seperate applications, it means that your application is running on several JVMs. Clustered or not, multiple applications will be running on a particular JVM at the same time. Question is about sharing JVM among applications. It's not about running single application on several instances.
Comment: What about when there is a cluster of WebLogic servers? In that scenario can't you have a single deployed application running on multiple WebLogic servers (and therefore multiple JVMs) concurrently? That can certainly be done with WebSphere, for scaling and resilience.
Comment: Sure you can, otherwise clustering would be totally pointless i think.
Comment: Then your statement that _"all deployed applications share same JVM"_ is not necessarily true, right?


A car is moving at 40 km/h. A fly at 100 km/h, starts from wall towards the car(20 km away)flies to car and back. How many trips can it make?

Question: A car is moving at a constant speed 40 km/h along a straight road which heads towards a wall.A fly flying at a constant speed of 100 km/h, starts from wall the towards the car at a instant when the  car is 20 km away, flies until it reaches the car and comes back to the wall at the same speed.It continues to fly between the car and the wall till the car reach the wall. How many trips has it made between the car and the wall?
I don't expect a brute force because I already did that. Some thing like arithmetic/geometric/harmonic progression will satisfy my curiosity.
Comment: In theory infinitely many.
Comment: This 100 km/h fly is a very impressive aviator given that ordinary houseflies have a max speed of 8 km/h. Even more impressive is its ability to instantaneously go from +100 km/h to -100km/h without feeling a bit groggy for a moment.
Comment: At least it's not a spherical cow....
Comment: Possible duplicate of ['Bee flying between two trains' problem](https://math.stackexchange.com/questions/1805312/bee-flying-between-two-trains-problem)
Comment: @Herohtar: ...and [Fly and Two Trains Riddle](https://math.stackexchange.com/questions/149479/fly-and-two-trains-riddle) and [2 Trains and Fly Problem. Find the number of trips made by the fly back and forth.](https://math.stackexchange.com/questions/779107/2-trains-and-fly-problem-find-the-number-of-trips-made-by-the-fly-back-and-fort) and probably others too.
Comment: i think right now question is a bit off-topic. This website is not designed to "satisfy [your] curiosity". You should show some work toward solution
Comment: I'm confident the question is supposed to be "what is the total distance the fly travels", not "how many trips can it make".  Otherwise it's a silly trick question.
Comment: How long is the fly? What is the fly's acceleration curve? Neither is negligible.
Comment: 100 kph!? What kind of super fly is this? A normal housefly can fly at about 5mph/8kph.
Comment: And, of course, it's probably worth linking to [Problem: Two Trains and a Fly](https://math.stackexchange.com/questions/619/problem-two-trains-and-a-fly) (that's post #619 on this site!) even though it's not actually a duplicate (as this question asks for the number of round trips rather than the total distance).
Answer: It has made infinitely many trips. Every trip will be shorter than the last, but the fly will always reach the wall before the car, so it will always have room for one more trip. And one more. And one more.
The total length the fly flies is 50km, as the car crashes into the wall exactly 30 minutes after the whole experiment started.
Comment: @user654700:  This is rigorous.  One can also write an equation for the length of each trip the fly makes and sum the series, but under the assumptions that is not needed.  Don't confuse rigor with fancy mathematical symbols.  There is a [famous anecdote about John von Neumann and this puzzle](http://mathworld.wolfram.com/TwoTrainsPuzzle.html).
Comment: I got that but can you please give me more rigorous proof? If you don't mind.
Comment: @user654700 What exactly do you find not rigorous enough?
Comment: I suppose there are some minor details that could be added to give it some more rigor (or at least make the rigor more obvious): when the fly is at the position of the car, it has to travel the same distance to get to the wall, but its speed is greater, so it will always reach first. Once the fly is at the wall, we know that the car is not yet at the wall, due to the above reasoning. Since the fly has nonzero speed and the car does not have "infinite" speed, the fly and the car will next meet at some point between their current positions (not at the wall). Repeat.
Comment: Well, one can figure that if the fly is at the wall and the car is a non-zero distance away that the fly flies to the car and that takes some non-zero time (they have a combined speed which is finite so to cover a distance takes non-zero time).  The fly will then fly to the wall.  As the fly is faster it reaches the wall first.  The car is now a non-zero distance away.  Thus is the same situation as before so *by induction* there will be an infinite number of trips .  That is formal and rigorous.
Comment: To be fully rigorous, you also have to assume the fly is a mathematical point and can reverse direction instantaneously.
Answer: Suppose the fly is at the wall.  And suppose this will be the last trip or partial trip of the fly.  Suppose the car is $h$ miles away.
The fly and and car have a combined speed of $140 \frac {km}{hr}$ so the fly reaches the car in $\frac h{140}$ hours.  In that time the car has traveled $40\frac h{140} = \frac 27h$ and is now $h-\frac 27h = \frac 57h$ from the wall.  So the fly heads back to the wall.
As the trip back is just as far this takes $\frac h{140}$ hours and the car has traveled another $\frac 27h$ and is now $\frac 37h$ from the wall. [1]
So the fly starts another trip, contradicting that this was his last.  So the fly never makes a last trip an instead there are an infinite number of trips.
Figuring out how far the fly flies is a matter of noting the car is on a straight path and travels $20km$ at $40 kmh$ so this takes $30$ minutes.  The fly no matter how many times (infinitely many) it zigs will travel at $100kmh$.  So in $30$ minutes it flies $50 km$.
If one wishes to set this up as an infinite sum.....
Each trip the fly flies $\frac {10}7$ of the distance the car was away. And each trip the car is $\frac {3}{7}$ of the distance it was before.  So the distance the fly travels is $\sum_{k=0}^{\infty} \frac {10}7*(\frac {3}{7})^k*20$ which if I did this correctly is
$\frac {10}7*20(\sum_{k=0}^{\infty} (\frac {3}{7})^k)= \frac {200}{7}\frac 1{1-\frac {3}{7}} = \frac {200}{7}\frac {7}{4}= 50$km.
[1](for the record, in this time, $\frac 1{70}h$ hours, the car has traveled $\frac 47h$ and the fly has travelled $\frac {10}7h$).
Answer: Simple way to calculate it: It takes the car 30 minutes to travel the 20km to the wall at 40km/hr. The fly, traveling at 100km/hr will travel 50km in those same 30 minutes.
Edit: There will be an infinite number of trips. It's similar to how Zeno's paradox works where the trips get shorter and shorter and eventually take an infinitely small amount of time. But all those infinitely small trips end up as a finite amount of distance.
Answer: Arthur's answer is very good, but here is another (equally valid) way of visualizing the problem:
Let us graph the positions of the wall, fly, and car over time. The wall doesn't move, so it is represented by a horizontal line. The car starts at some distance away from the wall but moves towards it at a constant speed until it hits the wall -- so we have a line that intersects the wall's line. Now for the interesting part:
The fly's path starts off as a line with greater slope than the car's line, until it hits the wall's line. The fly's speed remains the same, but it is going in the opposite direction. So now the path continues as if the wall's line was a mirror and it was reflected. When the fly hits the car, the same thing happens -- the fly's path is reflected and it continues towards the wall again (one caveat: when it bounces off the car's line, the angles of incidence and reflection are not equal so it isn't behaving exactly as light would).
So we can see that the fly's path continues bouncing up and down, always at the same or opposite slope.
The final thing to notice to grasp the intuition is that this diagram we have constructed is self-similar. If we zoom in so that the second bounce with the wall is where the first bounce used to be, we have the same exact diagram as before. I won't prove this, but if you draw it out, you can see it intuitively. Essentially, this means that no matter how close the car gets to the wall, we can zoom in and see more bounces for the fly.


Understanding failed connection reason

Question: Edit: The issue came about because our machines did not have external IP address and so outgoing traffic was going through Cloud NAT, which was misconfigured (min connections per vm)
I am having issues with a GCP machine being able to connect to an external HTTP server. Below is a line from tcpdump
<code>16:17:26.561616 IP 184.108.40.206 > 220.127.116.11.http: Flags [S], seq 1152634327, win 28400, options [mss1420,sackOK,TS val3415260604 ecr 0,nop,wscale 7], length 0
16:17:26.561736 IP 220.127.116.11 > 188.8.131.52: ICMP host 188.8.131.52 unreachable - admin prohibited filter, length 68

22.214.171.124 is a GCP gateway
126.96.36.199 is my machine on GCP
184.108.40.206 is the external server
</code>
How do I know which machine is enforcing the rule that blocks the connection attempt?
Comment: It's probably the machine that the ICMP message came from. That's what it is in every other case. BTW, you should not fake RFC1918 addresses, nor use other people's public IP addresses as examples. See [here](https://meta.serverfault.com/q/963) for details and advice.
Answer: GCP has 2 implied rules stated in the link . The implied egress rule permits all the egress traffic with the lowest priority (65535).
I have replicated the scenario an placed a firewall rule to my GCP project (wheew is my GCP VM source address) denying all the egress traffic to a specific external address (x.x.x.x), I got that TCPdump (performed over my instance) shows reattempts of connection:
Where x.x.x.x is an external IP and vminstance is my GCP Instance.
18:19:50.499009 IP vminstance.39728 > x.x.x.x.80: Flags [S], seq 1309572437, win 28400, options [mss 1420,sackOK,TS val 323066870 ecr 0,nop,wscale 7], length 0
18:19:51.527849 IP vminstance.39728 > x.x.x.x.80: Flags [S], seq 1309572437, win 28400, options [mss 1420,sackOK,TS val 323067128 ecr 0,nop,wscale 7], length 0
So stated that, and compared to your output you may want to look the remote network/host firewall rules
Comment: Turns out the issue was due to a misconfigured GCP NAT gateway.

Understanding failed connection reason


how can I reduce 2 select to 1 select linq to gain performance?

Question: my question is simple but I got stuck with something. Can you tell me how can I reduce 2 select into 1 select LINQ in c#? I am using CloudNative.CloudEvents NuGet package for cloud-native events.
var orderEvents = input
    .Select(_ => new OrderDocument(_.Id, _.ToString()).ToOrderEvent())
    .Select(_ =>
        new CloudEvent()
        {
            Type = _.EventType,
            Subject = _.Subject,
            Source = _.Source,
            Data = _
        });

input is a parameter from cosmosDbTrigger it`s type : IReadOnlyList
OrderDocument.cs
public class OrderDocument
{
    public string Id { get; private set; }

    public string Json { get; private set; }

    public OrderDocument(string id, string json)
    {
        Id = id;
        Json = json;
    }

    public OrderEvent ToOrderEvent() => OrderEventHelper.ToOrderEvent(Json);
}

OrderEventHelper.cs
public static OrderEvent ToOrderEvent(string json)
{
    ArgumentHelper.ThrowIfNullOrEmpty(json);

    var orderEvent = JsonConvert.DeserializeObject<OrderEvent>(json);
    var eventDefinition = OrderEvents.EventDefinitions.SingleOrDefault(_ => _.EventType == orderEvent.EventType);

    return eventDefinition == null
        ? orderEvent
        : new OrderEvent(
            orderEvent.Id,
            orderEvent.Source,
            orderEvent.EventType,
            orderEvent.Subject,
            orderEvent.DataContentType,
            orderEvent.DataSchema,
            orderEvent.Timestamp,
            JsonConvert.DeserializeObject(orderEvent.Payload.ToString(), eventDefinition.PayloadType),
            orderEvent.TraceId);

}

Comment: TBH I highly doubt that your performance issues (if you have any) will be fixed by reducing number of selects. Have you profiled your application? Do you know what actually the hotspot is?
Comment: You should avoid using the discard operator `_` as an actual variable you consume.  `_.Id` is asking for future readers of your code to be confused.
Comment: You can do both actions in one select by passing a function through the `Select` rather than just returning the `OrderEvent`, see my updated answer for an example.
Comment: @Penguen Look into Deferred Execution, the chained `Select` should still only iterate your collection once: https://stackoverflow.com/questions/7324033/what-are-the-benefits-of-a-deferred-execution-in-linq
Comment: @Ibrennan208 why do you address this to me? =)
Comment: @GuruStron Haha, my mistake, I fixed it. I really just wanted to type your name :p
Comment: @GuruStron  I didn`t measure performance by using profiler or anything for my issue but Undoubtedly, select().select() is not the best practice and it will produce a couple of performance issues.
Comment: @Penguen while I agree that chained selects are not that great, but from the performance standpoint of view for LINQ-to-Objects the difference should be minimal (for ORMs - it can depend on actual ORM and database).
Answer: linq extensions are basically for loops in the background. If you want to perform multiple actions against a list, perhaps making your own simple for loop where you can manage that yourself would work.
Your code:
var orderEvents = input
    .Select(_ => new OrderDocument(_.Id, _.ToString()).ToOrderEvent())
    .Select(_ =>
        new CloudEvent()
        {
            Type = _.EventType,
            Subject = _.Subject,
            Source = _.Source,
            Data = _
        });

could be changed to:
// our result set, rather than the one returned from linq Select
var results = new List<CloudEvent>();

foreach(var x in input){
   // create the order event here
   var temporaryOrderEvent = new OrderDocument(x.Id, x.ToString()).ToOrderEvent();

   // add the Cloud event to our result set
   results.Add(new CloudEvent()
   {
       Type = temporaryOrderEvent .EventType,
       Subject = temporaryOrderEvent .Subject,
       Source = temporaryOrderEvent .Source,
       Data = temporaryOrderEvent
   });
}

where you then have a result list to work with.
If you wanted to keep it all in linq, you could instead perform all of your logic in the first Select, and ensure that it returns a CloudEvent. Notice here that you can employ the use of curly brackets in the linq statement to evaluate a function rather than a single variable value:
var orderEvents = input
    .Select(x =>
    {
       // create the order event here
       var temporaryOrderEvent = new OrderDocument(x.Id, x.ToString()).ToOrderEvent();

       // return the Cloud event here
       return new CloudEvent()
                  {
                       Type = temporaryOrderEvent .EventType,
                       Subject = temporaryOrderEvent .Subject,
                       Source = temporaryOrderEvent .Source,
                       Data = temporaryOrderEvent
                  };
    });

Answer: How about putting conversion to OrderEvent and using ToCloudEvent in the same Select?
var orderEvents = input
    .Select(_ => new OrderDocument(_.Id, _.ToString()).ToOrderEvent().ToCloudEvent())

public class OrderEvent
{
    public CloudEvent ToCloudEvent()
    {
        new CloudEvent()
        {
            Type = this.EventType,
            Subject = this.Subject,
            Source = this.Source,
            Data = this
        };
    }
}


Variable initialization past Xstream

Question: Consider the following declaration as part of SomeClass
private Set<String> blah    = new HashSet<String>();

Made in a class, which is later
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);

StringBuilder json = new StringBuilder(xstream.toXML(SomeClass));

rd = (SomeClass) xstream.fromXML(json.toString());

When i @Test
assertTrue(rd.getBlah().size() == 0);

I get an NPE on rd.getBlah()
When I, instead of initializing up front, place initialization to a constructor of SomeClass
public SomeClass() {
  blah = new HashSet<String>();
}

Same problem - NPE on rd.getBlah()
When i modify the getter to check for null first, it works, but ..
public Set<String> getBlah() {
   if (blah == null)
      return new HashSet<Sgring>();
   return blah;
}

I am puzzled ... Why does XStream not initialize variables and whether lazy instantiation is necessary?
Comment: I am a little confused by xstream.toXML(SomeClass);  Shouldn't it be xstream.toXML(object) where object is of type SomeClass?
Comment: If there is anything we know it is that `SomeClass` is most certainly of type `SomeClass` :)
Comment: My point was: taking what you've written above at face value, if SomeClass is a type, then your code above does not compile.  SomeClass is not of type SomeClass, and neither is SomeClass.class of type SomeClass...
Answer: XStream uses the same mechanism as the JDK serialization. When using the enhanced mode with the optimized reflection API, it does not invoke the default constructor. The solution is to implement the readResolve method as below:
public class SomeClass{
    private Set<String> blah;

    public SomeClass(){
        // do stuff
    }

    public Set<String> getBlah(){
        return blah;
    }

    private Object readResolve() {
        if(blah == null){
            blah = new HashSet<String>();
        }
        return this;
    }
}

Reference
Comment: Thank you. Indeed this works!. Two things: could you provide a reference to the above and how may i find out whether i am running in enhanced mode or not?
Comment: @JAM, 1) I provided the reference below the code snippet and 2) I am not sure, but I believe it runs in this mode by default..
Comment: Why does readObject() not work in this instance? I have a similar problem here: http://stackoverflow.com/questions/15752945/xstream-wont-call-readobject in which readObject() seems to be the right solution, but only readResolve() works.

Variable initialization past Xstream