Proof of d'Ocagne's identity

Question: It's known that Fibonacci numbers satisfy the following relation:

$$F_mF_{n+1}-F_{m+1}F_n=(-1)^nF_{m-n}$$

Which is called d'Ocagne's identity.
This identity with the following identities are well-known:

$$F_{n-1}F_{n+1}-F_{n}^2=(-1)^n\tag{Cassini's identity}$$
$$F_{n}^2-F_{n-r}F_{n+r}=(-1)^{n-r}F_r^2\tag{Catalan's identity }$$
$$F_{n+i}F_{n+j}-F_{n}F_{n+i+j}=(-1)^{n}F_iF_j\tag{Vajda's identity }$$
$$F_{k−1}F_n + F_kF_{n+1} = F_{n+k} \tag{Honsberger identity}$$

Cassini's identity is a special case of Catalan's identity and can be derived with $r=1$.
The usual way for proving these identities is using $2×2$ matrix , another way would be induction,I know how to prove Catalan's identity using induction but still I have not seen any proof of d'Ocagne's identity,I'm asking if someone know a proof of that (induction preferred)?
Also is there any combinatorial poof for d'Ocagne's identity? if yes, so it would be really nice to see the proof.

My try:

Define:
$$a:=\frac{1+\sqrt{5}}{2}\;\;\;\;\;\;\text{and}\;\;\;\;\;\;\; b:=\frac{1-\sqrt{5}}{2}$$
Then using this follows:
$$F_mF_{n+1}-F_{m+1}F_n$$
$$=\left(\frac{a^{m}-b^{m}}{\sqrt{5}}\right)\left(\frac{a^{\left(n+1\right)}-b^{\left(n+1\right)}}{\sqrt{5}}\right)-\left(\frac{a^{\left(m+1\right)}-b^{\left(m+1\right)}}{\sqrt{5}}\right)\left(\frac{a^{n}-b^{n}}{\sqrt{5}}\right)$$

$$=\frac{\color{red}{a^{\left(m+n+1\right)}}-a^{m}b^{\left(n+1\right)}-a^{\left(n+1\right)}b^{m}+\color{blue}{b^{\left(m+n+1\right)}}}{5}-\frac{\color{red}{a^{\left(m+n+1\right)}}-a^{\left(m+1\right)}b^{n}-a^{n}b^{\left(m+1\right)}+\color{blue}{b^{\left(m+n+1\right)}}}{5}$$
$$=\frac{-a^{m}b^{\left(n+1\right)}-a^{\left(n+1\right)}b^{m}+a^{\left(m+1\right)}b^{n}+a^{n}b^{\left(m+1\right)}}{5}$$$$=\frac{a^{m}b^{n}\left(a-b\right)+a^{n}b^{m}\left(b-a\right)}{5}=\frac{\left(a-b\right)\left(a^{m}b^{n}-a^{n}b^{m}\right)}{5}$$$$=\left(a-b\right)\frac{\left(a^{\left(m-n\right)}-b^{\left(m-n\right)}\right)}{\sqrt{5}}\frac{a^{n}b^{n}}{\sqrt{5}}$$$$=\left(a-b\right)\frac{a^{n}b^{n}}{\sqrt{5}}F_{m-n}$$$$=\bbox[5px,border:2px solid #00A000]{\left(-1\right)^{n}F_{m-n}}$$
Which is the claim.

Another way for proving this identity would be setting $i \mapsto m-n$ and $j \mapsto 1$ in Vajda's identity.
Comment: In turn, Catalan's identity is a special case of Vajda's identity with $i=-j$.
Answer: See the paper Fibonacci Numbers and Identities by Lang and Lang. The authors discuss an elegant framework, involving what they call $\mathcal F$-functions, that unifies proofs for many identities for Fibonacci and Lucas numbers, including d'Ocagne.
Answer: Call the left-hand side $u_{m,\,n}$ so$$\begin{align}u_{m+1,\,n+1}+u_{m,\,n}&=F_{m+1}F_{n+2}-F_{m+2}F_{n+1}+F_mF_{n+1}-F_{m+1}F_n\\&=F_{m+1}F_{n+2}-F_{m+1}F_{n+1}-F_{m+1}F_n=0,\end{align}$$so some sequence $a_k$ satisfies $u_{m,\,n}=(-1)^na_{m-n}$. To verify $a_k=F_k$, we only need to check the case $n=0$, i.e. $u_{m,\,0}=F_m$, but that's trivial.
Answer: d'Ocagne identity comes straightly from the matrix form
$$
\eqalign{
  & \left( {\matrix{
   {F_{\,k + 2} }  \cr
   {F_{\,k + 1} }  \cr
 } } \right) = \left( {\matrix{
   1 & 1  \cr
   1 & 0  \cr
 } } \right)\left( {\matrix{
   {F_{\,k + 1} }  \cr
   {F_{\,k} }  \cr
 } } \right)\quad  \Rightarrow   \cr
  &  \Rightarrow \quad \left( {\matrix{
   {F_{\,m + 1} } & {F_{\,n + 1} }  \cr
   {F_{\,m} } & {F_{\,n} }  \cr
 } } \right) = \left( {\matrix{
   1 & 1  \cr
   1 & 0  \cr
 } } \right)\left( {\matrix{
   {F_{\,m} } & {F_{\,n} }  \cr
   {F_{\,m - 1} } & {F_{\,n - 1} }  \cr
 } } \right) =   \cr
  &  = \left( {\matrix{
   1 & 1  \cr
   1 & 0  \cr
 } } \right)^{\,n} \left( {\matrix{
   {F_{\,m - n + 1} } & {F_{\,1} }  \cr
   {F_{\,m - n} } & {F_{\,0} }  \cr
 } } \right) = \left( {\matrix{
   1 & 1  \cr
   1 & 0  \cr
 } } \right)^{\,n} \left( {\matrix{
   {F_{\,m - n + 1} } & 1  \cr
   {F_{\,m - n} } & 0  \cr
 } } \right) \cr}
$$
and taking the determinant
Answer: Define:
$$a:=\frac{1+\sqrt{5}}{2}\;\;\;\;\;\;\text{and}\;\;\;\;\;\;\; b:=\frac{1-\sqrt{5}}{2}$$
Then using this follows:
$$F_{n+i}F_{n+j}-F_{n}F_{n+i+j}$$
$$=\left(\frac{a^{\left(n+i\right)}-b^{\left(n+i\right)}}{\sqrt{5}}\right)\left(\frac{a^{\left(n+j\right)}-b^{\left(n+j\right)}}{\sqrt{5}}\right)-\left(\frac{a^{\left(n\right)}-b^{\left(n\right)}}{\sqrt{5}}\right)\left(\frac{a^{\left(n+i+j\right)}-b^{\left(n+i+j\right)}}{\sqrt{5}}\right)$$$$=\frac{\color{red}{a^{\left(2n+i+j\right)}}-a^{\left(n+i\right)}b^{\left(n+j\right)}-a^{\left(n+j\right)}b^{\left(n+i\right)}+\color{blue}{b^{\left(2n+i+j\right)}}}{5}-\frac{\color{red}{a^{\left(2n+i+j\right)}}-a^{\left(n\right)}b^{\left(n+i+j\right)}-a^{\left(n+i+j\right)}b^{\left(n\right)}+\color{blue}{b^{\left(2n+i+j\right)}}}{5}$$$$=\frac{-a^{\left(n+i\right)}b^{\left(n+j\right)}-a^{\left(n+j\right)}b^{\left(n+i\right)}+a^{\left(n\right)}b^{\left(n+i+j\right)}+a^{\left(n+i+j\right)}b^{\left(n\right)}}{5}$$$$=\frac{a^{n}b^{\left(n+j\right)}\left(b^{i}-a^{i}\right)+b^{n}a^{\left(n+j\right)}\left(a^{i}-b^{i}\right)}{5}$$$$=\frac{\left(a^{i}-b^{i}\right)}{\sqrt{5}}\frac{\left(b^{n}a^{\left(n+j\right)}-a^{n}b^{\left(n+j\right)}\right)}{\sqrt{5}}$$$$=\frac{\left(a^{i}-b^{i}\right)}{\sqrt{5}}\left(a^{n}b^{n}\frac{a^{j}-b^{j}}{\sqrt{5}}\right)$$$$=\bbox[5px,border:2px solid #00A000]{\left(-1\right)^{n}F_{i}F_{j}}$$

Now I will show that how the other identities can be derived using Vajda's identity :
Set $i \mapsto n-1$, $j \mapsto k$ and fix $n=-1$ in Vajda's identity to get:
$$F_nF_{k+1} -F_1F_{n+k}=(-1)^{1}F_{n-1}F_{k}$$
$$F_nF_{k+1}-(-1)^{1}F_{n-1}F_{k}=F_1F_{n+k}$$
$$F_n\color{red}{F_{k+1}}+F_{n-1}F_{k}=F_1F_{n+k}$$
$$F_n(\color{red}{F_{k}+F_{k-1}})+F_{n-1}F_{k}=F_{n+k}$$
$$F_{k-1}F_n+F_k(F_n+F_{n-1})=F_{n+k}$$
$$\bbox[5px,border:2px solid #00A000]{F_{k-1}F_n+F_kF_{n+1}=F_{n+k}}$$
Which is Honsberger identity.

Set $i \mapsto m-n$ and fix $j = 1$ in Vajda's identity to get:
$$F_mF{n+1}-F_nF_{m+1}=(-1)^{n}F_{m-n}F_1$$
$$\bbox[5px,border:2px solid #00A000]{F_mF_{n+1}-F_{m+1}F_n=(-1)^{n}F_{m-n}}$$
Which is d'Ocagne's identity.

Set $i,j \mapsto r$ and $n \mapsto n-r$ in Vajda's identity to get:
$$F_nF_n-F_{n-r}F_{n+r}=(-1)^{n-r}F_rF_r$$
$$\bbox[5px,border:2px solid #00A000]{F_n^2-F_{n-r}F_{n+r}=(-1)^{n-r}F_r^2}$$
Which is Catalan's identity.

Set $i,j \mapsto r$ , $n \mapsto n-r$ and fix $r = 1$ in Vajda's identity to get:
$$F_nF_n-F_{n-1}F_{n+1}=(-1)^{n-1}F_1F_1$$
$$F_n^2-F_{n-1}F_{n+1}=(-1)^{n-1}F_1^2$$
$$\bbox[5px,border:2px solid #00A000]{F_{n-1}F_{n+1}-F_n^2=(-1)^{n}}$$
Which is Cassini's identity.

Proof of d'Ocagne's identity


Which test should I perform?

Question: I have 2 datasets. Dataset X looks like this:
Jmp_o   Nws_r
1       0
0       1
1       1
0       1
0       1
1       0
1       0
...    ...

I calculate the conditional probability P(jmp_o=1|nws_r=1). There is another dataset Y which is like:
Jmp_o   Nws_r
1       0
0       0
1       0
0       0
0       0
1       0
1       0
...    ...

From dataset Y I calculate unconditional probability P(jmp_o=1).
I want to test whether these 2 probabilities are statistically different (by means of p-value).
What test should I perform?
Further clarification: first I have dataset X from where I calculate the conditional probability. Then from dataset X I create a subsample which has Nws_r=0. After creating dataset Y, I calculate the unconditional probability. Now I need to check whether they are different.
Comment: I don't know why the datasets look like that! I'm posting an excel sheet.
Answer: If data can be assumed all independent, you can use a standard test to compare two proportions (prop.test in R with references on its help page), where in the first sample you only use the observations for which nws_r=1.
Comment: Would you please tell what test it would be for SAS? and any help on the code?
Comment: To further clarify, first I have dataset X from where I calculate the conditional probability. Then from dataset X I create a subsample which has Nws_r=0. After creating dataset Y, I calculate the unconditional probability. Now I need to check whether they are different.
Comment: For help with SAS code please see https://stats.meta.stackexchange.com/questions/793/internet-support-for-statistics-software.

Which test should I perform?


How do I get all ID of the server that has my bot? I need to get all invite links of the server that have my bot

Question: I want to get all the invite links of the guilds/servers that have my bot in, how should I do it?
client.guilds.array().sort() only output server names. How should I get the ID/invite links of the server?
Answer: If you want to get the ID's of the servers that have your bot, just loop through the array and print guild.id. For example:
var serverArray = client.guilds.array();
for(i = 0; i < serverArray.length; i++) {
    print("Server ID: " + serverArray[i].id);
}

If you want to get an invite link to the server, then use guild.fetchInvites(). Example:
var serverArray = client.guilds.array();
for(i = 0; i < serverArray.length; i++) {

    serverArray[i].fetchInvites().then(invites => {
        invites.map(invite => {
            print("Invite link: " + invite.url);
        });
    });

}

Note that the above example will only work if there are actually invite links to the server. If there are no invite links, then you can create one using GuildChannel.createInvite(). https://discord.js.org/#/docs/main/11.6.4/class/GuildChannel?scrollTo=createInvite


Increment upload size Wordpress

Question: I want to increment the file size of Wordpress.
I've tried to change the php.ini file in /etc/php5/apache2/php.ini :
upload_max_filesize = 128M
post_max_size = 10M

I've tried adding to my theme's functions:
@ini_set( 'upload_max_size' , '64M' );
@ini_set( 'post_max_size', '64M');
@ini_set( 'max_execution_time', '300' );

I've tried adding to the .htaccess file:
php_value upload_max_filesize 10M
php_value post_max_size 10M

Also I've tried to install a plugin called "Increase Upload Max Filesize" and the plugin is telling me:
Your upload_max_filesize was already 128M.
Your post_max_size was 16M.

After trying each of these 4 methods I've restarted apache service, but none of these is working, when I go to "Add media" Wordpress shows me that the maximum filesize is 1MB.
What's wrong?
Comment: Make sure php.ini does not contain errors and php pulls settings from the expected php.ini file.
Comment: On windows  or linux server?
Comment: @NextDeveloper There's no errors on php.ini, also the Wordpress plugin is showing me the correct php.ini values: Your upload_max_filesize was already 128M. Your post_max_size was 16M. But then when I go to media uploader Wordpress shows me maximum 1 MB permitted.
Comment: @batz I'm using linux server
Comment: have you tried uploading file more than 1MB?
Answer: I had a similar issue. In the end turned out there were 2 php.ini files. 1 in "php" files, and one in "phpmyadmin" files. When i changed both problem solved but not sure this what you are facing. Something similar is mentioned here.
Comment: I just checked which php.ini is apache loading (phpinfo()) and upload_max_filesize = 128M, post_max_size = 16M
Comment: Could be your on shared hosting that somehow overrides your php settings ?
Comment: Maybe try a lower number from 128M , like 30 50 70
Comment: Still the same issue \o/

Increment upload size Wordpress


getting a grip on logs(syslog-ng)

Question: As we continue to move away from NetWare and beginning to use Suse Linux as our server base, centralized logging is becoming more of an possibility.  I know I can install syslog-ng, but beyond that, what good tools are available for log aggregation/archiving and in particular, viewing those logs in a central place via a common gui interface?
Thanks!
Answer: php-syslog-ng might be worth a try. It also has a fully working demo on the website and some screenshots to get a first impression.
Quoting from the site:

Php-Syslog-ng is a frontend for
  viewing syslog-ng messages logged to
  MySQL in realtime. It features
  customized searches based on device,
  priority, date, time, and message.

Splunk, which has already been mentioned here, seems to be quite hip at the moment. You could always try the free version and decide for yourself if it's worth the cash.
Comment: Thanks, I'll take a look at php-syslog-ng.  The problem with splunk, and most non free apps of this type, is that the pricing is generally way out of wack for what a K12 School District is willing and able to pay for something that doesn't add any educational value.
Comment: FWIW, php-syslog-ng was renamed to LogZilla a few years ago adding a new GUI and MUCH better scalability.
Answer: There is a nice logging solution and analyzer called octopussy that has been mentioned on Server Fault numerous times.  It is based on syslog-ng but adds a web interface and some intelligence to it.
Send the URL to a coworker and see if he's willing to click it.
Features(copied from their home page):

LDAP supported for Octopussy Users & Contacts
Send Alerts by Email, IM(Jabber), NSCA(Nagios) & Zabbix_sender
Export Reports by Email, FTP & SCP
Create Map to show your architecture (more info)
Input & Output Plugins for Reports (more info)
Reports Scheduling
'RRDTool' to graph syslog activity
Lot of Services already supported: Bind, Cisco Router, Cisco Switch, DenyAll Reverse Proxy, Drbd, F5 BigIP, Fortinet FW, Ironport MailServer, Linux Kernel/System, Linux IP Tables, Monit, MySQL, Nagios, NetApp NetCache, Juniper Netscreen FW, Juniper Netscreen SM, Postfix, PostgreSQL, Samhain, Snmpd, Squid, Sshd, Syslog-ng, Windows Snare Agent, etc)
Wizard to easily create new Message/Service for Unrecognized logs
Answer: Splunk is the best. You can use the free version up to 500 MB a day or get the paid version. We used the free version for many months before needing the for-pay on but mileage may vary.
Answer: XLog-Solution will store all your logs in the same database and allow archiving. Dashboard is web based. They have alerts and many more.

getting a grip on logs(syslog-ng)


Attribute error while importing boto3 using python3

Question: I'm trying to use aws rekognition client using boto3 on my raspberry pi, have successfully installed aws cli and have configured it also. But when i execute the following code avaialbe in aws blog,
import boto3

def detect_labels_local_file(photo):

    client=boto3.client('rekognition')

    with open(photo, 'rb') as image:
        response = client.detect_labels(Image={'Bytes': image.read()})

    print('Detected labels in ' + photo)
    for label in response['Labels']:
        print (label['Name'] + ' : ' + str(label['Confidence']))

    return len(response['Labels'])

def main():
    photo='photo'

    label_count=detect_labels_local_file(photo)
    print("Labels detected: " + str(label_count))

if __name__ == "__main__":
    main()

I get the following error :
  import boto3
  File "/usr/local/lib/python3.7/dist-packages/boto3/__init__.py", line 16, in <module>
    from boto3.session import Session
  File "/usr/local/lib/python3.7/dist-packages/boto3/session.py", line 17, in <module>
    import botocore.session
  File "/home/pi/.local/lib/python3.7/site-packages/botocore/session.py", line 28, in <module>
    import botocore.configloader
  File "/home/pi/.local/lib/python3.7/site-packages/botocore/configloader.py", line 19, in <module>
    from botocore.compat import six
  File "/home/pi/.local/lib/python3.7/site-packages/botocore/compat.py", line 25, in <module>
    from botocore.exceptions import MD5UnavailableError
  File "/home/pi/.local/lib/python3.7/site-packages/botocore/exceptions.py", line 99, in <module>
    class SSLError(ConnectionError, requests.exceptions.SSLError):
AttributeError: module 'botocore.vendored.requests' has no attribute 'exceptions

Please help me solve it , or tell me what i'm doing wrong . Note :  I'm using python 3.7.3 .
Answer: This blog post should help to explain it.
You will now need to include this dependency yourself as it is no longer bundled with boto3.
For you Raspberry Pi running the following should be sufficient
pip install requests

Then add import requests to your py script
Comment: i read the blog post, but i'm still not clear what do i need to do; just import requests also before boto3? I tried that but the error still exits.
Comment: Basically run `pip install requests` on your host. Then add `import requests` to top of your script
Comment: It didn't work bro, still getting the same error, but in my ubuntu pc it works fine. So i'm changing systems to work with it.


Link image to new tab

Question: I have a problem trying to link image teaser to open in a new tab when clicked. How do i go about that? I know in html is target="_blank" attribute.
Comment: You'll need to provide more context to know where (e.g. module, theme, etc). to have someone answer this.
Answer: One way you can do this is with mytheme_preprocess_field where mytheme is the name of your theme, inside of mytheme.theme file:
/**
 * Implements hook_preprocess_field().
 */
function mytheme_preprocess_field(&$variables) {
      if ($variables['field_name'] == 'field_mylink') {
        foreach ($variables['items'] as $key => $item) {
          $variables['items'][$key]['content']['#options']['attributes']['target'] = '_blank';
        }
      }
}

This would add target="_blank" to each value entered for the link field. But you don't mention if the field is a link field or image field though.
Comment: My page has other images but I want to target this one field that has unlimited images

Link image to new tab


AWS: Unable to connect Amazon QuickSight to RDS

Question: We have a few MySQL RDS instances in West-1 (N. California) and wanted to create some reports using QuickSight. First issue was that QuickSight was only available in West-2 (Oregon) and did not show our RDS, so I created a read-replica database into West-2.
I was still not able to connect to my instance, and it showed the following error:
Connection failed. Make sure your instance is accessible from the appropriate Amazon QuickSight IP address range.
I had already created a Security Group allowing IP 220.127.116.11/27 in the inbound rules and applied it to my instance. What eventually allowed me to connect to the instance was to set the 'Publicly Available' field of the instance to 'Yes'.
However, my boss prefers it to remain 'No' and we were also able to connect to the non-public instance via DOMO using MySQL SSH connection method.
Is it possible to get the connection between QuickSight and RDS working without setting Publicly Accessible to Yes?
Answer: Things have changed, luckily.
It is possible to connect Amazon QuickSight to a DB in RDS which is in a VPC, although the AWS docs are not clear about all the necessary steps.
Basically, follow the steps here,
https://docs.aws.amazon.com/quicksight/latest/user/working-with-aws-vpc.html
but make sure you will create TWO security groups:

Security Group for the Instance in Your VPC
Security Group for Amazon
QuickSight's Elastic Network Interface

Let's start with the second one:
It is the one which will QuickSight assign to a network interface (ENI), which will be automatically created in your VPC to access the DB. This is the one I missed to create at first and this is the one you use to create a VPC Connection in QuickSight. The details are in the above docs in the paragraph "Security Group Rules for Amazon QuickSight's Elastic Network Interface".
The first one looks like this:
Inbound: TCP / port according to the DB – in the case of MySQL it is "MYSQL/Aurora, TCP,
3306", Source: the previous security group.
Do not forget to add this one to your DB instance.
Good luck.
Comment: Just as an update: [Here](https://aws.amazon.com/de/premiumsupport/knowledge-center/quicksight-redshift-private-connection/) is a blog entry last updated in May 2021 describing the process. And [here](https://www.youtube.com/watch?v=uZr3FIW64nk) is the corresponding video from Feb 2021.
Comment: I am also facing the same problem - to connect Quicksight to RDS in a VPC. Does the above solution is applicable to Quicksight standard edition? or Enterprise edition?
Answer: I created a support request with AWS about this, their answer is below.  I will give it a try.
Hi Alistair,
Thank you for contacting AWS Premium Support. I am happy to assist you today.
I understand that you would like to connect to your Prod RDS database from QuickSight, but you getting an error: "Not Validated". You also would like to know if there is a workaround seeing that your RDS instance in not Publicly accessible.
Amazon Web Services offers a service called CloudFormation, this service helps automate certain processes.
This service will allow your RDS instance to connect to QuickSight through a custom NAT instance. Therefore you will not have to put your Data Base in a public subnet.
Attached is a CloudFormation template (NAT_RDS_Provisioning.template), after launching the CloudFormation stack [1] an instance and a security group will be created, you then enter the required variables.
This will then give access from the source address on the source port you define to the endpoint of the EC2 instance which will then allow QuickSight to access your RDS instance server without making your RDS instance public.
To launch this CloudFormation stack please see the steps below… Please keep in mind that the region you create this in must be the same region that your database resides in.
<code>1. From your AWS console navigate to " CloudFormation "
2. Click " create stack ", you will then be asked to Select Template, you will then select " Design template".
3. Next to Parameters - click " Mappings ", at the bottom of that page you will see: Components and Template.
4. Select " Template " and copy and paste the provided script in there. (see attached: NAT_RDS_Provisioning.template)(Please use case link below signature)
5. In the top right hand corner you will see a refresh button, click to refresh.
6. On the top left there is a square with a tick inside (clicking this validates the template).
7. Once validated - click the little cloud with the arrow in it , this will create the stack.
8. You will be taken back to the select template page, click "next" in the bottom right corner.
9. Under Specify Details, name your stack and then complete all Parameters, info on parameters provided below:
    9.1 Stack name  (Example: NAT-RDS-QuickSight)
    9.2 DestinationAddress - Add your RDS instance Endpoint here. (That way when a fail-over occurs the endpoint should be updated in 60 seconds maximum).
    9.3 DestinationPort - The service remote destination port:
    9.4 InstanceType - The EC2 instance class. (The size of the NAT instance will depend on the amount of data you want to pull into QuickSight)
    9.5 KeyName - Name of an existing EC2 KeyPair to enable SSH access to the instance:
    9.6 SourceAddress - The source range you want to allow access from: example 0.0.0.0/0.
    9.7 SourcePort - The port the service must listen on:
    9.8 Subnet - a Public Subnet that is in the same VPC as your RDS instance:
10. Click " Next "
11. On the Options page - complete the desired fields and click " Next " (Optional)
12. Review all information - (Confirm the details for your NAT EC2 instance)
13. Under template you will see "Estimate cost - click on cost to give you an idea of the monthly estimate to have this service running)
14. Then  select " Create " in the bottom right hand corner.
15. On the main CloudFormation Page, click "refresh" You will the notice the status of your Stack being created.
16. If you navigate to your EC2 console you will notice your NAT instance running / creating.
</code>
Please ensure that the NAT instance has access to your RDS instance, this includes Security Group settings.
This should be done by including the IP address of the NAT instance in the Security Group of the RDS instance database.
You should then be able to access the EC2 IP address and port as setup, this will then forward traffic to your Database.
When creating the above you would have seen the estimate costs involved however I have added two more links below for some more information on this and also the cost calculator for you too.
Costs will be the same as an EC2 instance, this launches the AWS Linux latest standard AMI, and throughput will be determined by the instance class  [2] & [3]:
<code>[1] https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/GettingStarted.Walkthrough.html
[2] https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html
[3] https://calculator.s3.amazonaws.com/index.html
</code>
I hope the above information and solution is helpful.
Should you run into any difficulties with any of the above or if you are unsure of anything, please free to reach out to me and I will be more than happy to assist.
To see the file named 'NAT-RDS-Provisioning-Template.template' included with this correspondence, please use the case link given below the signature.
Best regards,
Delene T.
Amazon Web Services

See the provided template file content here: https://pastebin.com/m67sz4bR
Comment: Note: when connecting to the data source from Quicksight, you need to first select the Database Type (eg MySQL or SQL Server and NOT RDS) then enter the Public DNS (Endpoint for NAT EC2 instance) of your NAT instance in the Database server field. Plus de-select the "Enable SSL" to validate your connection.
Comment: Thank you!! my RDS instance was publically accessible and I wasn't able to connect It via quickSight
Answer: Does your RDS Replica is in a VPC or not?
Identify first and then accordingly create a security group and attach neccessary rules to it !
I would recommend you to read Authorizing Connections from Amazon QuickSight to Amazon RDS Instances
Comment: That's the documentation that I followed to get the IP address to white-list. My instance is behind a VPC.


Expression Blend is blocked / locked / malfunctioning?

Question: I am experiencing some very strange behavior with Blend:
Since weeks i am working an a project where I use Blend 4 and Visual Studio 2010 simultaneously. I've never experienced problems with one of these programs or with their co-existence. Work proceeds fine.
But a few minutes ago - from one boot of the computer to the next - Blend seems to have a serious problem:
From now on I am not able alter any value anywhere in my project. I can't create new Controls on a plain surface as well delete existing ones. If i try to alter some attribute of some existing control, the width of an existing button for example nothing happens:
Drag and Drop with the mouse results in nothing more than a slight flickering of the control which looks like if it is fighting against my modification to retain its current value. Regardless what manipulation I apply with the mouse the control stays untouched neither does any value in the properties-panel of Blend change.
It feels as if my project is in read-only mode or locked somehow.
But now comes the frustrating fact: When I apply the modifications described above nothing changes BUT the corresponding XAML code does! Enlarging the width of a button with the mouse doesn't show any effect at the control itself or in the properties pane but the XAML attribute width is changing as I move the mouse ?!
Did anybody also experience this behavior before ? Does anyone has some suggestions ? Maybe the solution is very obvious and just made a fool of myself but I got really stuck with that problem - so any help or suggestions are very much appreciated ... Thanks in advance !
EDIT: It really seems to be a Blend problem because when I open the project in Visual Studio everything is working as it should ...
Answer: Are you certain that there is not a control sitting on top of the others?
Alternatively, are your other controls in a panel (perhaps a grid) that has it's visibility set in a trigger?  If so, Visual Studio displays controls visibility a little differently than Blend does.  Blend attempts to get the property to which you bound your visibility during design time, whereas Visual Studio seems to display the item so long as you have visibility initially set to visible.
Can we see some code to make sure?
Comment: Re-trace your steps, can you think of anything you may have done before this began? At first it sounded like maybe you were running into a memory issue but from what you explained, sounds like a build issue of some sort.
Comment: Ya no worries, one thing you'll run into often with blend, is a pinnacle need for as much RAM as possible. It's a memory hog which can cause some odd issues from time to time but it can be a beautiful beast. Good luck amigo!
Comment: Hi and thank you very much for your answer. In the meanwhile since posting the question I've made some progress in investigating what's going on: The phenomenon appears in every XAML file i open with Blend. Even when i create a completely new project with a plain XAML i am not able to create any object on it. Furthermore I experience the following: After rebooting my machine, starting Blend I am indeed able to create a new project with a plain XAML that behaves normally. ... [I'll cont. in the next comment :)]
Comment: [continued from prev. comment] ... But as soon as I close this new project and load my current working project Blend again starts to come up with this error. Then after closing this project, ending Blend, restarting Blend and again creating a new project I also have this error here (Although creating a new project did succeed **before** i opened my working project. Because i experience this error in all of my dozens of XAML files I think it won't help to post some code. I am currently thinking of re-installing Expression Studio, although I really want to avoid that :)
Comment: Yes Chris, at first I thought in the same way. I have now rebooted my machine several times without doing anything to solve the problem but suddenly the error is gone. I have currently no idea how to reproduce this error but as long as it will not come back again I will stop thinking about it - not the best solution but because of a lack of time and an overload of frustration (that came from silly error searching) I will continue my work on the project :) I hope I don't see me posting again in 5 minutes ;)


destructing array containing objects

Question: <code>let chosen = 4;

let team = [
  { titel: "ahmad", age: 20, available: true, skills: ["html", "css"] },
  { titel: "mizo", age: 30, available: false, skills: ["js", "react"] },
  { titel: "jo", age: 40, available: true, skills: ["pyhton", "django"] },
];

(() => {
  if (chosen === chosen) {
    let {
      titel,
      age,
      available,
      skills: [s1, s2],
    } = team[chosen - 1];
    console.log(`Team-${chosen}:
    name: ${titel}
    age:  ${age}
    skill: ${s1}
    availability: ${(() => {
      if (available) return `available`;
      else return `unavailable`;
    })()}
    `);
  } else return;
})();

</code>
why the given code above throws this error
(Uncaught TypeError: Cannot destructure property 'titel' of 'team[(chosen - 1)]' as it is undefined.) in the console if you choose a number less than 1 or greater than 4 ??
Comment: I really don't understand what you're trying to do here. But since `chosen` is 4, `team[chosen - 1]` is `team[3]` which is `undefined` - your array has only 3 elements. And you can't use object destructuring on `undefined` [Also, unrelated, but why check `if (chosen === chosen)` when that will always be true?]
Answer: This is because it exceed the number of elements in the array.
the team array has 3 items.
To access the first item, whose index is 0, you would do team[0].
To access the last item, whose index is 2, you would do team [2]
When you do team[4-1], you end up with team[3] which has exceeded the length of the array, and is therefore undefined.
Remember, arrays in javascript are 0-indexed. That means the first item is always at index 0, and the last item is at team.length-1, which in this case, is 2.
Comment: thank you @Arky Asmal fro your answer, but can you tell me how to manage this error in my code.

destructing array containing objects


flask-sockets and ZeroMQ

Question: I'm playing around with getting zeromq pub/sub messages sent up to a browser with a websocket. The following "works", in that messages do get sent up through a websocket. However, trying to reload the page just hangs, as I'm guessing the while True loop is blocking. I thought that the gevent.sleep() call would allow a context switch, but apparently not. Any idea how to get all these parts working together?
import zmq
import json
import gevent
from flask_sockets import Sockets
from flask import Flask, render_template
import logging
from gevent import monkey

monkey.patch_all()

app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

sockets = Sockets(app)
context = zmq.Context()

ZMQ_LISTENING_PORT = 6557

@app.route('/')
def index():
    return render_template('index.html')

@sockets.route('/zeromq')
def send_data(ws):
    logger.info('Got a websocket connection, sending up data from zmq')
    socket = context.socket(zmq.SUB)
    socket.connect('tcp://localhost:{PORT}'.format(PORT=ZMQ_LISTENING_PORT))
    socket.setsockopt(zmq.SUBSCRIBE, "")
    gevent.sleep()
    while True:
        data = socket.recv_json()
        logger.info(data)
        ws.send(json.dumps(data))
        gevent.sleep()

if __name__ == '__main__':
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('', 25000), app, handler_class=WebSocketHandler)
    server.serve_forever()

Answer: Nevermind, just realized need to do
import zmq.green as zmq

in order to use with gevent compatibility. Here's a link to pyZeormq docs.

flask-sockets and ZeroMQ


Como fazer uma promise encadeada com Javascript puro?

Question: Como fazer uma chamada encandeada com a promise nativa do Javascript?
Quero dizer, gostaria que a sentença abaixo fosse executada uma após a outra e que eu pudesse saber quando essa sequência de promises forem finalizadas.

var promise;

console.log('iniciando...');

[1, 2, 3, 4, 5].forEach(function (i) {

    promise = new Promise(function (resolve) {
        setTimeout(function () {
          resolve(i);
        }, 1000)
    });

    promise.then(function (value) {
         console.log(value);
    });
});

console.log('finalizado');
Comment: Você tinha que fazer uma propaganda velada pro Bolsonaro, né? Nossa, essa precisa ser gênio pra entender, eu não entenderia se não fosse eu que bolei :D
Comment: Esta pergunta não é duplicada desta outra https://pt.stackoverflow.com/q/140814/129 ?
Comment: @Sergio pode martelar :p, agora que vi que são parecidas
Answer: Eu vi uma solução para isso no AngularJs. Adaptei essa solução para o Javascript nativo.
Veja o código abaixo:

var promise = Promise.resolve();

console.log('iniciando...');

[1, 2, 3, 4, 5].forEach((i) => {

    promise = promise.then(function () {
        console.log(i);
        return new Promise(function (resolve) {
            setTimeout(function () { resolve(i) }, 1000)
        })
    })

});

promise.then(function (value) {
   console.log('finalizando');
});

Se você ver observar o código, iniciamos uma promise já resolvida e usamos o método then, que, por sua vez, retorna outra promise. Quando fazemos isso, o método then pode ser encandeado para resolver a promise retornada no then anterior.
Por exemplo:
 promiseA.then(function () {
    return promiseB;
 }).then(function () {
     return promiseC;
 })

Todo o segredo no forEach acima resume-se em igualar a variável promise definida externamente ao resultado da promise criada na iteração.
Quando chamamos a promise após o forEach, fará com que o resultado de then seja resolvido apenas após a promise da última iteração ser resolvida.


Computing Work with Force Fields

Question: I was given the following question:

Compute the work done by the force field $\mathbf{F}\left(x,y\right)=<2y,-2x>$ along the curve C, where C is the line segment from $\left(4,2\right)$ to $\left(0,4\right)$.

I know that $W=\int_{C}\ F\left(x,y,z\right)\ dr=\int_{C}2ydx-2xdy$.
My question is - how do I create a parametric equation for $x$ and $y$? I think I need to make one in order to find my limits and substitute it in , I just don't know how.
Answer: Hint: You can always parameterize a line segment from point $P_1$ to $P_2$ as
$$P_1 + (P_2 - P_1) t, ~ 0 \leq t \leq 1$$
Comment: This makes sense! Thank you!

Computing Work with Force Fields


How can a class start when I run the program?

Question: I want to create a little game with a square that moves around.Does anyone know how to make the class start when I run the program?
this is the class
class Player:
    def __init__(self, event):
        self.player = self.canvas.create_rectangle(240, 240, 260, 260,
        fill="blue", outline="dark blue")
        canvasx = canvas.winfo_width()
        canvasy = canvas.winfo_height()
        canvas.bind_all("<KeyPress-Up>", move)
        canvas.bind_all("<KeyPress-w>", move)
        canvas.bind_all("<KeyPress-Down>", move)
        canvas.bind_all("<KeyPress-s>", move)
        canvas.bind_all("<KeyPress-Right>", move)
        canvas.bind_all("<KeyPress-d>", move)
        canvas.bind_all("<KeyPress-Left>", move)
        canvas.bind_all("<KeyPress-a>", move)
    def move(event):
        if event.keysym == "Up" or event.keysym == "w":
            canvas.move(1, 0, -5)
        elif event.keysym == "Down" or event.keysym == "s":
            canvas.move(1, 0, 5)
        elif event.keysym == "Right" or event.keysym == "d":
            canvas.move(1, 5, 0)
        else:
            canvas.move(1, -5, 0)

canvas = Canvas(tk, width=500, height=500, bg="silver")
canvas.pack()

this while loop should make the function run, but it doesn't
while True:
    Player.__init__
    Player.move
    tk.update()
    time.sleep(0.01)

Comment: `Player.__init__` doesn't **call** the function itself, and nor is directly calling `__init__` the correct way to create an instance of `Player`. Please read a good book on OOP in Python before attempting to code your own class.
Comment: Post your full code.
Comment: Only the imports and the tkinter basics options are missing
Comment: If you search on the phrase "Pygame object move", you'll find resources that can explain it much better than we can in an answer here.  I expect that what you want is called a "sprite".
Comment: A `class` is not an executable entity that one can "start": it's a container for data and methods that work together to encapsulate a programming concept.  You can call a class method ... but you want an independently movable icon.  Work through more game animation tutorials to get the necessary concepts.  You have the basic structure; I expect the work-through will be quick for you.
Answer: This:
Player.__init__
Player.move
tk.update()
time.sleep(0.01)

is not how you create an instance of a class. When you put Player.__init__, you're not actually calling the constructor. You're basically just stating that it exists. Same with Player.move. You have to actually call the method. Replace those two lines with this:
playerOne = Player(canvas)
playerOne.move()

Now playerOne is an instance of the Player class.
Beyond that, you have an additional problem in the Player constructor.
def __init__(self, event):
    self.player = self.canvas.create_rectangle(240, 240, 260, 260,
    fill="blue", outline="dark blue")

When you reference self.canvas, there is no self.canvas. You have to assign it before you can use it. And you don't seem to use self.player anywhere. I'm not sure exactly what you're going for with that, but try something like this:
def __init__(self, canvas):
    self.canvas = canvas.create_rectangle(240, 240, 260, 260,
    fill="blue", outline="dark blue")

And then replace your move method definition with this:
def move(event=None):
    if event == None:
        return
    if event.keysym == "Up" or event.keysym == "w":
        canvas.move(1, 0, -5)
    elif event.keysym == "Down" or event.keysym == "s":
        canvas.move(1, 0, 5)
    elif event.keysym == "Right" or event.keysym == "d":
        canvas.move(1, 5, 0)
    else:
        canvas.move(1, -5, 0)

Defined outside of your Player class.
Comment: File "C:\Users\vitoa\Desktop\tkinter.py", line 12, in __init__
    self.player = self.canvas.create_rectangle(240, 240, 260, 260, fill="blue", outline="dark blue")
AttributeError: 'Player' object has no attribute 'canvas'
Comment: Did you try to run it?


Overcoming "tracking nervousness" when recording a take?

Question: I'm in that nasty position of becoming nervous when I hit the record button. I can be in my own little studio, no pressure whatsoever, playing perfectly, but as soon as I hit that record button, my playing goes to pieces and it can take 20 takes to do something I did perfectly a dozen times in a row moments earlier.
I'm not a nervous person in day-to-day life, and I love performing on stage, I don't get nervous there at all. Is this likely to be a self-induced pressure type of situation? What tips are there for overcoming nerves when tracking audio? (I'm mainly talking about guitar here, but also piano, etc).
Answer: Since you are recording alone, the pressure you are feeling is self-induced.  Typically when it comes to recording, musicians feel pressure for a variety of reasons:

The take has to be perfect because of the cost of the studio.
The take has to be perfect because of their reputation / job.
The take has to be perfect because time is limited.
The take has to be perfect because it is a representation of them, and they want the best representation of them out there for
    the public. (who doesn't?)

Though this list is not exhaustive, it can provide some insight into why people will record a track over and over again until it's just right.
For me personally, I know that I will re-record something a hundred times if I need to in order to get the take that I want.  Eric Johnson, a notable guitarist, is famous for spending hours and hours and hours just getting his tone right before he does any recording, and even then it takes forever.
So, how do we get around this?
I think I have a few suggestions that could help:

Know your material - cold.  Be able to pick up your guitar and play what you want to play with no warmup at all.  It should be easy and reflexive.  If you are actively thinking about your playing while you record, that hesitancy will come out on the recording.
Get more experience recording in a variety of situations - different recording studios or friends with setups.  Or maybe just taking your own equipment to different locations.  Providing different contexts will give your brain a more comprehensive understanding of the recording process, and therefore should reduce the pressure of the process.
Record a throw-away track.  Recording throw-away tracks are a great way to flex your muscles without pressure.  You know you're not going to use the track anyway, so whatever happens, happens.  If it turns out for the better, then great!  The nice thing about having your own little setup is that you aren't dependent on studio time, so that eliminates that pressure.  When I record, I like to record 3 or 4 throw-away tracks before I do the "real thing".  Sometimes I end up liking one of the earlier tracks better - even though it might have a couple flaws.

This list is not comprehensive by any means, but hopefully it allows you to approach your sessions with a different perspective.
Hope that helps!
Comment: _Know your material - cold_ - +100 . When recording, unless you're a very experienced improviser, you need to know exactly what you're going to play before you record, and have it etched into your brain. IMO, all problems with recording come from uncertainty, which leads to hesitation and nervousness, resulting in screw ups.
Answer: You're making yourself nervous because you're making a take a big deal.
Part of the big deal of doing a take is that cueing up the recording, starting it, getting ready to play, etc. all adds "ritual" that makes this performance more "special" than your normal practice runs.
So, work at removing as much ritual as possible from the process. Find the keyboard shortcuts for your recording software; if you can control recording with a footswitch, try that. Anything so that starting a take ain't no thing.
Make it so that abandoning a take and starting again is easy too. Find a way so that if you screw up, restarting from a sensible point is a tiny effort.
I quite like the feature in GarageBand in which you record over a loop. You can loop many times, and you end up with a pull-down representing a take for each time around the loop. I always screw up the first time around the loop. I'll just let it keep going until I get a good take -- then I'll discard the bad takes.
Comment: +1 I loop when I'm recording too. I assume I'll mess up on the first try and keep doing it until I get it right. I used to have the same issue as the asker but after practicing recording a lot it sort of just went away. But looping definitely helped and still does.
Answer: Record everything you do, even when you practice. As soon as your working on your music in a daw and you plug your guitar, open a track and record it. Eventually you will forget it and play normally.
Answer: Deep breathe. Clear thoughts. The bad takes didn't happen. This is a new fresh take.
The old takes are gone now. This take is going to be pure. Don't worry. You've practiced. You got this. Deep breathe. Clear thoughts. Press record.
1...2...3...4 GO!!!!
Comment: It seems like you're suggesting practicing relaxation techniques and self affirmations? If so, you might want to clarify that, or whatever you are suggesting. Right now this isn't much of an answer.
Comment: @ToddWilcox -It is self explanatory. A great deal has been conveyed in this answer, although there aren't too many words used. Not every answer need be long and cerebral.
Comment: @Stinkfoot Ideally answers would not get flagged for their lack of clarity or content, as this one was. I don't think I'll be the only one to review this so maybe others will vote to delete and maybe they won't. I'm only trying to help Willie d pre-empt any flags or delete votes. It doesn't have to be long and cerebral, but it also doesn't help for it to be too poetic.
Answer: A slight variant on the previous answer's suggestion of a throwaway track: When you're having trouble with a take, pause, take a deep breath and try to record the worst take of anything that anyone has ever recorded. Deliberately play wrong notes, drop out of key, miss the beat, whatever. See if you can make yourself and anyone else in the studio laugh. It's a silly thing to do and completely wastes the take, but it also breaks up the tension, gets you to relax a little bit mentally and puts a smile on your face. The reasons most of us became musicians in the first place is because to some degree we enjoy it, sometimes we need to remind ourselves of that.
You never know you might come up with a whole new unique and original playing style or make it onto the studio's Christmas mix tape. Either is good!


There is already an object named ""; in the database

Question: I am using pyspark in databricks to append data to a sql table via ADF pipelines. Code is sown below:
log_status_df_all = spark.createDataFrame(log_status_df_all)
log_status_df_all.write.format("com.microsoft.sqlserver.jdbc.spark").mode(write_mode).option("url", url).option("dbtable", 'Logs_Collection_Status').option("user", username).option("password", password).save()
log_status_df_all.show()

On some days I am get the error message:
com.microsoft.sqlserver.jdbc.SQLServerException: There is already an object named '<table_name>' in the database.
Upon simply re-running the pipeline the table is updated with no issues; therefore the code is working. How can I prevent this from happening again? Is it an error when multiple pipelines try writing to the same table at the same time?
The rest of the error message is shown below:
---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
<command-3143827225825384> in <module>

      8
      9   log_collection_df = spark.createDataFrame(log_collection_df)
---> 10   write_df_sql(log_collection_df, 'Logs_Collection_Status', 'overwrite')
     11

<command-1421348210166948> in write_df_sql(df, table, write_mode)
     14
     15
---> 16   spark_df.write.format("com.microsoft.sqlserver.jdbc.spark").mode(write_mode).option("url", url).option("dbtable", table_name).option("user", username).option("password", password).save()
     17
     18   #backup table

/databricks/spark/python/pyspark/sql/readwriter.py in save(self, path, format, mode, partitionBy, **options)
    735             self.format(format)
    736         if path is None:
--> 737             self._jwrite.save()
    738         else:
    739             self._jwrite.save(path)

/databricks/spark/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py in __call__(self, *args)    1255         answer = self.gateway_client.send_command(command)    1256         return_value
= get_return_value(
-> 1257             answer, self.gateway_client, self.target_id, self.name)    1258     1259         for temp_arg in temp_args:

/databricks/spark/python/pyspark/sql/utils.py in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

/databricks/spark/python/lib/py4j-0.10.7-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
--> 328                     format(target_id, ".", name), value)
    329             else:
    330                 raise Py4JError(

Py4JJavaError: An error occurred while calling o661.save. : com.microsoft.sqlserver.jdbc.SQLServerException: There is already an object named 'Logs_Collection_Status' in the database.     at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:258)   at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1535)  at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:845)  at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:752)   at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7151)  at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2478)   at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:219)  at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:199)    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeUpdate(SQLServerStatement.java:680)   at com.microsoft.sqlserver.jdbc.spark.BulkCopyUtils$.executeUpdate(BulkCopyUtils.scala:456)     at com.microsoft.sqlserver.jdbc.spark.BulkCopyUtils$.mssqlCreateTable(BulkCopyUtils.scala:495)  at com.microsoft.sqlserver.jdbc.spark.SingleInstanceConnector$.createTable(SingleInstanceConnector.scala:33)    at com.microsoft.sqlserver.jdbc.spark.Connector.write(Connector.scala:60)   at com.microsoft.sqlserver.jdbc.spark.DefaultSource.createRelation(DefaultSource.scala:51)  at org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand.run(SaveIntoDataSourceCommand.scala:45)     at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:70)    at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:68)   at org.apache.spark.sql.execution.command.ExecutedCommandExec.doExecute(commands.scala:86)  at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:152)   at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:140)   at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$5.apply(SparkPlan.scala:193)  at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)   at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:189)   at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:140)    at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:117)     at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:115)    at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:711)  at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:711)  at org.apache.spark.sql.execution.SQLExecution$$anonfun$withCustomExecutionEnv$1.apply(SQLExecution.scala:113)  at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:243)   at org.apache.spark.sql.execution.SQLExecution$.withCustomExecutionEnv(SQLExecution.scala:99)   at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:173)  at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:711)   at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:307)   at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:293)     at sun.reflect.GeneratedMethodAccessor841.invoke(Unknown Source)    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)    at java.lang.reflect.Method.invoke(Method.java:498)     at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)     at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:380)   at py4j.Gateway.invoke(Gateway.java:295)    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)     at py4j.commands.CallCommand.execute(CallCommand.java:79)   at py4j.GatewayConnection.run(GatewayConnection.java:251)   at java.lang.Thread.run(Thread.java:748)

