Two children paradox: where is my reasoning wrong?

Question: I hope here is the good place to be asking this. Apologies otherwise.
The statement is as follows:
"Ms Michu has two children. We know one of the two is a girl, we call that girl Ludivine. What is the probability that Ludivine has a brother, rather than a sister?"
This is with the usual assumptions that there is an equal chance for one person to be a boy or a girl, no cis or gemels, etc.
I read that the answer should be 2/3. Demonstration is :
For any given set of 2 children, there are 4 different equiprobable combinations:
GG BB BG GB
We get rid of the bb combination because there is no girl. That leaves us with 3 possibilities, of which 2 match the criteria of the statement, hence the probability of Ludivine having a brother is of 2/3.
But, if I follow the following reasoning, I obtain a probability of 1/2:
Ludivine(L) is either the elder(e) or the youngest(y), with an equal probability of 1/2.
If she is the elder(e), it gives 2 combinations, with again a probability of 1/2 for each:
B(y) G(L)(e)
G(y) G(L)(e)
If she is the youngest we again have 2 equiprobable combination :
G(L)(y) B(e)
G(L)(y) G(e)
By combining those probabilities, we have 2 cases out of 4 where she has brother. Therefore she has a probability of 2/4 or 1/2 to have a brother.
Now I feel like my reasoning is wrong somewhere, but I can't see where or why, even though i went through quite a few topics on the subject; hence why I'm re-discussing that old topic...
Thanks in advance!
Comment: kind of, it's just a different explanation - you could say i need more elements of concrete thinking, say pedagogical, because i'm not used to mathematics.
Comment: I don't understand.. wasn't the whole point of the original 4 possibilities GG, GB, BG, BB already sorted by youngest and oldest? Otherwise what is the *real* difference between GB and BG?
Comment: Ahh well the main problem here is that it's not just GG, GB, BG, BB ... if order matter like the difference between GB & BG then you also have to have the difference between the girls... girl_1 then girl_2 or girl_2 then girl_1, so your real data set is: gg, gg, gb, bg, bb, bb — Which still equates to 50% chance it's a boy, not 66.666%
Answer: The problem is not really with your reasoning as much as with your interpretation of the question.
In the first interpretation, we know that there is a girl, and then we pick one of them, and then ask what is the probability that the other child is a boy. In this case, since we know that there is a girl, there are as you say exactly 3 equally probable possibilities, GG,GB,BG. And hence we can check that the answer is $\frac{2}{3}$.
In the second interpretation, we pick a child at random, and then it turns out to be a girl, and then we ask what is the probability that the other child is a boy. In this case, there are exactly 2 equally probable possibilities, GG and GB, where the first letter denotes the gender of the picked child, and the second letter denotes the gender of the other child. Clearly the answer is $\frac{1}{2}$. (Your added "reasoning" about the picked child being elder or younger isn't important.)
So the underlying issue is that when specifying a probability question, it is absolutely crucial to clearly state the order in which actions are performed.
Comment: oooh, yeah, so i pick a child, regardless if he is elder or younger, it drives me out of the "at least one" territory. I didn't realize i picked a child... i built the reasoning around a sampled child... i thought that, by examining each "child picked is a girl" situation, it would automatically add up to all equiprobables situations, which it didn't. Thanks !
Comment: @vic: You're welcome! By the way, you should upvote all helpful answers, and accept the one that helped you the most so that this question doesn't remain unanswered.
Comment: i would gladly upvote all the answers here, but it says i don't have enough reputation to upvote (need 15). (also i didn't see that i could select the most helpful answer or something)
Answer: It looks like you're double counting the two girls case. If you assign 1/8 chance to G(L)(y) G(e) and another 1/8 to G(y) G(L)(e), then you have:
B(y) G(L)(e) with chance .25
G(y) G(L)(e) with chance .125
G(L)(y) B(e) with chance .25
G(L)(y) G(e) with chance .125
We've obviously excluded the double boy case, but we should condition on no boys. So then we have 2/3 chance of a brother.
Answer: The probability of the situation you have described as "B(y) G(L)(e)" is $\frac{1}{4}$, as you have said.  But the probability of "G(y) G(L)(e)" is $\frac{1}{8}$: probability that elder child is a girl, $\frac{1}{2}$; probability that younger child is a girl, $\frac{1}{2}$; probability that you give the name Ludivine to the elder of the two girls, $\frac{1}{2}$.  Therefore these two events are not equiprobable.
Answer: How exactly do we know one of the two is a girl? We don't just abstractly know it. There is some story how we received the information. If we meet a person in hospital visiting a sick child, and that is how we gained the information, there is an equal chance that we would have received the information "Ms Michu has at least one boy" or "Ms Michu has at least one girl". If we meet Ms Michu picking up her child at a girls' school, we couldn't have received the information "Ms Michu has at least one boy" because it's a girls' school and she had to pick up a girl.
People with two boys turn up at hospitals visiting a sick child. People with two boys don't turn up at girls' schools to pick up their child. So how we got the information influences the result.


How to calculate number of triangles and points after dividing a triangle n times?

Question: When having a triangle and dividing it n times, how to get the number of triangles and points?
<code>      a
     / \
    /   \
   f-----d
  / \   / \
 /   \ /   \
c-----e-----b
</code>
edit: This triangle is part of an icosahedron as base geometry for a sphere, left it out due to jitter information. Then the assumptions took place.
Comment: Hope that I tagged right, don't no any mathmatic terms while english isn't my first language. Please tell me if/what is wrong, I'll update ASAP. Lack of naming conventions makes searching a horror too.
Comment: $N_{triangles}=4^n$
$N_{points}=3\cdot\frac{3^n-1}{2}$
Comment: If by "divide $n$ times" you mean subdivide each of the small triangles that resulted from the last operation, repeated $n$ times, then the number of triangles is a simple formula but the number of points would depend on how you create and count the vertices. On the second subdivision, do you exactly bisect each edge so that the new triangle inside $\Delta cef$ and the new triangle inside $\Delta def$ share a single vertex on the edge $ef$, and if so, do you count that vertex just once?
Comment: My previous comment assumed you subdivide the upside-down triangles too. If you don't, then there's no ambiguity about how you count the number of points.
Comment: My apologies for the delay - an emergency arised here and had to leave.
Comment: Δdef will be divided too and those vertices will be counted once for both (Δcef and Δdef). But it won't be a bore two know how it is calculated of those are counted twice.
Answer: Each division multiplies the number of small triangles by $4$, and you start with one triangle at $0$ divisions, so the number of triangles after $n$ divisions is $4^n$.
The number of distinct horizontal sides of small triangles after $n$ divisions is
$$\sum_{k=1}^{2^n}k=\frac{2^n(2^n+1)}2=2^{n-1}(2^n+1)\;.$$
There are the same number of distinct sides of small triangles parallel to each of the non-horizontal sides of the original triangle, so there are altogether $3\cdot2^{n-1}(2^n+1)$ distinct sides of small triangles after $n$ divisions.
Now let $p_n$ be the number of vertices after $n$ divisions; clearly $p_0=3$. If $n\ge 1$, there are $3\cdot 2^{n-2}(2^{n-1}+1)$ small sides after $n-1$ divisions, and the $n$-th division adds one vertex for each of those sides, so
$$p_n=p_{n-1}+3\cdot2^{n-2}(2^{n-1}+1)\;.$$
Thus,
$$\begin{align*}
p_n&=p_0+\sum_{k=1}^n3\cdot 2^{k-2}(2^{k-1}+1)\\\\
&=3+3\sum_{k=1}^n\left(2^{2k-3}+2^{k-2}\right)\\\\
&=3+\frac32\left(\sum_{k=0}^{n-1}4^k+\sum_{k=0}^{n-1}2^k\right)\\\\
&=3+\frac32\left(\frac{4^n-1}3+2^n-1\right)\\\\
&=2^{2n-1}+3\cdot2^{n-1}+1\;.
\end{align*}$$


pandas: replace non-empty rows in a column with a list

Question: I have a dataframe like the following (but longer) with some rows containing None values:
data = {'first Column':  ['she is', 'they are',NaN,'we are',NaN],
    'second Column ': ['my', 'her',NaN,'his',NaN],
    'third column': ['friend', 'brothers',NaN,'sisters',NaN]
    }