Comment: Added snipet above.
Comment: >Is it an error when multiple pipelines try writing to the same table at the same time?

No. Multiple pipelines can write to the same table.  That is fine. It is an error if multiple pipelines are trying to create the table.
Comment: Does the `write.format()` command create the table if it doesn't exist?  Are any other commands deleting that table?  Are you sure it isn't a concurrency issue?
Comment: Yes, `write.format()` always creates a table if it does not exit in the SQL database.  The table definitely exists as other pipelines are writing to it. Does it matter if I am overwriting the table or appending to it? There is no command deleting the table. It could be a concurrency issue, as the issue only happens when pipelines are running or when the same script is running multiple times in parallel. How would I troubleshoot this issue?
Answer: The issue has now been resolved.
Previous code:
if condition1==True:
     write_mode = 'overwrite'
elif condition2==True:
      write_mode = 'append'

log_status_df_all = spark.createDataFrame(log_status_df_all)
log_status_df_all.write.format("com.microsoft.sqlserver.jdbc.spark").mode(write_mode).option("url", url).option("dbtable", 'Logs_Collection_Status').option("user", username).option("password", password).save()
log_status_df_all.show()

Current code:
write_mode = 'append'

log_status_df_all = spark.createDataFrame(log_status_df_all)
log_status_df_all.write.format("com.microsoft.sqlserver.jdbc.spark").mode(write_mode).option("url", url).option("dbtable", 'Logs_Collection_Status').option("user", username).option("password", password).save()
log_status_df_all.show()


menu block or view that shows only siblings and parents

Question: It seems like this function was removed in drupal 8 so I am trying to find a solution that doesn't involve created a large amount of blocks or hard coding something. (Best would be a block or a view)
I have menu structure like this:
<code>Parent 1
- Child 1.1
-- Grandchild 1.1.1
-- Grandchild 1.1.2
- Child 1.2
-- Grandchild 1.2.1
-- Grandchild 1.2.2
Parent 2
- Child 2.2
-- Grandchild 2.2.1
-- Grandchild 2.2.2
</code>
When I am on Grandchild 1.1.1 I want to see only the entire tree of Parent 1 (that means parent 1 plus all of its child and grandchild items), nothing from Parent 2 and below.
Answer: If you need a solution quickly, you may want to see my post in the Menu Block issue queue:
https://www.drupal.org/node/2811337#comment-11752266
It sounds like I had the same issue you had, and this was the only way I could figure to get the behavior. You'll need the patch that introduces "Active Trail" and "Active Trail Parent" first, as options for Menu Block.
Answer: It seems this question has an ongoing patch at https://www.drupal.org/node/2811337 (which i found just after offering the bounty! :)
Comment: Yes, this is a major issue with MB right now in my opinion, as the behavior that existed in 7 no longer exists in 8. Patches do exist. I wound up hacking the module for my case to just force it to happen.
Answer: You can do this with css if there is no quick fix available by drupal
Comment: Thanks, but as stated in my question, I need the actual data to be printed to the HTML.