df = pd.DataFrame (data, columns = ['first Column','second Column','third column])

my_list= ['gold','silver','bronze']
I would like to replace every row in the 'third column' with a list if it does not contain none value, like this :
  desired output:
     first column   second column   third column
  0  she is          my             ['gold','silver','bronze']
  1  they are        her            ['gold','silver','bronze']
  2  NaN             NaN            NaN
  3  we are          his            ['gold','silver','bronze']
  4  NaN             NaN            NaN

I have tried np.where, but it does not select the desired rows
   np.where(df.loc[df['third column'] != 'NaN', [','.join(my_list)], df['third column']

Answer: df.loc[df['third column'].notna(),'third column']=[my_list]

Result:
  first Column second Column             third column
0       she is             my  [gold, silver, bronze]
1     they are            her  [gold, silver, bronze]
2          NaN            NaN                     NaN
3       we are            his  [gold, silver, bronze]
4          NaN            NaN                     NaN

PS: if you specifiy data as a dict with column names you don't need the columns argument in the dataframe constructor.


Is it less secure to use a passphrase-removed key with apache?

Question: I have a simple website with an ssl certificate and I noticed that when I would reboot apache was asking for the passphrase (causing the server to halt essentially).
I did the following to remove it (fixing my issue w/ the reboot)

openssl rsa -in foo.key -out foo.key.nopass

The question I have is, does this in any way reduce the effectiveness of my ssl cert?
Answer: In normal operation (ie, with an encrypted private key), the private key is known to the running webserver, but isn't present on-disc.  In order to get a copy of the private key, an attacker would have to subvert the running webserver.
If you leave the private key constantly decrypted on-disc, then (assuming you have the permissions set tightly) an attacker needs only to subvert the file system.
But as you've observed, there is a cost to leaving the key encrypted on-disc: unattended restarts aren't possible.  Only you can say whether the additional security afforded by leaving the key encrypted on-disc justifies the additional cost.
For myself, I suspect that anyone who can subvert file system protections can probably read your web server's memory anyway (think <code>/proc/kcore</code>), and thus the difficulty of extracting the decrypted key from the memory map of the running server is the only additional protection afforded by encrypting the key.  I tend to assume attackers are intelligent, so that makes the additional security fairly small.


DocumentDB Spatial - Request Rate is large

Question: So, my collection contains 25,000 points and 15,000 polygons.  I guess the polygons are fairly large, most of the worlds land mass is covered.
The points are coming back fine.  The first polygon in the collection comes back fine, when i do a query like:
<code>SELECT TOP 2 * FROM c.features[0] f WHERE (f.geometry.type='Polygon' OR f.geometry.type='MultiPolygon') AND ST_WITHIN({'type':'Point','coordinates':[26.35, 31.00]}, f.geometry)
</code>
If I use different coordinates for this query, I am getting a "Request Rate is large" message, try again after a few seconds.
Does DocumentDB not deal well with spatial queries on a large collection of polygons?
Edit1: Query takes 1157.53 RUs, and the current pricing tier is S1 so 250RUS...I may see my problem!
Edit2: So I updated the collection to S2, then S3. RUS were going up to 11,000, and I'm still getting "Request Rate is Large". What can be done?  The documents are about 50kb in size, 15,000 of them.  Doesn't seem like a lot to me
Edit3: I am completely flummoxed as to why, if I change the coordinates by 1 degree, the query fails.
Edit4: Selecting by ID comes back at 3.49RU. Select by asking, is a point inside a polygon...over 11,000. Is this normal?  If it is, is DocumentDB suitable for anything other than storing and querying point data?
Thanks
Comment: Have you looked at the RU cost for each query? Also: What RU cap is your collection set to? Please edit your question with this information.
Comment: OK will do @DavidMakogon
Answer: So... per edit: Given that your spatial query RU cost is ~1000 RU, and you're at a 250RU tier... the first query gets honored, but then you're in a "deficit" state (you basically ate up your RU allocation for about ~4 seconds). And that explains why you're throttled for a short bit of time.


Dealing with hook_cron when configuration is required

Question: What's the best way in dealing with functions that require configuration in a hook_cron?
Example (pure fiction):
My hook_cron calls function_close_ticket, this function has various variable_gets all of which have defaults but those defaults may not be relevant to the users setup (they are however relevant to a default casetracker setup), especially if the user has customised casetracker a lot.
Would I be best leaving as is and letting hook_cron fire or wrapping the function inside in a call to get the state of a user configurable variable? Or is there some other way of dealing with this problem?
Answer: If you require configuration, then you shouldn't provide a default value using variable get (You provide an empty default value instead). If the no value is set, you should make a log using watchdog and exist without doing anything, since the conf was missing.
If you can provide a default settings that would make everything work, that would be a better option, since the user don't have to do any setup, be can if he wants to.
The checks should not really happen in cron, but in the function actually doing whatever needs to be done.
Comment: Thanks I've switched things around in my module so it takes all this into account.
Answer: In addition to making a watchdog entry as googletorp suggests, if the module simply doesn't work without a user setting up some configuration options, you should consider implementing hook_requirements() so that if a user checks their site status report, they'll be prompted to visit the configuration page.


Sinatra enable :sessions not working on passenger/apache

Question: Am having trouble getting enable :sessions to persist for a simple Sinatra app hosted on passenger/apache. I'm storing the state of session[:authorized] in a cookie. It works locally when hosted on Rack::Handler::Mongrel but I can't seem to get same behaviour on passenger.
I've tried two methods for enabling sessions, both of which don't work on the passenger/apache installation
enable :sessions
and
use Rack::Session::Pool, :domain => 'example.com', :expire_after => 60 * 60 * 24 * 365
Any ideas on how to fix?
Answer: We were facing something similar although we were not using Apache / Passenger (in development mode). We resolved it like this -
Comment out the Rack::Session commands from within your Sinatra app. Do it in the config.ru file. and haven only enable :sessions in your sinatra app.
That should work.
Answer: This issue occurred for me because I had enabled sessions in the wrong configuration area. My configuration looked like this:
configure :development do
  # ... other settings ...
  enable  :sessions
end

By moving enable :sessions out of the :development specific configuration sessions started working for me:
configure :development do
  # ... other settings ...
end

enable  :sessions


in cloudformation is it possible to create a reusable string?

Question: i have a string the is formed from a number of variables which i use for many different things such as Tags and host names.
is there a way of creating a reusable string  that i can just Ref though out the template?
any thoughts on this would be much appreciated.
edit:
An example would be passing in 2 parameters
such as ProjectName and Environment
joining them
"Fn::Join" : [ "-", [ {"Ref":"ProjectName"}, {"Ref":"Environment"} ] ]

and using the results in a number of places
Comment: Are you talking about a parameter? http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/concept-parameters.html
Comment: I think Transformations are what AWS provide for this. Sadly, they don't support YAML aliases yet.
Answer: Unfortunately my experiments are to agree with your conclusion Graeme.  I have struggled with this for some time but not found a way of computing a String via Fn::Join and keeping it for later in the template.
Can I share with you a typical example?
As at 2014-09-18, the most sophisticated way of storing a string value for re-use in the Resources section would be via a (second-level) Mapping.  Better still, I can pre-compute a Condition and determine whether to use the string or not.  But unfortunately the storing of a string just does not work.
Here is an example stanza of such a Mapping …
    "LoadBalancerBucketMap": {
        "BucketName": {
            "string": {
                "Fn::Join": [
                    "-",
                    [
                        "mylb",
                        {
                            "Ref": "Environment"
                        },
                        "logs"
                    ]
                ]
            }
        }
    },

And here is an access expression to it in a Resource
                "S3BucketName": {
                    "Fn::FindInMap": [
                        "LoadBalancerBucketMap",
                        "BucketName",
                        "string"
                    }

In this example, Environment is a literal string Parameter with a convenient default.  So that is a very clear example of creating and re-using a string.  But here is what the CloudFormation processor says …
Template validation error: Template format error: Every Mappings attribute must be a String or a List.
So I share your frustration that there does not seem to be a way in a template to provide the effect of a temporary string variable.
… So far as I can see.  But the answer you originally received said the opposite of this (although without an example).
So if anyone does have an example workaround, then please could they share?
Answer: You can use params or mappings to store strings that you can use in your templates.
Comment: This only works for static strings. The OP specifically asked for computed strings, which doesn't seem to be possible at all.
Answer: unfortunately i have found that it not possible to do what i was trying to achieve.
it doesn't help but there it is.
Answer: We actually make our CloudFormation stack name exactly {ProjectName}-{Environment} during aws cloudformation deploy. Have you considered this naming convention for your stack name?
Afterwards, you can just reference it as { "Fn:Sub": "${AWS::StackName}" }.
Answer: If you haven't switched to CDK, you might consider switching to YAML. YAML has a concept of anchors (&) and aliases (*) that can be used anywhere in a document. The anchor must be defined before the alias is used. There's also a merge thing (<<: *<name>) that is almost always supported, including SAM or whatever I'm using, but not officially in the YAML spec.
This can make it easy to reuse whatever you'd like after it is first defined.
Resources:

  Hello:
    Type: AWS::Serverless::Function
    Properties: &FUNCTION_PROPERTIES      # This is the anchor
      Handler: index.handler
      Runtime: python3.6
      InlineCode: |
        def handler(event, context):
          print("Hello, world!")
      ReservedConcurrentExecutions: 30
      Layers:
        - Ref: MyLayer
      Tracing: Active
      Timeout: 120
      FileSystemConfigs:
        - Arn: !Ref MyEfsFileSystem
          LocalMountPath: /mnt/EFS
      Policies:
        - AWSLambdaExecute
        - Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Action:
                - s3:GetObject
                - s3:GetObjectACL
              Resource: 'arn:aws:s3:::my-bucket/*'
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /path
            Method: get

  Goodbye:
    Type: AWS::Serverless::Function
    Properties:
      <<: *FUNCTION_PROPERTIES         # This is the alias
      InlineCode: |
        def handler(event, context):
          print("Goodbye, world!")

Comment: > An error occurred (ValidationError) when calling the CreateStack operation: Template error: YAML aliases are not allowed in CloudFormation templates


Is there any open source load generators?

Question: I would like to know if there is any open source load generator for stress testing. I am using JMeter script to run the test. I know there is one called flood.io but think it is not free. Can you please recommend me some option and documentation on how to use it properly? Thanks!!
Answer: Well, JMeter is open source, you can observe source repositories so it matches your needs.
The point is where to run JMeter so you need to have your own bare metal machines (or normal desktop/laptop/virtual machine). If you're looking for an open-source operating system there is a wide range of free and open source Linux distributions, FreeBSD, illumos, etc.
If you don't have any machines and any money to invest into these machines there are some free cloud options like AWS Free Tier or Oracle Cloud Free Tier, also some SaaS service providers offer free pricing plans, for example BlazeMeter gives you 50 virtual users, LoadFocus gives you 20 concurrent users, etc.


host multiple websites in default website IIS 7.5 using application?

Question: Can I host different host address web sites on port 80 in default website in IIS 7.5 by creating applications ? Or Do I need to create separate websites in IIS with port 80?
Any good documentation, please provide me. I need to host www.WebsiteA.com and www.WebsiteB.com on port 80. I was in the impression of  using single website host different websites.
Comment: you mean virtual directory or applications?
Comment: Use virtual directories. For example, let's say you have two sites `A` and `B` that you want to both host on port 80. Put them both as virtual directories, then you can reach them at `http://server/A` and `http://server/B`
Comment: But I don't that urls. I need it like this www.siteA.com and www.siteB.com. Different host addresses.
Comment: In that case, host them as separate sites, configure DNS for `siteA.com` and `siteB.com` to both point to your server, and then configure each site with Host Header Values in IFS.
Comment: If you want the same content to be served for both siteA.com and siteB.com then simply have both of those added to the single site's [Host Header entries](http://technet.microsoft.com/en-us/library/cc753195(v=ws.10).aspx) and it will respond to either. Otherwise, you want 2 separate sites in IIS named accordingly with matching bindings/hostnames to serve independent content.
Answer: If you want them to look like this: www.WebsiteA.com and www.WebsiteB.com
Then you have to create different websites.
Different applications are used in case you have the same host header and want your url be like: www.WebsiteA.com/app1 and www.WebsiteA.com/app2
Here are some technet links that can give you more insight
Add a binding to a site IIS 7
http://technet.microsoft.com/en-us/library/cc731692(v=ws.10).aspx
Configure a Host Header for a Web Site (IIS 7)
http://technet.microsoft.com/en-us/library/cc753195(v=ws.10).aspx
Managing Sites in IIS 7
http://technet.microsoft.com/en-us/library/cc771341(v=ws.10).aspx


Platform.runLater, too slow for processing large amount of tasks

Question: public class ReadFromQueue
 {
     order = orderFromQueue;

     if(!Repository.ordersIdMap.containsKey(order.orderID))
     {

         Platform.runLater(new Runnable()
         {
            @Override public void run()
            {
                Repository.ordersCollection.add(order);
            }
         }
      });
      Repository.ordersIdMap.put(order.orderID, order);
  }

So hi again, I made another question, cause the previous one.. was bad (sorry)
Let me put you in this scenario. You have a reader that goes to a queue and gets an order (lets say its a order object, ready to use), this thing work so quick that gets a lot of orders per second.. (To be exact i get 40.000 orders in less than a minute).. I have a Repository that is a singleton class, in this class i have a ordersIdMap (ConcurrentHashMap of key String and value Order) and a ordersCollection that is a ObservableList (the source of my tableView). I CAN'T add the order if already exist in the collection so in my map i save the orderId (string) as the key, so that way if the same order cames again i must update it (the else code is not here but is not importan now). The thing is that calling the Platform.runLater for drawing to the UI is giving me problems.. why? cause if i go to get another order and the Platform.runLater hasn't finished.. the order doesn't get created on the map, so to my "reader" the order its new and create it again (in the case that the order has the same orderId), so i get the same order over and over again.. I must say that some times its quick enough and the order gets the update .. but most of the times is too slow and the order its created again. I also tried to put the "Repository.ordersIdMap.put(order.orderID, order);" right next to the if condition.. so that way the map will have the key no matter what..BUT still doesn't work (why..? dunno).. Also if i dont use the platform.runlater ..its works but i get a lot NullPointersException.. cause im trying to update the UI to quick..i think.. any answer is usefull!!.. THANKS! and sorry for my english.
EDIT: This is the entire code.. the execRpt is a like a "small order" and from that i can create a bigger order.. i receive many execRpt and then create the orders.. if the order exist update..if not add it, but it fails on updating (some times) and just add the order like if it was a new one.
package com.larrainvial.trading.trademonitor.listeners;

import com.larrainvial.trading.emp.Controller;
import com.larrainvial.trading.trademonitor.Repository;
import com.larrainvial.trading.emp.Event;
import com.larrainvial.trading.emp.Listener;
import com.larrainvial.trading.fix44.events.ReceivedExecutionReportEvent;
import com.larrainvial.trading.trademonitor.events.CalculatePositionsEvent;
import com.larrainvial.trading.trademonitor.vo.ExecRptVo;
import com.larrainvial.trading.trademonitor.vo.OrderVo;
import javafx.application.Platform;
import javafx.concurrent.Task;
import quickfix.FieldNotFound;
import quickfix.fix44.ExecutionReport;

public class ReceivedExecutionReportToMonitorListener implements Listener
{
    private OrderVo orderVo;
    private String ordStatus = "";
    private String transactTime = "";
    private String text = "";
    private int qty = 0;
    private int cumQty = 0;
    private int lastQty = 0;
    private int leavesQty = 0;
    private double price = 0;
    private double avgPx = 0;
    private double lastPx = 0;

    @Override
    public void eventOccurred(Event event)
    {
        ExecutionReport executionReport = ((ReceivedExecutionReportEvent)event).message;
        try
        {
            String settlType = "";
            String orderID = executionReport.isSetOrderID()? String.valueOf(executionReport.getOrderID().getValue()) : "";
            String execID = executionReport.isSetExecID()? String.valueOf(executionReport.getExecID().getValue()) : "";
            String execType = executionReport.isSetExecType()? String.valueOf(executionReport.getExecType().getValue()) : "";
            String clOrdID = executionReport.isSetClOrdID()? String.valueOf(executionReport.getClOrdID().getValue()) : "";
            String clOrdLinkID = executionReport.isSetClOrdLinkID()? String.valueOf(executionReport.getClOrdLinkID().getValue()) : "";
            transactTime = executionReport.isSetTransactTime() ? String.valueOf(executionReport.getTransactTime().getValue()) : "";
            text = executionReport.isSetText() ? executionReport.getText().getValue().toString() : "";
            String tif = executionReport.isSetTimeInForce() ? String.valueOf(executionReport.getTimeInForce().getValue()) : "";
            String handlInst = executionReport.isSetHandlInst() ? String.valueOf(executionReport.getHandlInst().getValue()) : "";
            String securityExchange = executionReport.isSetSecurityExchange()? String.valueOf(executionReport.getSecurityExchange().getValue()) : "";
            String orderType = executionReport.isSetOrdType()? String.valueOf(executionReport.getOrdType().getValue()) : "";
            String account = executionReport.isSetAccount() ? String.valueOf(executionReport.getAccount().getValue()) : "None";
            ordStatus = String.valueOf(executionReport.getOrdStatus().getValue());
            lastPx = executionReport.isSetLastPx()? executionReport.getLastPx().getValue() : 0;
            price = executionReport.isSetPrice()? executionReport.getPrice().getValue() : 0;
            avgPx = executionReport.isSetAvgPx()? executionReport.getAvgPx().getValue() : 0;
            lastQty = executionReport.isSetLastQty()? (int)executionReport.getLastQty().getValue() : 0;
            leavesQty = executionReport.isSetLeavesQty()? (int)executionReport.getLeavesQty().getValue() : 0;
            cumQty = executionReport.isSetCumQty()? (int)executionReport.getCumQty().getValue() : 0;
            qty = executionReport.isSetOrderQty()? (int)executionReport.getOrderQty().getValue() : 0;

            ExecRptVo execRpt =  new ExecRptVo(orderID,
                                          execID,
                                          execType,
                                          ordStatus,
                                          clOrdID,
                                          clOrdLinkID,
                                          securityExchange,
                                          String.valueOf(executionReport.getSide().getValue()),
                                          qty,
                                          lastQty,
                                          leavesQty,
                                          cumQty,
                                          executionReport.getSymbol().getValue().toString(),
                                          orderType,
                                          price,
                                          lastPx,
                                          avgPx,
                                          tif,
                                          "",
                                          handlInst,
                                          securityExchange,
                                          settlType,
                                          account,
                                          text,
                                          transactTime);

            orderVo = new OrderVo(execRpt);
            OrderVo orderExist = Repository.ordersIdMap.putIfAbsent(orderID, orderVo);

            if(orderExist == null)
            {
                Platform.runLater(new Runnable()
                {
                    @Override public void run()
                    {
                        Repository.ordersCollection.add(orderVo);
                    }
                });
            }
            else
            {
                Repository.ordersIdMap.get(orderID).price.set(price);
                Repository.ordersIdMap.get(orderID).qty.set(qty);
                Repository.ordersIdMap.get(orderID).ordStatus.set(ordStatus);
                Repository.ordersIdMap.get(orderID).transactTime.set(transactTime);
                Repository.ordersIdMap.get(orderID).text.set(text);

                if(avgPx > 0)
                    Repository.ordersIdMap.get(orderID).avgPx.set(avgPx);
                if(cumQty > 0)
                    Repository.ordersIdMap.get(orderID).cumQty.set(cumQty);
                if(lastQty > 0)
                    Repository.ordersIdMap.get(orderID).lastQty.set(lastQty);
                if(lastPx > 0)
                    Repository.ordersIdMap.get(orderID).lastPx.set(lastPx);
                if(leavesQty > 0)
                    Repository.ordersIdMap.get(orderID).leavesQty.set(leavesQty);
                if(ordStatus.equals("8"))
                    Repository.ordersIdMap.get(orderID).rejected.set("1");

                Repository.ordersIdMap.get(orderID).execRpts.add(execRpt);
            }
            if(execType.equals("1") || execType.equals("2") || execType.equals("F"))
            {
                CalculatePositionsEvent calculatePositionsEvent = new CalculatePositionsEvent(execRpt);
                Controller.dispatchEvent(calculatePositionsEvent);
            }
        }
        catch (FieldNotFound ex)
        {
            ex.printStackTrace();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

Comment: Your English seems fine, but I still can't understand what you're asking.
Comment: Questions like this make me wish for the too specific close classification.
Comment: Its hard to explain.. but the main problem about this.. is that i cant repeat orders on the ordersCollection.. but the if condition its not working always.. some times the orderId key doesnt exist (when it should exist) in the hashMap and it's weird ..cause the code i think is ok.
Answer: One problem in your code is that you have a check-then-act pattern which is not atomic. One workaround would be something like:
order = orderFromQueue;
Order alreadyInMap = Repository.ordersIdMap.putIfAbsent(order.orderID, order);

if(alreadyInMap == null) { //it really is a new order
    Platform.runLater(new Runnable() {
        @Override public void run() {
            Repository.ordersCollection.add(order);
        }
    });
}

Also note that "cause if i go to get another order and the Platform.runLater hasn't finished.. the order doesn't get created on the map" does not make sense: when you call Platform.runLater(), the runnable is put in a queue but is executed asynchronously (unless your method already runs on the FX Thread).
Comment: I like assylias' example, there is an executable sample based on this pattern, in the [ItemProcessor class here](http://codetidy.com/6574) that was created for a somewhat similar StackOverflow question on [complex JavaFX concurrency patterns](http://stackoverflow.com/questions/18530493/complex-concurrency-in-javafx-using-observablelists-and-properties-from-multipl).
Comment: Hello to both of you and thank you for the answer. I tried this, but still doesn't work, why?, i don't know how it happens but some times the "alreadyInmap" returns null when the order already exists.. how can this happen? i really don't get it.. cause i already added the order in the "putIfAbsent" method.. i don't have an explanation for this, i just don't get it, cause it seems imposible to fail, but it does, i wanna cry..
Comment: `alreadyInMap` will always be null if the order already exists. Can you clarify what "doesn't work"?
Comment: I edited my question and put the entire code. What "doesn't work?" the "else" part.. cause instead of updating, it creates a new one, i just cant understand how can this posible happend..
Comment: @GabrielFigoxVargasFierro One issue is that your list of `Repository.ordersIdMap.get(orderID).xxx.set()` in the else block is not atomic - so if you receive two orders with the same id at the same time, they will set things in random order and `Repository.ordersIdMap.get(orderID)` will be a mix of two (or more) orders. Also, I don't know how `OrderVo` is implemented, but unless the setters (as in `avg.set()`) are not properly synchronized, you have no guarantee that the changes will be visible by other threads. Overall there seem to be quite a few concurrency issues in your code.
Comment: But once an order with a given orderId is inserted in your map, no other order with the same id will replace it.
Comment: @assylias: Thank you for all your help!. The "else" doesn't matter to me right now, i will check that anyway. I just made another test with exact code, but not using the Platform.runLater, and it works, but throws me an error in the output console, doesnt really matter to me right now cause it works.. so i can see that the problem is the Platform.runLater, i think that if i want to use that i will have to us the synchronized method in some way.. to fix this problem. Im gonna start investigating about it
Comment: Still can't fix this..The only thing i know is that the Platform.runLater its giving me problems.. cause if i dont use it..it works perfect! but throws me exceptions..
Comment: @GabrielFigoxVargasFierro Not sure if it is related, but if the Runnable you submit to Plaftorm.runLater throws an exception, the exception is "swallowed" (otherwise it would stop the whole JavaFX Thread). See also: http://stackoverflow.com/a/12798390/829571.
Comment: I MADEEEEEEEEEEEEE IT!!!!! using synchronized, a object and a boolean.. if u want that code i can answer to myself on my own question..lol, Thank you! i can go out and celebrate now!


Necessity of compactness in Dini's theorem

Question: In Rudin there's an example given to support the necessity of compactness
$$f_n(x)=\frac1{1+nx}\ x\in(0,1),$$
which is not uniformly convergent.
My question is if the interval would have been compact i.e. if $x\in[0,1]$
then would $f_n$ be uniformly convergent in the closed interval?
Plz help me with a proper explanation.
Comment: The limit function is not continuous in that case.
Comment: @Thorgott Then for x€[0,1] its also not uniformly convergent then how is the necessity of compactness for dinis theorem is supported by this example when x€(0,1)?
Answer: Let
\begin{equation*}f_n(x)=\frac{1}{1+nx},\ x\in[0,1].\end{equation*}
The limit function clearly is
\begin{equation*}f(x)=\begin{cases}1&,\text{ if }x=0,\\0&,\text{ if }0<x\le1.\end{cases}.\end{equation*}
So, in this extended case, the limit function of this sequence of continuous functions is itself not continuous. Hence, Dini's Theorem says nothing and it is easy to see that the convergence is still not uniform. This might seem unsatisfying, but it is actually completely natural.
If $f_n$ is any monotone sequence of continuous functions that converges pointwise on an open interval $(a,b)$ to a continuous function $f$, but not uniformly (that is, a sequence that is an example to support the necessity of compactness similar to the one Rudin gives) and $\tilde{f_n}$ are continuous extensions of $f_n$ to $[a,b]$ converging pointwise to a function $\tilde{f}$, then the $\tilde{f_n}$ are still monotone and hence $\tilde{f}$ must be discontinuous, for otherwise the convergence on $[a,b]$ would be uniform by Dini's Theorem and hence it's restriction to $(a,b)$ would be uniform contrary to our hypothesis.
The example is still very much a proper one to showcase why the compactness assumption is necessary, because it meets all the other assumptions, yet the conclusion fails. In fact, you can precisely trace back the gap between the theorem and the counter-example in $(0,1)$ by looking at the proof. Rudin constructs a decreasing sequence of compact sets $K_n$ and then uses a well-known theorem on the intersection of such sequences to conclude that this sequence must be eventually empty, which is equivalent to the desired result. For the particular $f_n$ in the example, it is easy to see that
$$K_n=(0,1)\cap\left(0,\frac{1-\varepsilon}{\varepsilon n}\right].$$
For reasonably small $\varepsilon$, these are all non-empty, but their intersection is empty, so the reasoning doesn't hold. If you extend this $f_n$ to $[0,1]$, you will see that the $K_n$ are still the same except for possibly containing the point $1$, but the same observations apply. In particular, note that $0\not\in K_n$ corresponds to $f$ having a discontinuity at $0$.


Diferença entre void e void*

Question: Qual a diferença entre o void* e o void como tipo de retorno de uma função?
Exemplo 1:
void *func_nome(int param){
      ...
  }

Exemplo 2:
void func_nome(int param){
      ...
  }

Comment: @LuizVieira deu pra entender o que é (void *) mas e o (void) ? e em relação a ser uma função, e não uma váriavel
Comment: Vc quer dizer em relação "ao retorno" de uma função (funções recebem 0 ou mais valores e retornam um valor). Seja como retorno ou como parâmetro, o tipo dos valores envolvidos precisam ser definidos. E aí se encontra a distinção, que já está explicada na outra pergunta. É que não estava claro que você também não sabia o que o `void` sozinho significa. Considerando isso, eu tirei o meu voto pra fechar.
Comment: Encontrei a resposta em http://pt.stackoverflow.com/questions/97138/qual-%c3%a9-a-finalidade-do-void-em-c
Answer: Ao se declarar uma função em C, C++ (e outras linguagens derivadas, como Java e C#) é sempre necessário declarar o tipo de retorno da função. void é um tipo especial para indicar que a função não retorna nenhum valor. Significa literalmente "nada". É o que algumas outras linguagens (como Pascal) definiriam como um procedimento (procedure).
Qualquer tipo* indica um ponteiro para aquele tipo. Por exemplo: int* é um ponteiro para inteiro e char* é um ponteiro para caractere. Mas void* não é um ponteiro para "nada". Trata-se de um caso especial. Ele indica um ponteiro para qualquer tipo, como se fosse um coringa. É usando quando não se sabe qual o tipo de dado está sendo apontado. É utilizado, por exemplo, como retorno da função malloc, porque a memória que ela aloca pode ser utilizada para qualquer tipo de dado. Cabe ao programador depois fazer a coerção para o tipo pretendido.

Diferença entre void e void*


eCommerce : fields vs attributes?

Question: From the docs :

Products variations can have attributes and other kinds of fields. Going back to our t-shirt analogy from above, if our t-shirts come in sizes and colors, perhaps the product variation should have an image field so you can upload a picture of a small red shirt. These kinds of non-attribute fields are loaded dynamically when variations are chosen.

What is the difference of purpose and meaning of "non-attribute fields" AND attributes ?
How are they different and similar ?
Answer: The way I think about it is in terms of sku numbers (or manufacturing part number/catalog number.) If a single product is available in multiple sizes (1 mg, 50 mg, 1 gm), each one will have its own unique sku. Those sizes are the variation attributes. But then I may also want to add on a non-attribute field like an image or a packaging/shipping surcharge (for a larger size). That data is specific to the product variation but isn't related to the sku.
Using the t-shirt analogy, if both size and color are attributes, then you might have the following unique variations:

TS_SM_01: small, blue t-shirt
TS_MD_01: medium, blue t-shirt
TS_LG_01: large, blue t-shirt
TS_SM_02: small, red t-shirt
TS_LG_02: large, red t-shirt
TS_SM_03: small, green t-shirt
TS_MD_03: medium, green t-shirt
TS_LG_03: large, green t-shirt

If I add on a field for an image or a field for some sort of customization, those new "non-attribute" fields do not cause me to create a whole new set of product variation sku numbers.
Comment: I'd like to add that non-attribute fields such as an image (and the default price field) will update once a variation changes. So as soon as you change color, you can also change the image preview, price, etc. If you would place the image field on the product instead, it would also display, but not update once the selection changes.
Answer: Hey there :) I wrote the above documentation a year or two ago. I think your question has two parts:
1. What is an attribute?
In the simplest terms possible, an attribute is something that differentiates your products at the SKU level.
An attribute for Drupal 8 is actually an entity, like a product or a piece of content. It's a specialized entity that has a specialized form for creation and management because the majority of product variations on Drupal Commerce 1.x needed something like what we built for 2.x.
One of the use cases we wanted to meet was the ability to add fields to attributes. So color or size are often used to describe an attribute. A color might need a field for a photorealistic representation of the color and a hexadecimal field that describes the color within the RGB spectrum.
2. In terms of entity architecture, why would I choose to make a differentiator an attribute? And the opposite situation?
When creating product variations, you can choose to create any number of fields. Sometimes those fields are best off being attribute references. Using attribute references lets the add-to-cart form understand the nature of your products and can help give you a configurable product form. This lets you pick the color and size combinations instead of picking from a long list of products with both colors and sizes pointed out.
In the end, no one is forcing you to use the attributes to document the differentiators. If you want to create an integer field per SKU that defines the length of the fabric you're selling, that doesn't have to be an attribute, but it could be a part of the pricing. (final price could be length x price)

eCommerce : fields vs attributes?


Supremum of a finite power series

Question: I'm trying to prove that the supremum of $\sum a^{x_{i}}$ given $\sum x_{i} = c$ and where $c$ is a positive constant, $x_{i} \geq 0$, and $a \geq1$, is when $(x_i)$ are all zero except one which would be equal to $c$.
Any ideas would be much appreciated.
Answer: $x \mapsto a^x$ is a convex function since $a \ge 1$, so we can use Jensen's inequality to show that we can 'move points further apart while keeping their sum the same' to increase the total value of the function. We can look for a finite procedure to do this to an arbitrary starting set of points until it becomes the equality case we know. One way is to pick any 2 non-zero points and move them apart until one becomes zero. This is always possible because all the points are non-negative. We only need to repeat this at most $n-1$ times where $n$ is the number of points, and then we are done.
Comment: This technique is called "smoothing" and can be applied to many kinds of inequalities, although it is generally easier to use when the objective function is a sum of function values where the function has only one or two inflection points.

Supremum of a finite power series


Colinearity between treatment and independent variable

Question: When you are studying a moderation effect of a factor, say license choice z (that has two treatments - choosing an open license 1 or not 0), on the relationship between an independent variable x and outcome variable y. Is it expected that x and z are non-correlated.
Does the presence of collinearity between x and z raise concerns of endogeneity and prevent us from drawing conclusion for the interaction effect? If yes, is there any robustness test that can be used to improve the confidence in the model and results ?
I have tried my sincere best to answer this question and I have reached out since I have pretty much reached a dead-end. I appreciate any feedback and help.Thank you.
Comment: Why do you call gender a treatment rather then a factor?
Comment: Thank you for pointing it out. I am sorry about that. I have not given a close enough example. I have edited the question.
Answer: Definitely. As an example, say age is one of your dependents and this license factor is the treatment. Now hypothetically taking this to an extreme, if all open licenses correspond to people over the age of say 50 and all 0 licenses correspond to youth say under 20, then any meaningful conclusions on the treatment cannot be separated from the hypothesis that age is in fact the driving factor. If any independents are highly correlated it becomes more difficult to determine what's driving the dependent.
Generally no, it's more a problem with how the data was sampled if true independence did exist. You can try dropping one of the offending variables in order to reduce the standard errors, but this leads to questions like which independent to drop and could lead to specification errors which is arguably more dangerous than collinearity.
Comment: Thank you for your succinct answer. In the example of age given in your response, do you think matching on the attribute - `age`, and then calculating the ATE can help increase the confidence in the result ?


EC2 AMI, does it mean state or just the program files and OS?

Question: I was wondering if creating an EC2 AMI backup, which means taking a snapshot would just save the OS, along with its settings or say, if a program were running and during that I take an EC2 AMI snapshot. The next time I fireup the EC2, I would see the programming running again?
Thanks.
Answer: Running state is not kept in any kind of backup or AMI snapshot, although if you create a new AMI image based on your current running instance all the rest (config files included) will be kept.
Have a look at this awesome Alestic instructions in how to create a new AMI image based on a running instance: http://alestic.com/2009/06/ec2-ami-bundle


Writing image value to field_collection object

Question: I'm creating a field collection item  and saving it via entity_create, and it all works great as long as I don't have an image tied to it. As soon as I do, I get an error, and it looks like this in the watchdog table:
    a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:516:"SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'fid' cannot be null: INSERT INTO {file_usage} (fid, module, type, id, count) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array
(
    [:db_insert_placeholder_0] =>
    [:db_insert_placeholder_1] => file
    [:db_insert_placeholder_2] => field_collection_item
    [:db_insert_placeholder_3] => 50
    [:db_insert_placeholder_4] => 1
)
";s:9:"%function";s:16:"file_usage_add()";s:5:"%file";s:43:"C:\xampp\htdocs\mysite\includes\file.inc";s:5:"%line";i:663;s:14:"severity_level";i:3;}

My code looks like this:
$values = array(
    'field_name' => 'field_bp_images',
    'field_bp_image_title' => array( LANGUAGE_NONE => array(array('value' => $title)), ),
    'field_bp_image_file' => array( LANGUAGE_NONE => array(array('value' => $fid)), ),
    'field_bp_image_photographer_name' => array( LANGUAGE_NONE => array(array('value' => $photographer)), ),
    'field_bp_image_photo_flag' => array( LANGUAGE_NONE => array(array('value' => $is_photo)), ),
  );
}

$field_collection_item  = entity_create('field_collection_item', $values);
#Attach to the node
$field_collection_item->setHostEntity('node', $node);

// # Save field-collection item.
$field_collection_item->save();

My $fid is definitely populated, but I am still getting that error telling me my fid cannot be null. I'm guessing I need to provide more elements to the array, but not sure what keys to give, or how many. Any thoughts?
Answer: The column name for an image field is fid (not value), so you just need to change this bit of your $values array:
'field_bp_image_file' => array( LANGUAGE_NONE => array(array('fid' => $fid)), ),

Comment: Clive, Thanks once again, that seems to have helped, once. I was updating only one record. Subsequent tries with several records produced errors such as these:
  "Warning: Illegal string offset 'field' in DatabaseCondition->__clone() (line 1895 of C:\xampp\htdocs\LLIS-NPAD\includes\database\query.inc)."
  and
"Recoverable fatal error: Object of class stdClass could not be converted to string". I'm unsure how to troubleshoot this, so I appreciate additional thoughts.
Comment: Clive, I'm still struggling with this. Any chance you can advice on how to find out what an image field expects? Just passing it the fid doesn't seem to be enough
Comment: Looks like I just needed to set the image up like this:      'field_bp_image_file' => array( LANGUAGE_NONE => array(array('fid' => $fid,'display'=>1,'description'=>'' )), ). Now to figure out which properties are required by word and other files, I can get this thing dones!


get 8 digit unique value when sequence of 7 positive integers given as input

Question: Consider a random sequence of numbers, like 1, 4, 15, 21, 27, 15... There are no constraints on what numbers may appear in the sequence and the sequence consist of 7 positive integers and each integer range from 0 to 255.The question is, do we have a function that will give unique output by performing mathematical operations on this sequence? By unique, I mean when the function is applied on sequence A, it must output a value that's different from the output obtained by applying the same function on any other sequence (or the same sequence but numbers placed in different order) in the world.and i need the output in 8 digits only.thanks
Comment: Very confusing. You write, "There are no constraints on what numbers may appear in the sequence," but then you proceed to give two constraints on what numbers may appear in the sequence, namely, "the sequence consist[s] of 7 positive integers" and "each integer range from 0 to 255." Moreover, the second constraint seems to allow zero, while the first constraint forbids it, as zero isn't positive. No matter; under any reasonable interpretation of what you want, Robert has shown you can't have it.
Comment: Actually sir i have an application that work like it take 7 inputs from user in range of 0-255 and generate an 8 digit number. and sorry im correcting my question the sequence produce single output regardless of order of elements i-e {1,2,3,....} should generate same result as {3,2,1..} or {1,3,2...}
Comment: Even so, the number of 7-element subsets of $\{\,1,2,\dots,255\,\}$ is the binomial coefficient 255-choose-7. If that's bigger than the number of 8-digit numbers (which is either $10^8$ or $9\times10^7$, depending on interpretation), then no can do.
Comment: So are you OK with what's been posted as comments and answer now?
Comment: Earth to Tehseen, come in, please.
Answer: Hint: ${}{}{}{}$
$$256^7 > 10^8$$
Comment: kindly explain it
Comment: There are more possible inputs than possible outputs.
Comment: so we can't get the output in 8 digits?
Comment: i have tried the continued fraction but that give ma a very big number.
Comment: Look up the pigeonhole principle.


Avoiding callback hell with async, using functions from other modules

Question: I have a user module where I am defining functions to be used across the code.  When I am creating a password I would like to utilize these functions:
User Module:
<code>//insert a local user into the database
User.prototype.insertLocalUser = function (email, password, cb) {

  var sql = "INSERT INTO VCUSER ( VCUSER_EMAIL, VCUSER_PASSWORD ) values ('" + email
    + "','" + password + "')";

  db.get().query(sql, function (err, rows) {
    if (err) return cb(err);

    return cb(err, rows);
  });
};

//generate hash function for password
User.prototype.generateHash = function (password, cb) {

  bcrypt.genSalt(10, function(err, salt) {
    if (err) return cb(err);

    bcrypt.hash(password, salt, null, function(err, hash) {
      return cb(err, hash);
    });
  });
};
</code>
Passport.js:
Here is where I am doing so,  granted this isn't too bad but I am currently stuck on trying to understand how to fix a simple nested callback issue with async and I don't want to move forward with a much more complex callback nest.
<code>//minor callback hell
      user.findByEmail(email, function (err, rows) {
        if (err) return done(err);

        if (rows.length) { //user must already exist prompt user
          return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
        } else {

          user.generateHash(password, function (err, hash) {
            if (err) return done(err);

            //insert a user with the newly hashed password into the database
            user.insertLocalUser(email, hash, function (err, rows) {
              if (err) return done(err);

              user.VCUSER_USERID = rows.insertId;

              //return the user we are done, they should be serialized and redirected
              return done(null, user);
            });
          });
        }
      });
</code>
I am trying to do something like this:
<code>//first search to see if the user already exists
  user.findByEmail(email, function (err, rows) {
    if (err) return done(err);

    if (rows.length) { //user must already exist prompt user
      return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
    } else {
      async.series([
        //code avoid callback hell here
        user.generateHash... {

        }

        user.insertLocalUser() {

        }
      ]);
    }
  });
</code>
I have looked at quite a few examples but I cannot seem to find something where someone is calling an outside modules code inside async.
Comment: Promises. Just use promises.
Comment: I second the sound advice from @Bergi, and I recommend avoiding SQL injection by parameterizing your query (e.g. use a prepared statement).
Comment: I have been dancing around promises, @Bergi I will attempt this. I still can't find any good examples of using a promise when calling another modules functions.
Answer: I will be looking into promises thanks to @Bergi's feedback.  Regardless if anyone is looking to do this here was my solution.  I highly recommend reviewing the async waterfall documentation it was some of the better material I have found.
<code>async.waterfall([
    //look in database for existing users with email inputed return as results
    function findUser(cb) {
      var sql = "SELECT * FROM VCUSER WHERE VCUSER_EMAIL = '" + email + "'";

      db.get().query(sql, function (err, result) {
        if (err) { cb(err); }

        cb(null, result);
      });
    },
    //check if there were any results, if so prompt, if not continue with user creation
    function generateHash(result, cb) {
      if (result.length) { return done(null); } //TODO determine how this is handled back to UI

      bcrypt.genSalt(10, function(err, salt) {
        if (err) { cb(err); }

        bcrypt.hash(password, salt, null, function(err, hash) {
          cb(null, hash);
        });
      });
    },
    //using recently generated hash create a user
    function insertNewUser(hash, cb) {
      var sql = "INSERT INTO VCUSER ( VCUSER_FIRSTNAME, VCUSER_LASTNAME, VCUSER_EMAIL, VCUSER_PASSWORD ) " +
        "values ('" + req.body.firstName + "','" + req.body.lastName + "','" + email + "','" + hash + "')";

      db.get().query(sql, function (err, rows) {
        if (err) { cb(err); }

        cb(null, rows);
      });
    }
  ], function (err, rows) {
    if (err) { return done(err); }
    else {
      user.VCUSER_USERID = rows.insertId;
      return done(null, user)
    }
  });
})
</code>


Upper bound of $\left(1+\dfrac{1}{2}\right)\left(1+\dfrac{1}{4}\right)...\left(1+\dfrac{1}{2^n}\right)$

Question: In a calculus book that I'm reading, there is a problem as follows:

Prove that this sequence $x_n=\left(1+\dfrac{1}{2}\right)\left(1+\dfrac{1}{4}\right)...\left(1+\dfrac{1}{2^n}\right)$ is monotonic, bounded and then converges.

I can prove that this sequence is increasing, but I found no way to find the upper bound for $x_n$.
Please give me some hint to find the upper bound, and may be the limit of this sequence also.
Thanks
Comment: Equivalently to Axel's anwer, you can use $1+x \le e^x$.
Comment: Also: https://math.stackexchange.com/q/1118666 – these and more similar questions can be found with [Approach0](https://approach0.xyz/search/?q=OR%20content%3A%24x_n%3D%5Cleft(1%2B%5Cdfrac%7B1%7D%7B2%7D%5Cright)%5Cleft(1%2B%5Cdfrac%7B1%7D%7B4%7D%5Cright)...%5Cleft(1%2B%5Cdfrac%7B1%7D%7B2%5En%7D%5Cright)%24)
Comment: Another one: https://math.stackexchange.com/q/1005763.
Comment: @anonimo Try to look at the right part of your post there are related post. If you do not find something then try to use the site suggested by MartinR.
Comment: How can you find out those link? I tried to search before posting this question, but I found nothing then I posted it.
Answer: Let,
$$u_n = \prod_{i=1}^n \left( 1+ \dfrac{1}{2^i}\right)$$
Hint:
Calculate $\ln(u_n)$ and use that $\ln(1+x) \leq x$ for all $x$.
Once you've shown that $(u_n)_n$ is bounded, as $(u_n)_n$ is an increasing sequence it follows that $u_n$ converges by the monotone convergence theorem.
Comment: You're welcome. Well it was not resquested in your problem. I will have to think about it, but it seems to be a much harder problem.
Comment: Yes me neither, it is rather simple to check that it converges. Yes I saw that :) but I meant it was not a question of your calculus book. If I ever find something I'll let you know.
Comment: You might take a look at this [answer](https://math.stackexchange.com/a/1119220/745510) that does not involve logarithms
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/126829/discussion-between-axel-and-anonimo).
Comment: Thank you. Can we calculate the limit Axel?
Comment: I think so, when I first look at this product, I found no intuition to imagine about its limit. Btw, I have requested in my question  :) (..."may be the limit of this sequence also.")
Comment: Just some more personal thought on this problem: It appears in the problem section after the lesson of monotonic sequences in the 1st chapter of convergence of sequences. The student is supposed not to know anything about the derivative (to prove that ln(1+x)<x, or the convergence to e of (1+1/n)^n. I see no reason for the authors to put this problem there, unless there is a more elementary solution?
Answer: Using GM-AM you get
$$\prod_{k=1}^n \left(1+\frac 1{2^k}\right)< \left(\frac{n+1}{n}\right)^n < e$$
Comment: The product is the so-called Pochhammer function
$$\frac{1}{2} \left(-1;\frac{1}{2}\right)_{n+1}$$


dense sets and which of the following are true??

Question: Which of the following statements are true??
a. If $A \subset Q$ such that $Q-A$ is finite then $A$ is dense in $R$.
b. There exists $A\subset Q$ such that $Q-A$ is infinite and $A$ is dense in $R$.
c. There exists a pair of disjoint subsets of $Q$ such that both of them are dense in $R$.
d. None of the above is a true statement.
Comment: @tattwamasi amrutam can you please contact on my email (in profile description) , i am preparing for iit jam this time (exam in feb) , hope you can help .thanks
Answer: a,b,c are all true, and so d is false.
b. We can take A to be the complement in $\mathbb{Q}$ of $\mathbb{Z}$.
c. We can take the elements of $\mathbb{Q}$ with even numerator and the complement (elements with odd numerator). These subsets are sense in $\mathbb Q$ and hence in $\Bbb R$.
Comment: @VikrantDesai Thanks, I edited.
Comment: In c., how can we take complement of $\Bbb Q$? We need two disjoint subsets of $\Bbb Q$ that are dense in $\Bbb R$.


how to represent REST API URL for update the number of likes of some post

Question: I am studying REST API.
I'm thinking about how to design the REST API for the following situations.
"If you click the Like button on a post, increase the number of likes on that post."
This corresponds to an UPDATE among CRUD. Right?
Then should I express the URL like this?
POST /post/{post_id}/likes

But there also will be situations like this.
If you press the "Like" button again, Decrease the likes again.'
In that case, would it be appropriate to send a request with this data in the payload?
POST /post/{post_id}/likes

{
countup: False // decrease likes
}

I coudn't think of anything better than this,
but I feel strange that this isn't a very good idea.
I want to design the API to match the convention.
I'd appreciate it if you could give me some better ideas.
Comment: In general, REST is just like using the regular Web but instead of humans interacting with those "pages" (a.k.a. resources) applications are doing it. How you design the interaction doesn't differ much from how you'd design the interaction on the human Web. Your outlined approach doesn't violate any HTTP standards nor REST constraints. As such it may be a viable solution. Keep in mind though that REST is more than just a simple CRUD Web-API. As a starting source I'd recommend to watch [this YT video](https://www.youtube.com/watch?v=aQVSzMV8DWc) by Jim Webber
Answer:
If you click the Like button on a post, increase the number of likes
on that post. If you press the "Like" button again, Decrease the likes
again.

Pressing the like button and adding a toggle is an UI thing.

on a post increase the number of likes or decrease the likes

If it would be operations I would do increaseLikesForPost(), decreaseLikesForPost(). What is hidden here that we usually add the session.userid as a parameter to know which user like the post later, not just increasing the number of like, so what really happens here is increaseLikesForPost(actualUser), which does not make much sense in this context. It would be normally just actualUser.like(post) or post.isLikedBy(actualUser). Since we use the API from the viewpoint of the post it is better to use the latter one.
So how do we translate this: post.isLikedBy(actualUser) or this: postIsLikedBy(post, actualUser) to the language of HTTP methods and an URIs?
A possible solution is POST|PUT /api/posts/:postid/likes/:actualuserid and DELETE /api/posts/:postid/likes/:actualuserid. If you don't want to add session related data to the URIs like actualuserid, then it is better to do POST|PUT /api/posts/:postid/like and DELETE /api/posts/:postid/like and get the actualuserid from the Authorzation header.


Programmatically rendering a Views pane with arguments from context

Question: I'm trying to programmatically render a Views pane (ie. a Pane display of a view) with a taxonomy term as argument (passed in the pane context)
The following code illustrate how the pane is rendered
$selected_type = 'views_panes';
$selected_subtype = 'persona_display-panel_pane_1';
$context = array(
  'context_taxonomy_term_1' => ctools_context_create('entity:taxonomy_term', $fully_loaded_taxonomy_term);
);
ctools_content_render($selected_type, $selected_subtype, array(), array(), array(), $context);

It mostly works and the view is rendered. However, the taxonomy term in the context is not used as argument for the view.
In the pane views display's settings, the "Argument input" for the one views' argument is configured as "Term ID" "From context":

I looked at the code for the view display handler. Arguments handling is done in views_content_plugin_display_panel_pane::pane_process_conf(). I checked there and the issues seems to be that $conf['context'] is not set. So $context_keys ends up being an empty array. Later in the switch statement, $key = array_shift($context_keys) sets $key to NULL, the isset($contexts[$key]) test fails and the $argument is ignored.
I have no idea if this is a bug with Views pane, or if something is missing in the pane rendering code.
Note: I'm actually using a Pane Field field in a Paragraphs bundle.
Comment: Note that this has been cross-posted as a support request in CTools' issues queue at https://www.drupal.org/node/2827763
Comment: Perhaps, if I understood this correctly, a work around, you could set the view contextual filter to `Get taxonomy term ID from url`. This way you do not have to pass any term ID programmatically.
Comment: That does not work neither.
Answer: I got it to work with
$selected_type = 'views_panes';
$selected_subtype = 'persona_display-panel_pane_1';
$context = array(
  'context_taxonomy_term_1' => ctools_context_create('entity:taxonomy_term', $fully_loaded_taxonomy_term);
);
$config = array(
  'context' => array('context_taxonomy_term_1');
);
ctools_content_render($selected_type, $selected_subtype, $config, array(), array(), $context);

So, in order to render a Views Pane display with contextual filters coming from the pane's context you to populate $context and inform the display handler on which entries of $context to use for each contextual filter with $config['context'].


Being deaf and still produce music, how is that possible

Question: Does anybody knows Sean Forbes? He is deaf, but produces music, like this. According to sources he can also play guitar and drums, how is this possible? Also check out the story of Patric Costello.
How is all this possible? Are they completely deaf, do they just feel the music (vibrating air) on their skin/stomach? Whats a meaning of a melody for them? Or of harmony?
Comment: Ask Ludwig, he did it.
Comment: There are rules of music theory can provide rules to follow. Also, there are people that become deaf that have internalized aural training well enough that they can still "hear" it.... still i would have to image it would be unsatifying to compose a piece and not hear it for real
Answer: He seems to wear a hearing aid, so he isn't profoundly deaf.  According to Wikipedia he's 90% deaf.  His parents bought him a drum set after noting him react to music on the radio.  (Just what the world needs, another deaf drummer :-)
Beethoven went deaf in later life.  Whether profoundly deaf or not, I don't know.
And there's this lady, who as well as having a successful musical career, seems to have thoroughly enjoyed her personal life!
https://en.wikipedia.org/wiki/Evelyn_Glennie
Comment: Isn't 'deaf drummer' tautologous?
Comment: @Dekkadeci - that 'Pardon.................' was probably because Laurence has worked with more than a few drummers...
Comment: Pardon?
.........................
Comment: @Dekkadeci - did it really need an explanation? It's a known and accepted fact that some drummers have their hearing affected by the volume they produce - and the viscious spiral of loudness that it often produces in some bands. Been there too often...
Comment: @Tim, given Laurence Payne's "Pardon?", I believed an explanation was warranted.
Comment: Tim jokingly means that drummers "strongly" tend to go deaf from inevitably playing too loudly too often.
Comment: The story of Evelyin is impressive too, but what I do not get: I saw this TED-Talk of her: https://www.youtube.com/watch?v=IU3V6zNER4g and in year way of speaking she does not sound like a deaf person, for example Sean also speaks in a way (if you hear interviews) that seems to be typical of deaf people...
Comment: According to [Wikipedia on Symphony No. 9](https://en.wikipedia.org/wiki/Symphony_No._9_(Beethoven)), Beethoven was almost totally deaf and couldn't hear the orchestra he "conducted"... and also the famous "still conducting while the symphony was already over"
Comment: Evelyn lost her hearing at age 12, Sean before age 1.  Hence the difference in speech I expect.
Answer: The musician's ear worm Audiation might be what you are looking for.  My brother in law can hear the music in his head solely by reading the score.  I'm trying to develop that skill.
Answer: If you go deaf early in life you can't understand true melody and harmony. You can feel vibrations, but that's not an acoustic experience. I don't know about the guys you mentioned, but let me explain a composer's case.
Beethoven (and Faure) went deaf later in his life. A composer learns the harmonic and melodic patterns and just knows how they sound in their head. When they read or write music they don't need to hear it - they know how it sounds.
Try it yourself with a reading book - read the words in your head, you can actually "hear" them since you already know what they sound like. You are familiar with the sounds produced by the combinations of letters. A good deaf composer can write music just as well as a deaf writer can write word-based works. Depends on how proficient you are with music, come up with a melody in your head (don't sing or play it), take a sheet of paper and write it down. That's it. Deafness doesn't hinder you that much once you have a good image of how music sound.
Players on the other hand can't play if they are completely deaf. There are many minute pitch and tempo corrections your brain does "automatically" (to some extent) by hearing the players around you, or even the previous note you played. Don't know about drummers, but I have a feeling even they need to listen to what's going on around them.
So: (experienced) composers - yes, conductors and players - no.
Comment: "If you go deaf early in life you can't understand true melody and harmony. You can feel vibrations, but that's not an acoustic experience." Actually, harmony simply is the relationships between vibrations of sound waves; so harmony is just feeling vibrations, like the 2:1 relationship between octaves. You can feel the music plenty without the assistance of your ears in a way that's not intuitive, but very real none the less.
Comment: So you're telling Evelyn Glennie that she can't do what she does do, user1803551
Comment: @LaurencePayne I wrote specifically that drummers are an exception, though I'm pretty sure it hurts them as well.
Comment: @SpiderShlong Both harmony and melody are just wave bundles, but feeling the vibrations with the body is not a substitute for the brain receiving them. Not practically, because you won't get the level of accuracy you need, and not neurologically.
Comment: User1803551 - I think that is entirely your opinion, and incorrect. There are those who say it is the same, and that in the brain it is the same. Have you got any references to support your assertion?
Comment: @DrMayhem Which part? Most of it is and has been the consensus and has everyday ample proof.


Change div value on input value change. Multiple changes on the same page

Question: I have multiple INPUTs with a save button each that should update other DIVs that contain the same ID in the id attribute. For the moment I can only change the value when I give the exact id with Jquery.
How can I change only the value that is on the same clicked parent div?
HTML

  <input type="text" id="newbud-2508891" value="10.00" required="" class="form-control border-0">
  SAVE

$10.00

  <input type="text" id="newbud-2508892" value="10.00" required="" class="form-control border-0">
  SAVE

$10.00

JQuery
function showMessage() {
    var message = jQuery("#newbud-2508891").val();
    jQuery("#bud-2508891").text(message);
}

JSFIDDLE
EDIT: How to have the same behavior for both parent DIV with the same JQuery code. For the moment I have to give the exact ID of the input and the result DIV in the code. Is there a way to have a code that doesn't require IDs and change both results DIV when the corresponding input is changed?
Comment: It's not immediately clear what your intended scenario is. Can you add some details to this to explain what you expect to happen? Thanks!
Comment: I have edited my question. Sorry for the confusion.
Comment: So if what I'm hearing you is correct, you want a helper function that changes the value of the input that is associated with the button that's clicked, correct? So you're looking for `this` element to be specified?
Comment: Exactly! But I'm not that knowledgeable when it's JQuery stuff.
Comment: Ok - So to clarify: You have a button that's updating *multiple* values? Or is one input linked to a single button? You can either tie them by class, or by id. class enables you do do .querySelectorAll("class") to get all of the things that match what you're looking for, and then `forEach()` over each of those elements.
Comment: It's one input linked to a single button that updates a single div
Answer: If you are using jQuery you do not need to use the onClick attribute on html tags. Further you can use selectors like [attribute^=value] to get elements which attributes begins with the given values.
Try something like this example:

$(document).ready(function() {

  $('*[id^="newbudbtn-"]').on('click', showMessage);

  function showMessage(event) {
    var elem = $(event.target);
    var id = elem.attr('id').replace('newbudbtn-', '');

    var source = $('#newbud-' + id)
    var target = $('#bud-' + id);

    if (source.length && target.length) {
      target.text('$' + source.val());
    }
  }

});

  <input type="text" id="newbud-2508891" value="10.00" required="" class="form-control border-0">
  SAVE

  <input type="text" id="newbud-2508892" value="10.00" required="" class="form-control border-0">
  SAVE

Comment: Thank you for your help, but your code doesn't seem to be working, Value doesn't change when the input value changes and the save button is clicked.
Comment: If I click on the save button the value of the input will be displayed in your "dropdown" -> "bud". If you change the value and click the save button again, it will still work. Do I misunderstood something?
Comment: Furthermore, you can use onClick events in HTML and pass `this` to access *where* click came from e.g. `onClick="myfunc(this)"`
Comment: I'm sorry but the code still doesn't work on my end, I changed the input value and clicked save and nothing happened. I will try your onClick="myfunc(this). This seems like a promising solution. Thank you
Comment: @CreekBarbara Do you run the snippet on my answer here on stackoverflow for testing?
Comment: I've tested the code on JSFIDDLER too with the same result.
Comment: @CreekBarbara I modified my answer a few seconds after posting. You don't get the latest Version - please try the current code. Additionally you do not need to insert the script tag in html while using jquery in the javascript window of jsfiddle :)
Comment: I'm happy that i could help you!
Answer: I think you'd be better served by using classes and then querying based on hierarchy.
Here is my example: Fiddle

function showMessage(e) {
 // We get the parent of the button that clicked it
 var node = e.parentNode;

  // Get initial value from sibling input
  var initialValue = node.querySelector("INPUT").value;

 // We query each of the elements in that container
  var elements = node.querySelectorAll(".text-change");
 elements.forEach( el =>
  {
   el.innerHTML = initialValue;
  });

}

  <input type="text" value="10.00" required="" class="form-control border-0 text-change">
  <button id="newbudbtn-2508891" class="btn btn-sm text-info bgbtb" style="color: white !important; background-color: #007bff;" onClick="showMessage(this)">SAVE</button>

$10.00

  <input type="text" id="newbud-2508892" value="10.00" required="" class="form-control border-0 text-change">
  <button id="newbudbtn-2508892" class="btn btn-sm text-info bgbtb" style="color: white !important; background-color: #007bff;" onClick="showMessage(this)">SAVE</button>

$10.00

Answer: you can listen to the event (target is the div you clicked on)
function showMessage(event)
{
    console.log(event.target)
}

Hope this helps.
Comment: Sorry, this is not what I was asking for. Thank you though.


Simulate a biased coin with a fair coin using a fixed number of tosses

Question: For which values of $p$ can you simulate a $p$-biased coin using a fair coin in a fixed number of tosses (the "reverse" direction of this problem)?
I have read of an approach where you consider the binary expansion of $p$, let's call it $0.b_1b_2b_3\dots$. Then, we toss the fair coin until it lands on heads. Let's say this took $n$ tosses. If $b_n=1$, then we map this to a heads for our $p$-biased coin, otherwise if $b_n=0$ we map this to a tails. This works because the probability of mapping to heads in our $p$-biased coin is simply
$$\sum_{i|b_i=1}\frac{1}{2^i}=0.b_1b_2b_3\dots=p$$
But this still gives an expected run time of $2$ flips. Is there an approach which takes a constant worst case number of flips? Or is the binary representation of $p$ in base 2 terminating a necessary condition for this to be the case? Any ideas are appreciated!
Comment: You might be interested in this paper: Szalkai and Velleman, Versatile Coins, Amer. Math. Monthly vol. 100 (1993), pp. 26-33.
Answer: By constant you mean nonrandom ? If there is a deterministic bound $n$ on the number of flips you need, then your coin is a random variable $X$ defined on $\{0,1\}^n$ and necessarily $p = P(X=1) = 2^{-n} \mathrm{Card}\{\omega \in \{0,1\}^n, X(\omega) = 1\}$ is a multiple of $2^{-n}$ so the binary representation terminates.
Regarding your randomized algorithm, when $p$ is non-dyadic it is optimal in expectation as explained by Lumbroso in appendix B of this paper https://arxiv.org/pdf/1304.1916.pdf (Lumbroso makes a small mistake : his computation does not work when $p$ is dyadic in which case you can stop the procedure after $2^{-n}$ steps for a small gain.
His optimality bound comes from the wonderful results of Knuth and Yao about the optimal generation of general discrete random variables from coin tosses (which they call DDG trees). I put the reference below, you can find it on libgen, it is a real gem and a great read. Lumbroso's paper also describes a neat optimal way do generate discrete uniform variables.
If you want many independent samples of your biased coin, you can get a performance boost up to $H(p) = p \log(1/p) + (1-p)\log(1/(1-p))$ expected bits per sample by reusing randomness from one sample to the next. https://arxiv.org/pdf/1502.02539.pdf $H(p)$ is the Shannon entropy of the distribution and is a hard lower bound. Lumbroso also does this in his paper for the discrete uniform case.

Knuth, Donald E.; Yao, Andrew C., The complexity of nonuniform random number generation, Algorithms and Complexity, Proc. Symp., Pittsburgh 1976, 357-428 (1976). ZBL0395.65004.


Any module which even comes close to frontpage slider module

Question: I saw this front page slider module, and I was impressed by it, but I see there is no Drupal 7 module and it is payed property now.
Is there any module which comes close to this one?
Comment: As WestieUK said, Views Slideshow is a great module to do this. We did a tutorial on how to do this, unfortunately its in spanish: http://rootstack.com/es/blog/sliders-flexibles-con-views-slideshow. Here's an example of what you're looking for, but with bigger dimensions: http://demos.rootstack.com/views-slideshow-demo-1.
Answer: Views Slideshow is incredibly configable and I am sure it will cater for that type of display. However is it not an off the shelf product like the wordpress example so dont expect to install it and it just work.
Instead like much of Drupal it is more like a construction box, complex but hugely powerful.
Comment: +1 for Views Slideshow. It's really amazing what you can do with it but as WestieUK mentions, it will involve some work. I am theming one right now for a new client site and was even able to make it responsive using the Adaptive Image module as well as having multiple languages work with it using Entity Translation.
Answer: WestieUK's answer is good. I used to use things like Views Slideshow and Views Carousel, but found them a bit too bloated (understandably so) and I wasn't able to configure everything I wanted. I've since just grabbed whatever JavaScript library I wanted to use (e.g. NivoSlider) and added the JavaScript files in my theme. You can even use the Views module to build the unordered list of items and then target that  with your jQuery selector that activates the slideshow.
This approach gives you a bit more control.
And, as WestieUK points out, much of Drupal is complex and hugely powerful. To really do things well, you can run your own SQL query in a little custom module to grab the nodes you want, the image style presets, etc., and display them in a render array for use with whatever slideshow library. This kind of thing gives you the leanest, fastest loading, and most customizable slideshow you can get.
Comment: Agreed, if you have the time to go the extra mile though :)


What cello technique used in titles of "The Night Of"

Question:

At the beginning of the title sequence of "The Night Of" the double bass is clearly plucked, but I'm not entirely sure about the higher cello part? Is it simply a (very) dry staccato? There's just so much - I don't know how to describe it - maybe texture (?), that I'm wondering if it's simply bowed?
Edit: just realised the bass is two double basses: one bowed, one plucked.
Edit: took an attempt to transcribe the music: https://musescore.com/user/24361621/scores/4810734
Answer: The bow is kind of dropped onto the string, and immediately removed, so it bounces.
Called spiccato, or brush stroke.
Comment: Thanks! So the pizzicato-ish sound underneath is part of the spiccato? Or do you think there's separate strings doing pizzicato as well?


Bernoulli differential equation

Question: I am considering the following elementary differential equation:
$$y'(x) = c y^2(x), \quad y(0)=x_0>0$$
for some given constant $c>0$. I consider this equation just for $x>0$, i.e. in the positive line.
This equation can be solved and the solution is given by
$$y(x) = \frac{1}{\frac{1}{x_0}-cx}, \quad x\in \mathbb{R}_+.$$
The intuition is that since $y'(x)$ is positive then $y$ must be increasing which it is... But I don't understand why it explodes at $x=\frac{1}{cx_0}$. What is the intuition behind? Why can't $y$ just be increasing and well-defined for all values $x>0$? and there is a single point singularity? I really can't see the intuition behind.
Any idea help comment on this?
Thanks!
Answer: As the function grows, so does the derivative. And the derivative grows at least constantly ($y^2 c \ge x_0^2 c$), so eventually $y$ will be larger than one. The function growth will be proportionate to the square of the function itself, and the square is larger than $y$ if $y > 1$. So as the function grows, the growth grows, and the function grows even faster, and this creates a vicious cycle culminating in the explosion.
EDIT: An intuition behind the point $z := 1/(x_0 c)$ is: The larger $x_0$ is, the quicker the process described above comes about, and the larger $c$ is, the quicker the process described above comes about.
For larger values than $z$ the function $y$ is negative. If it grows, $y^2$ shrinks. Thus, the growth of $y$ comes to a halt as soon as $y$ approaches the $x$-axis from below.
Comment: I see but then it goes well again for larger values even very big values of $x>>0$, it only explodes once.. and why at precisely $1/(cx_0)$.. I don't see the intuition of this point.
Comment: For larger values the function is negative. If it grows, $y^2$ shrinks. But on the precise point issue I've got to think a bit more.

Bernoulli differential equation


How can I print a field value in node.html.twig?

Question: I want to print a field value in node.html.twig. When I use {{ content.field_test }}, it prints the full HTML markup of the field.
How can I just print the field value?
Answer: While you can print the first value of the field without the surrounding div container with {{ content.field_test[0] }}, this is not a recommend way to do it.
The markup you want to change is in the field template. If you don't want for example any div's around the field field-test, then place a field template in the template folder of the theme:
field--field-test.html.twig:

  {%- for item in items -%}
    {{ item.content }}
  {%- endfor -%}

The benefit you get is that this outputs multi-value fields and that you keep the attributes of the field, which is important if you want the theme to work with core and third-party modules for client side functionality like, for example, quickedit.
Comment: I want use command directly .
Answer: This will help:
Twig Field Value :  It gives them more control over the output without drilling deep into the render array or using preprocess functions.