Sending message to all user (dm off failure)

Question: The issue im having here is when the bot is cycling through the members and its sending the message, when a user has the dms off it just stops going through them.
I would like it so it keeps going through the members after hitting a member with dms off.
CODE:
@client.command()
async def pd(ctx):
  try:
    for m in client.get_all_members():
        await m.send(ad)
        print(f"received the ad")
  except:
    print(f" has [DM] `off`")

This is what it looks like after hitting a member with dms off.
TERMINAL:
bot is now online
received the ad
received the ad
received the ad
received the ad
 has [DM] `off`

Thank you!
Answer: The reason your code is not working is because whenever you get an error, the loop is broken, and execution continues from the except: block.
You can fix this simply by putting the try: and except: inside the loop.
@client.command()
async def pd(ctx):

  # Iterates over each member
  for m in client.get_all_members():

    # Try sending the message to the member
    try:
      await m.send(ad)
      print(f"received the ad")

    # If an error is produced, log it.
    # After this, the loop will continue onto
    # the next member.
    except:
      print(f" has [DM] `off`")

Answer: OK! So I figured out the issue I had. I needed to move
try:
Down a line to make it inside the loop
EXAMPLE:
@client.command()
async def pd(ctx):

    for m in client.get_all_members():
       try:
        await m.send(ad)
        print(f"received the ad")
       except:
        print(f" has [DM] `off`")
    print("finished sending ads")


JBoss EAP modules maven depencency

Question: Do you know if there are any maven artifacts (similar to org.glassfish.main.extras:glassfish-embedded-all), where I can have all provided libraries of the JBoss EAP at once?
I use this page as a reference for JBoss EAP library versioning, but it's a bit cumbersome to add them one by one for every new project.
Answer: I think you need something as a BOM (Bill Of Materials). There are several for JBoss. https://github.com/jboss-eap/jboss-bom
I found a tutorial on how to use it with some more details. http://www.mastertheboss.com/jboss-frameworks/maven-tutorials/jboss-maven/maven-and-jboss-how-to-use-boms It's a bit old but hopefully this is the direction you was looking for.
Comment: Hm, not what I hoped for I guess :P

JBoss EAP modules maven depencency


How to switch between conflictual hooks?

Question: In a custom module I'm implementing the hook_menu_alter hook to alter the page callback for the $menu['taxonomy/term/%taxonomy_term'] menu.
I've noticed that my hook is not implemented because another contrib module ( Taxonomy Display module ) already implements the same hook (all works fine if I disable TD).
What I need is not to prevail on TD hook with mine, but to use my hook under a certain condition, and TD hook for all other cases.
The condition is the presence of parameter "v" in the querystring, like the following example:
if url == taxonomy/term/tid?v=value then use mymodule_menu_alter
if url == taxonomy/term/tid then use taxonomy_display_menu_alter
How I can do that?
Thank you very much!
MXT
Comment: Your hook should be called even if it's implemented in the Taxonomy Display Module
Answer: If you implement a hook, it will always be executed.
The condition of a query string makes things more complicated in your situation, because all menu items are defined by their path (taxonomy/term/tid in your case). This means that - as far as Drupal is concerned - taxonomy/term/tid?v=value and taxonomy/term/tid have the same menu item, so both requests will be handled by the same code.
Is it really necessary that the URL takes the form of ?v=value? If you could make it taxonomy/term/tid/value, you can create your own custom menu item for taxonomy/term/%/%, and simply leave the taxonomy/term/tid path as is.
Comment: If that is not possible, you need to make sure that your hook is called after the other one (using module weight or hook_module_implements_alter()). Then, look if the argument is there, do your own stuff and if not, manually pass the call forward by calling the Taxonomy Display page callback in your code().
Comment: I'm not sure if it would work to use hook_module_implements_alter, because hook_menu is called when the menu cache is built, not at every request, so you cannot use it to switch the menu callback on a per-request basis. (Or am I wrong?)
Comment: @Berdir: yes! it is exactly what i did!
Comment: marcvangend: Of course, it's not possible to use module_implements_alter() on a per request basis (the hook call itself is cached as well). But it can be used as an alternative to changing the menu weight, which is not always an option. E.g. when you need to be before a module in one case but later for another hook.
Answer: I'm not sure but perhaps you should make the weight of your module higher than Taxonomy Displays, so your modules hook get called first. Check out this http://drupal.org/node/110238
Answer: I've reached a working solution:
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    // move mymodule at the end of the list, so it will be implemented at last:
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

function mymodule_menu_alter(&$menu) {
  if (isset($menu['taxonomy/term/%taxonomy_term'])) {
    // alter menu to serve my own custom term page
    $menu['taxonomy/term/%taxonomy_term']['page callback'] = 'mymodule_term_page';
  }
}

function mymodule_term_page($term) {

    $params = drupal_get_query_parameters();
    $vocab = taxonomy_vocabulary_load($term->vid);

    // If this voc hasn't to be processed, return the default taxonomy term page:
    if(!variable_get('mymodule_' . $vocab->machine_name . '_enabled')) {
      module_load_include('inc', 'taxonomy', 'taxonomy.pages');
      return taxonomy_term_page($term);
    }

    // If param 'v' is present in querystring
    if(isset($params['v'])) {
      // return another custom callback term page:
      return mymodule_show_term_tree($term);
    }
    else {
      // Else call Taxonomy Display module calback page:
      module_load_include('module', 'taxonomy_display');
      return taxonomy_display_taxonomy_term_page($term);
    }
}

I'll hope this will be usefull to others.


What's the probability of rolling the same number twice with a pair of dice?

Question: There are a number of questions similar to this, but I'm asking about rolling two dice twice, not one die two times. Or I guess you could think of it as 4 dice total, with each pair distinguishable.
So Person A rolls two dice (d6) and gets some result between 2 and 12, with 7 being the most likely. Now Person B rolls two dice. What are the odds that Person B rolled the same number as Person A?
I've been trying to work this out for some time now, but it's been a while since I've taken Probability. (Do we have to do some conditional probability stuff here?)
Answer: I guess by 'number' you mean 'sum'. My answer is based on this guess.
The probability of rolling a sum of $s$ is $1/36$ times the number of ways to write $s$ as an ordered sum of two numbers from $1$ to $6$. If we let this number be $n(s)$, we have
$$n(2)=1,\  n(3)=2,\ n(4)=3,\ n(5)=4,\ n(6)=5.\ n(7)=6,$$
$$n(8)=5,\ n(9)=4,\ n(10)=3,\ n(11)=2,\ n(12) = 1.$$
The probability of rolling $s$ twice is $(n(s)/36)^2$, so the probability of rolling a number twice is
$$ \frac{1}{36^2}.\left(2\sum_{k=1}^5 k^2 + 6^2\right)=\frac{1}{36^2}\left( 5(5+1)(10+1)/3 + 36\right)=\frac{146}{36^2}=\frac{73}{648}$$
Answer: Well, just go about it in the simplest way possible. There is no need for conditional probability here because the second roll is independent of the first.
If $X_1$ is the first roll and $X_2$ is the second one, the probability of them being the same is:
$$
P(X_1=X_2) = \sum_{n=2}^{12} {\left[ P(X_1=n) P(X_2=n) \right]} = \sum_{n=2}^{12} {\left[ P(X=n)^2 \right]}
$$
because the probability functions are identical
Note that the value of $P$ depends on $n$ because some numbers are more probable than others when you have two dice. This is the only difference with the similar problem of single die rolls.
Comment: I'm getting 101/648. Sound about right?
Comment: I get something else.
Comment: I think the number in Prometheus' reply is correct so you should be getting $\frac{73}{648}$
Comment: Ahh, typo. Got it. Thanks!
Answer: Because both pairs of dice are independent, call their sums $S_1$ and $S_2$, this is just $P(S_1 = 2)\cdot P(S_2=2) + P(S_1 = 3)\cdot P(S_2=3) + \ldots  + P(S_1 = 12)\cdot P(S_2 = 12)$
And the probabilities of $S_i=2,3,\ldots,12$ is are classical ($\frac{1}{36}$ for 2 and 12, $\frac{2}{36}$ for 3 and 11, up to $\frac{6}{36}$ for sum 7).


I am getting default header in the react-native android ,How to fix that header?

Question: enter image description hereHow I can change that header in the react-native, After giving build I am getting that default android header.Please me out with this issue
Comment: please provide more details, code snippets if possible
Comment: also define what kind of changes you want to apply
Comment: I want to remove the top header that's it
Comment: what `Stack.Screen` does the screenshot correspond to? you can edit your question to add more details, it's not necessary to create an answer for that https://stackoverflow.com/help/how-to-ask
Answer: <code>  <NavigationContainer>
          <Stack.Navigator
            screenOptions={{
              headerTransparent: false,
              headerTitleAlign: "center",
              headerTitleStyle: {
                fontSize: 13,
                fontWeight: "normal",
                letterSpacing: 1,
                color: "#fff",
              },
              headerStyle: {
                backgroundColor: "#7862FF",
              },
              headerTintColor: "#fff",
              headerBackTitleVisible: false,
            }}
          >
            {loginState.userToken == null ? (
              <>
                <Stack.Screen
                  name="Login"
                  component={SignInScreen}
                  options={{ headerShown: false }}
                />
                <Stack.Screen
                  name="SignUp"
                  component={SignUpScreen}
                  options={{ headerShown: false }}
                />
                <Stack.Screen
                  name="Forgotpassword"
                  component={Forgetpassword}
                  options={{ headerShown: false }}
                />
              </>
            ) : (
              <>
                <Stack.Screen
                  name="Landing"
                  component={LandingScreen}
                  options={{ headerShown: false }}
                />
                <Stack.Screen
                  name="Dashboard"
                  component={DashboardScreen}
                  options={{ title: "Dashboard", headerTransparent: false }}
                />
                <Stack.Screen
                  name="ArCamera"
                  component={CreateArTag}
                  options={{ title: "", headerTransparent: true }}
                />
                <Stack.Screen
                  name="ViewArTag"
                  component={ViewArTag}
                  options={{ title: "", headerTransparent: true }}
                />
              </>
            )}
          </Stack.Navigator>
        </NavigationContainer>
</code>


phonegap how to store files in the local filesystem

Question: I'm looking for the appropriate way of storing files into the document folder within phonegap/cordova.
I've done some google searches but all I seem to find is how to use local storage or webSQL.
Also looked at the phonegap plugins github page but nothing seems promising.
The file I'm looking to store is actually a binary file I'll download from the internet.
Answer: Then you will want to use FileTransfer.download to get the binary file from the internet. Then you can manipulate it using the File API.
Comment: Thanks Simon, I'll try it out and let you know the results.
Comment: Here's a more detailed explanation of the problem: http://stackoverflow.com/questions/6417055/download-files-and-store-them-locally-with-phonegap-jquery-mobile-android-and-io


O que realmente é o DNX?

Question: Faz bastante tempo perguntei aqui o que é o runtime environment, em especial na plataforma .NET. Acontece que agora o .NET possui o DNX que é o ".NET Execution Enviroment". Na prática usamos o DNX para executar softwares desenvolvidos com a nova versão do .NET, tendo suporte a utilizar o CLR usual ou então o Core CLR.
Nesse ponto que está minha dúvida. Pelo que estou vendo existe uma diferença entre o runtime environment (no caso CLR ou Core CLR) e o execution environment (no caso o DNX). Me parece que o DNX serve só para escolher um runtime environment e de alguma forma conectar o software com o runtime environment, mas eu não estou entendendo muito bem se é isso e como isso funciona.
Nesse caso o que realmente é o DNX e qual é a real necessidade dele? Além disso, qual a relação dele com o runtime environment?
Answer:
Isto não é mais válido com a implantação do CLI - Command Line Interface

Aos poucos toda tecnologia que surgiu à partir da abertura do código do .NET e da arquitetura mais modular vai se consolidando e chegando no ponto de ter tudo o que é necessário para usar em produção.
Você já deve saber que o CoreCLR substitui o .NET que é uma plataforma cheia de coisas para fazer as aplicações funcionarem. Mas se for ver bem o CLR é apenas um dos componentes do .NET. Então a CoreCLR não substitui por completo o .NET. Alguns componentes que cuidam da infraestrutura de funcionamento das aplicações desenvolvidas usando a CLR são necessários para iniciar a aplicação.
Lembre-se que no momento que você instala o .NET no computador, você praticamente cria um segundo sistema operacional rodando ali. Se for no diretório onde o .NET fica instalado possivelmente dentro do C:\Windows verá que tem algo bem complexo ali. Aquilo não é só a CLR. Tem o compilador, gerenciadores de ambiente responsáveis pelo controle de exceções, gerenciamento de memória, threads, processos, domínios, segurança do código, etc. Ele é o hospedeiro nativo que executado as aplicações gerenciadas.
Pois bem, o DNX é isto mas com uma filosofia diferente, mais modular e menos intrusiva no sistema operacional, como é o .NET. É um jeito mais convencional de chamar a aplicação gerenciada, ou seja, você chama o DNX que vai chamar o resto. No .NET isto é mais transparente. Muita gente acha que está executando um executável real quando executa uma aplicação .NET. Note que não estou dizendo que é um substituto exato.
A definição oficial diz que ele é um SDK específico para aplicações .NET.
A motivação principal dele existir é para hospedar aplicações ASP.NET, já que ele permite que a aplicação rodar sem depender de uma infraestrutura extra, como o IIS, por exemplo. Mas não se restringe a isto.
Acho que nem preciso dizer que uma das diferenças dele para o .NET é que ele foi feito para rodar em diversas plataformas e o .NET original continua sendo exclusivo do Windows. Pela sua filosofia deve ser até difícil portar .NET na forma atual para outras plataformas. E a Microsoft nem está interessada nisto. Fazer o mesmo sistema de carga do ambiente e da aplicação seria muito complicado em outras plataformas. Por isto o Mono e o Java não fazem isto.
Na resposta que eu dei (linkada na pergunta acima) eu dou mais detalhes sobre o fato de existir vários hosts, várias versões do CLR, algumas personalizadas. Como gerenciar tudo isto, como ter algo em comum que faça tudo isto funcionar? A resposta é o DNX. Obviamente existem outras formas de executar uma aplicação .NET sem o DNX. Ele é uma das formas de fazer isto.
Ele também ajuda atender demandas mais modernas. Ele lida de um jeito moderno com configurações, pacotes e atualizações. Ele pode gerenciar as dependências e você só puxa para um deploy o que realmente vai usar.

Retirado da Wiki do DNX.
Eu sei que esqueci de algumas coisas que ele faz, eu tento melhorar com o tempo. Se tiver algo específico que precise saber, que seja traduzido da documentação, deixe um comentário.
É bom ficar atento às novidades. O DNX está sendo modificado.

O que realmente é o DNX?


Como dividir uma string em tamanhos específicos em JavaScript?

Question: Preciso dividir uma string em tamanho específico em JavaScript.
Sei que é possível usar o join() para transformar uma string em um array de letras:
'hello'.split('')

Porém, eu preciso de uma forma onde eu possa determinar o tamanho em que essa string vai ser quebrada.
Por exemplo, em PHP, temos a função str_split() onde você pode determinar o tamanho dessas strings.
No exemplo abaixo, quero dividir a string de 3 em 3.
str_split ('stackoverflow', 3)

Resultado:
[
    "sta",
    "cko",
    "ver",
    "flo",
    "w",
]

Existe alguma maneira de fazer isso em JavaScript?
Answer: A maneira mais simples é:
'string'.match(/.{1,3}/g)

jsFiddle: https://jsfiddle.net/1qhjtc66/1/
A maneira sem Regex com um loop pode ser
const string = 'stackoverflow';
function spliter(str) {
    const chars = str.split('');
    let temp = [];
    let parts = [];
    for (let char of chars) {
        temp.push(char);
        if (temp.length == 3) {
            parts.push(temp.join(''));
            temp = [];
        }
    }
    if (temp.length) parts.push(temp.join(''));
    return parts;
}

jsFiddle: https://jsfiddle.net/58ckfs2f/
Outra maneira, integrando a resposta do @Maniero numa função seria:
const string = 'stackoverflow';

function spliter(str, nr) {
    const parts = [];
    for (let i = 0, length = str.length; i < length; i += nr) {
        parts.push(str.substring(i, i + nr));
    }
    return parts;
}

console.log(spliter(string, 3)); // ["sta", "cko", "ver", "flo", "w"]
console.log(spliter(string, 2)); // ["st", "ac", "ko", "ve", "rf", "lo", "w"]
console.log(spliter(string, 5)); // ["stack", "overf", "low"]

jsFiddle: https://jsfiddle.net/p5611mnw/

E qual é a mais rápida?
Fiz um teste onde corro a função 100.000 vezes e o resultado foi:
match 208 ms
pushloop 388 ms
substring 30 ms

Answer: Sei que alguém fornecerá uma solução com RegEx, maseu prefiro algo assim (pode por em uma função para depois usar em uma só linha de forma mais simples que RegEx e provavelmente mais rápida.

var str = 'stackoverflow';
var chunks = [];
for (var i = 0, charsLength = str.length; i < charsLength; i += 3) chunks.push(str.substring(i, i + 3));
for (var i = 0; i < chunks.length; i++) console.log(chunks[i]);

Coloquei no GitHub para referência futura.
Comment: Ah, é verdade! Tem como usar o `substring` também :D
Answer: string.match

console.log("stackoverflow".match(/.{1,3}/g));

Array.map

var str = 'stackoverflow';
var partes = 3
var pedacos = []

str.split('').map(function(v, i){
    var len = str.length - 1

    if ((i % partes == 0) && (len !== i))
      pedacos.push(str.substring(i, i + partes))

    if (len == i)
      pedacos.push(v)
})

console.log(pedacos)

While / substring

function extrairPedacos(str, n){
    var pedacos = []
    var i = 0

    while (i < str.length){
      (i % n == 0 ? pedacos.push(str.substring(i, i + n)) : i++)
      i++
    }
    return pedacos
}

console.log(extrairPedacos("stackoverflow", 3))
Answer: Eu sempre gosto de escrever os códigos em versões ES5/ES6, assim como suas versões imperativas e funcionais, então para contribuir aqui está um modelo ES6 um pouco funcional:
const splitStr = (str, size) => {
  const length = Math.ceil(str.length / size);
  return Array.from({ length }, (_, i) => (i *= size, str.substring(i, i + size)))
}

Aproveitando do teste do Sergio, eu o atualizei com o modelo proposto aqui, o resultado acabou ficando:
match 328 ms
pushloop 260 ms
substring 31 ms
splitStr 110 ms

Answer: Há n formas de fazer, uma outra maneira seria assim:
var string = 'stackoverflow';

fnc = (str, num) => {
    var t=str.split(''), col = [];
    for(var i in t) {
       col.push(t[i]);
       if((i+1) % num === 0) {
         col.push('-');
       }
    }
  return col.join('').split('-').filter(e => e != "");
}

fnc(string, 3);


Solving quadratic system

Question: If $a,b,c\in \mathbb{R}$ satisfy the system
$a^2+ab+b^2=9$;
$b^2+bc+c^2=16$;.
$c^2+ac+a^2=25$.
Find $ab+ac+bc$
Comment: Are these supposed to be integers? Real numbers? What?
Comment: If you define $a,b,c\in\mathbb R$, then Raghav's answer is not sufficient. There are the other solutions. see the first one and the fourth one in the following page. http://www.wolframalpha.com/input/?i=a%5E2%2Bab%2Bb%5E2%3D9%2C+b%5E2%2Bbc%2Bc%5E2%3D16%2C+c%5E2%2Bca%2Ba%5E2%3D25
Comment: Are you sure it isn't $c^2 + ac + a^2$?
Answer: The following is a geometric solution. Let $P$ be a point, and consider three line segments $PA,PB$ and $PC$ making an angle of $120$ degrees with each other. Thus $\angle APB = \angle BPC = \angle CPA = 120^o.$ Here $|PA| = a, |PB| = b$ and $|PC| = c.$
Then by the law of cosines, triangle $ABC$ has sides $3,4$ and $5.$
Further the area of the triangle $ABC$ is $\frac{1}{2}\cdot 3 \cdot 4 = 6.$ This can be calculated another way, namely $\frac{1}{2}\left( ab + bc + ca\right) \sin 120,$ since area of $ABC = $ areas of $PAB + PBC + PCA.$
Comparing the two, we are done.
Comment: so, you are assuming $a,b,c\gt0$? But there are the other solutions. http://www.wolframalpha.com/input/?i=a%5E2%2Bab%2Bb%5E2%3D9%2C+b%5E2%2Bbc%2Bc%5E2%3D16%2C+c%5E2%2Bca%2Ba%5E2%3D25
Comment: But we aren't interested in finding $a,b,c.$ We are only interested in $ab+ bc+ca.$ Note this is preserved by the other solutions you've mentioned.
Comment: I'm talking about the value of $ab+bc+ca$. See the first one and the fourth one in the page I wrote.
Comment: If P is exterior at triangle ABC , $ab+bc+ac=-8\sqrt{3}$
Answer: If you subtract the first equation from the second, you get $c^2-a^2 + bc - ab = 7,$ so $(c-a)(c+a +b) = 7.$ You get similar equations (all with an $a+b+c$ factor) when you subtract the second from the third, etc, which gives you a linear system in $a, b, c$ (you know $a+b+c \neq 0,$ from the first sentence).
Comment: Another identity can demand usage $$\sum_{\text{cyc }}(a-b)(a^2+ab+b^2)=0$$ :)
Comment: $$a^2+ab+b^2=9$$  $$(c-a)(a+b+c)=7$$  $$(c-b)(a+b+c)=16$$

Solving quadratic system


Duplicating a website in IIS 7

Question: I've set up an integration website in IIS 7 on Windows Server 2008 r2.
Now, I'd like to create copies of this site with different bindings and physical paths so that each developer can work on his own copy of the site.
On a previous project, I simply created a new site in IIS and then manually recreated all the necessary configuration changes.  But this project's site has some fairly complicated configuration, and I'd rather not have to go through all that a second (let alone third or fourth!) time.
Is there a way to duplicate a site in IIS 7?
Answer: Could IIS Export be the tool you're looking for?
Additionally, this StackOverflow post may be useful: https://stackoverflow.com/questions/841547/how-can-i-duplicate-a-websites-settings-in-iis7
Effectivly, all settings are stored in the web.config file, so you should be able to simply duplicate that after you have used the IIS GUI to make your configuration changes.
Comment: Thanks.  I was able to copy/edit the `` records in `c:\windows\system32\inetsrv\config\applicationHost.config`, and this got me most of the way there.

Duplicating a website in IIS 7