text:
Q: Programming with speech recognition of microsoft. How could I close the speech recognition engine each time when it got a word I am programming using the speech recognition of microsoft. I run an example and it works very well. But if I open the speech recognition, the program will be always inside. I want to each time the engine stops when it recognize the words. Is that possible.
My code is a little like this:
_trainer = new SpeechRecognitionEngine();
_trainer.LoadGrammar(new Grammar(new GrammarBuilder(word))); // load a word
_trainer.SpeechRecognized += _trainer_SpeechRecognized;
_trainer.SpeechRecognitionRejected += _trainer_SpeechRecognitionRejected;
_trainer.SetInputToDefaultAudioDevice(); // set the input to the default audio device
_trainer.RecognizeAsync(RecognizeMode.Single);

Thanks for your help.
I tried to call _trainer.Dispose() at the end, but the engine will not work at all and gives me a break.

A: add RecognizeCompleted event to SpeechRecognitionEngine
_trainer.RecognizeCompleted += _trainer_RecognizeCompleted;

inside the _trainer_RecognizeCompleted add
_trainer.RecognizeAsyncStop();

to cancel the  SpeechRecognitionEngine manually,
_trainer.RecognizeAsyncCancel();

to start SpeechRecognitionEngine again call RecognizeAsync again.
_trainer.RecognizeAsync(RecognizeMode.Single);

See MSDN samples
1-)
SpeechRecognitionEngine.RecognizeAsync Method (RecognizeMode) (System.Speech.Recognition)
2-)
RecognizeMode Enumeration (System.Speech.Recognition)

A: You just have to stop the recognizer in the event speechRecognized (when a word is captured)
private void _trainer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
       //Do your work
         _trainer.RecognizeAsyncStop();
    }


text:
Q: Proof of linear independence of two functions In my class we're learning vector spaces, and in the text book there's an example with no solution and it goes like this:

If the domain of functions $f$ and $g$ is $[-1,1]$ and if they are defined $f(x) = \arcsin\left(\displaystyle\frac{2x}{1+x^2}\right)$ and $g(x) = \arctan(x)$, then $(f,g)$ is linearly independent?

I don't know how to prove this, if I can make a linear combination of one of them using the other it's dependent, but how should I go about doing that?
Thanks in advance.

A: If you want to show that $f$ and $g$ are linearly independent, a very similar (but different) question was asked recently. Many techniques for solving that problem are also applicable here.
If you want to show that $f$ and $g$ are linearly dependent, you have to show that $\arcsin(2x/(1+x^2))$ is some constant multiple of $\arctan x$.

A: Theorem: Let $f$ be a function defined in an intrval $I$, and let $F$ be an antiderivative of $f$ in $I$. Then every other derivative of $f$ in $I$ is of the form $F+costant$.
Now use above theorem to see that: $$\arcsin\left(\frac{2x}{1+x^2}\right)= \left\{
        \begin{array}{ll}
            -\pi-2\arctan(x) & \quad x \leq-1 \\
            2\arctan(x) & \quad -1\leq x\leq1 \\\pi-2\arctan(x) & \quad x\geq1
        \end{array}
    \right.
$$

A: $x=\tan g(x) \sin f(x)=2\tan g(x)/1+\tan^2g(x)=\sin 2g(x)$ so $f(x)=2g(x)$ (under suitable conditions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Perform function for another ViewController I have a function in ViewController that I would like to perform from a UIButton in ProfileViewController. How would I do this? Below is the code I have tried.
Code in ViewController
func hideProfileButton (sender:AnyObject) {
    self.profileButtonOutlet.hidden = true
}

Code in ProfileViewController
ViewController.hideProfileButton(self)

A: You can not directly perform one class's @IBAction from another class's UIButton
Here you are dealing thing like owner and slave.
in storyboard/Xib file if you define that the owner of your viewcontroller is ProfileViewController then the UIButton of that view is only response to it's owners @IBAction.
You can have to Viewcontroller which have one owner like Two xib files with have same owner and then you can do thing like you say in question two different Xib files button call same @IBAction,br>
What you can do is...
1] Create an @IBAction in your ProfileViewController and call your ViewController's method
2] Create delegate object in ProfileViewController implement protocol like "btnClicked" and make ViewController to response that delegate by implementing it.
3] Create a NSNotification and make ViewController as an observer and call that notification from ProfileViewController (not preferable solution)


text:
Q: How do I decide on what key to join the tables I have two tables: orders and customer
orders:
+--------+-----------+------------+-------------+-------------+
| ord_no | purch_amt |  ord_date  | customer_id | salesman_id |
+--------+-----------+------------+-------------+-------------+
|  70009 |    270.65 | 2012-09-10 |        3001 |        5005 |
|  70002 |     65.26 | 2012-10-05 |        3002 |        5001 |
|  70004 |    110.50 | 2012-08-17 |        3009 |        5003 |
|  70005 |   2400.60 | 2012-07-27 |        3007 |        5001 |
|  70008 |   5760.00 | 2012-09-10 |        3002 |        5001 |
|  70010 |   1983.43 | 2012-10-10 |        3004 |        5006 |
|  70003 |   2480.40 | 2012-10-10 |        3009 |        5003 |
|  70011 |     75.29 | 2012-08-17 |        3003 |        5007 |
|  70013 |   3045.60 | 2012-04-25 |        3002 |        5001 |
|  70001 |    150.50 | 2012-10-05 |        3005 |        5002 |
|  70007 |    948.50 | 2012-09-10 |        3005 |        5002 |
|  70012 |    250.45 | 2012-06-27 |        3008 |        5002 |
+--------+-----------+------------+-------------+-------------+

customer:
+-------------+----------------+------------+-------+-------------+
| customer_id |   cust_name    |    city    | grade | salesman_id |
+-------------+----------------+------------+-------+-------------+
|        3002 | Nick Rimando   | New York   |   100 |        5001 |
|        3007 | Brad Davis     | New York   |   200 |        5001 |
|        3005 | Graham Zusi    | California |   200 |        5002 |
|        3008 | Julian Green   | London     |   300 |        5002 |
|        3004 | Fabian Johnson | Paris      |   300 |        5006 |
|        3009 | Geoff Cameron  | Berlin     |   100 |        5003 |
|        3003 | Jozy Altidor   | Moscow     |   200 |        5007 |
|        3001 | Brad Guzan     | London     |       |        5005 |
+-------------+----------------+------------+-------+-------------+

The problem I am trying to solve is

Write a SQL statement to make a list with order no, purchase amount, customer name and their cities for those orders which order amount between 500 and 2000.

My Query for that is
SELECT ord_no, purch_amt, cust_name, city
FROM orders o
JOIN customer c
ON o.customer_id = c.customer_id
WHERE purch_amt BETWEEN 500 AND 2000

The above query gives correct answer as per this link.But I am not understanding on what column to join.
I have joined tables on o.customer_id = c.customer_id but what If I join both tables on salesman_id.
Why join on customer_id is correct and salesman_id is wrong. I wanted to understand in general how to decide columns on which join should occur when there are more than one common columns in tables between which join occurs( in this case customer_id and salesman_id)

A: The question to answer: What does customer.salesman_id represent?
orders.salesman_id obviously tells us which salesman sold the stuff, while orders.customer_id tells us who bought it. So we join by customer_id in order to get the customer name for an order.
customer.salesman_id may mean something like the salesman who usually sells to the customer, which would be completely unrelated to the task.
It could also be, however, that a customer_id is only valid in combination with a salesman_id. So salesman #1 has a customer #1, but salesman #2 also has (another) customer #1. That would be composite keys, i.e. salesman_id + customer_id would be the customer's primary key and naturally the orders' foreign key. You'd have to join on both columns then. (However, it would be a bad idea then to call these columns ID. salesman_number + customer_number would be a better choice then, to indicate that they are not the tables' single IDs.)
So you see, it depends on the meaning of customer.salesman_id. In order to write queries, you must know your data model. As you say your solution was correct, customer.salesman_id obviously has a meaning unrelated to the given task.

A: You use a relational database, where there is a relation between the orders and the customers (who placed these orders). There is also a relation to the salesman who handled each order. Depending on the information you need you need to join tables, and relevant details are linked by their key, their unique identifier in each table.


text:
Q: Azure Table Storage SDK - Empty a table This may seem a trivial question, but I'm having some hard time to figure it out.
I just need to empty an Azure Storage Table using the .NET SDK.
The only thing I found is the following:
TableOperation deleteOperation = TableOperation.Delete(entity);
TableResult result = await table.ExecuteAsync(entity);

This would require to query the whole table and iterate over the results, which in terms of performance is unreasonable. Is there some method to empty the whole table?
Thanks

A: You can delete the table and recreate it. However please keep in mind that deleting a table is an asynchronous operation on the storage side and may take at least 30 seconds or more (depending on the data). While a table is being deleted, you can't recreate it.
Other alternative is to make use of Entity Batch transactions and delete 100 entities at a time. This will be faster than deleting single entities.

A: You can delete an entire table like so:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
tableClient.DeleteTableIfExist("mytable");

As Gaurav points out this is done asynchronously so if you want to recreate the table you will need to use a while loop and keep trying every say 5s until the create works.

A: It seems that DeleteTableIfExists method on CloudTableClient has been discontinuated and moved into Microsoft.WindowsAzure.Storage.Table.CloudTable.
I wrote an extension method EnsureTableIsEmpty which deletes and recreates the table using Polly to provide a basic retry strategy. Below the code:
public static async Task<CloudTable> EnsureTableIsEmpty(this CloudTable table)
{
    await table.DeleteIfExistsAsync();
    await Policy
        .Handle<StorageException>((exc) => { return exc.Message == "Conflict"; })
        .WaitAndRetryAsync(
            5,
            retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
            (exception, timeSpan, retryCount, context) =>
            {
                //Logging stuff
            })
        .ExecuteAsync(() => table.CreateIfNotExistsAsync());

    return table;
}

It is working kinda well. Any suggestion or improv would be nice.


text:
Q: ssh : Permission denied (publickey,gssapi-with-mic) i'm use centos 5.9.
after installing gitlab by this link ssh not working.
before install gitlab ssh correctly working.
i'm using this server localy and other services such as elastix and apache,mysql installed on server.
appeare this error :
OpenSSH_6.9p1 Ubuntu-2ubuntu0.1, OpenSSL 1.0.2d 9 Jul 2015
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to 192.168.88.23 [192.168.88.23] port 22.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
                                        debug1: Local version string SSH-2.0-OpenSSH_6.9p1 Ubuntu-2ubuntu0.1
debug1: Remote protocol version 2.0, remote software version OpenSSH_4.3
debug1: match: OpenSSH_4.3 pat OpenSSH_4* compat 0x00000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to 192.168.88.23:22 as 'root'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-rsa,ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-dss-cert-v00@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,ssh-dss
debug2: kex_parse_kexinit: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1,hmac-md5-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1,hmac-md5-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug1: kex: server->client aes128-ctr hmac-sha1 none
debug1: kex: client->server aes128-ctr hmac-sha1 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<7680<8192) sent
debug1: got SSH2_MSG_KEX_DH_GEX_GROUP
debug2: bits set: 3111/6144
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: got SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: ssh-rsa SHA256:7J6JOe94H9PedNKlx6yG/wMy6ZYC8iB74WdOVGDgY7A
debug1: Host '192.168.88.23' is known and matches the RSA host key.
    debug1: Found key in /root/.ssh/known_hosts:1
debug2: bits set: 3102/6144
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /root/.ssh/id_rsa ((nil)),
debug2: key: /root/.ssh/id_dsa ((nil)),
debug2: key: /root/.ssh/id_ecdsa ((nil)),
debug2: key: /root/.ssh/id_ed25519 ((nil)),
debug1: Authentications that can continue: publickey,gssapi-with-mic
debug1: Next authentication method: gssapi-with-mic
debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available

debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available

debug1: Unspecified GSS failure.  Minor code may provide more information

debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available

debug2: we did not send a packet, disable method
debug1: Next authentication method: publickey
debug1: Trying private key: /root/.ssh/id_rsa
debug1: Trying private key: /root/.ssh/id_dsa
debug1: Trying private key: /root/.ssh/id_ecdsa
debug1: Trying private key: /root/.ssh/id_ed25519
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey,gssapi-with-mic).

A: please make sure following changes should be uncommented, which I did and got succeed in centos7
vi /etc/ssh/sshd_config

1.PubkeyAuthentication yes

2.PasswordAuthentication yes

3.GSSAPIKeyExchange no

4.GSSAPICleanupCredentials no

systemctl restart sshd

ssh-keygen

chmod 777 /root/.ssh/id_rsa.pub

ssh-copy-id -i /root/.ssh/id_rsa.pub user@ipaddress

thank you all and good luck

A: Setting 700 to .ssh and 600 to authorized_keys solved the issue.
chmod 700 /root/.ssh
chmod 600 /root/.ssh/authorized_keys

A: I had the same problem. In my case, macOS doesn't load my SSH keys, but I fix it with:
ssh-add <SSH private key>
ssh-add <SSH public key>

I couldn't connect to a Droplet on DigitalOcean, but the subsequent commands work for me.
You can go to the forum here.

A: I had the same issue while using vagrant.  So from my Mac I was trying to ssh to a vagrant box (CentOS 7)
Solved it by amending the /etc/ssh/sshd_config PasswordAuthentication yes then re-started the service using sudo systemctl restart sshd
Hope this helps.

A: According to the line debug1: Authentications that can continue: publickey,gssapi-with-mic , ssh password authentication is disabled and apparently you are not using public key authentication.
Login to your server using console and open /etc/ssh/sshd_config file  with an editor with root user and look for line PasswordAuthentication then set it's value to yes and finally restart sshd service.

A: Tried a lot of things, it did not help.
It get access in a simple way:
eval $(ssh-agent) > /dev/null
killall ssh-agent
eval `ssh-agent`
ssh-add ~/.ssh/id_rsa

Note that at the end of the ssh-add -L output must be not a path to the key, but your email.

A: In Centos 7
Error : publickey,gssapi-keyex,gssapi-with-mic
Ans : Root access to vi /etc/ssh/sshd_config and change the PasswordAuthentication ( no ) to yes.
2 . Restart the sshd services
root> systemctl restart sshd.service

*Logon into local id via putty without key.

A: Setting PasswordAuthentication to yes,  is not the best way to go ,
is not as secure as using private and public keys for authentication !
First make sure that that you have the fallowing permissions set, on the server side.
First check your home dir (SERVER SIDE)
[vini@random ~]$ ls -ld ~

drwx------. 3 vini vini 127 Nov 23 15:29 /home/vini

if it is not like this, run
chmod 0700 /home/your_home

Now check .ssh folder
[vini@random ~]$ ls -ld  /home/vini/.ssh/

drwx------. 2 vini vini 29 Nov 23 15:28 /home/vini/.ssh/

if it is not looking like this, run
chmod 0700 /home/your_home/.ssh

now make sure that authorized_keys looks like this
[vini@venon ~]$ ls -ld  /home/vini/.ssh/authorized_keys

-rw-------. 1 vini vini 393 Nov 23 15:28 /home/vini/.ssh/authorized_keys

or just run
chmod 0600 /home/your_home/.ssh/authorized_keys

After that go to /etc/ssh/sshd_config
For best security set
PermitRootLogin no

PubkeyAuthentication yes

keep as yes for testing purposes
PasswordAuthentication yes

Make sure that
ChallengeResponseAuthentication no

Comment those lines for GSSAPI
# #GSSAPIAuthentication yes
# #GSSAPICleanupCredentials no

Make sure that is set to UsePAM yes
UsePAM yes

now restart sshd service
systemctl restart sshd

on the client side
cd /home/your_home/.ssh

generate new keys; setting a password is optional but is a good idea
ssh-keygen -t rsa -b 2048

copy pub key to your server
ssh-copy-id -i id_rsa.pub user_name@server_ip

start ssh agent

eval $(ssh-agent)

ssh-add /home/user/.ssh/your_private_key

now your are good to go !
ssh user_name@server_ip

if everything works just fine
make a backup of your private key and then deny PasswordAuthentication
PasswordAuthentication no

Restart you server
now anyone trying to ssh into  your server, without your keys  should get
vini@random: Permission denied (publickey).

keep script kids away from your business, and good luck

A: As a few others have mentioned, make sure you are using the right private key when you ssh into your server. I had multiple ssh private keys set up in my directory, so it was defaulting to a different key. To ssh with the correct key call it out in your CLI call ssh centos@IP-ADDRESS -i YOUR-PATH-TO-KEY, in my case the path was ~/.ssh/id_rsa

A: As everybody else has already said you need to edit /etc/ssh/sshd_config and change PasswordAuthentication no to PasswordAuthentication yes
I ran into this problem setting up a Vagrant box - so therefore it makes sense to script this and do it automatically in a shell provisioner:
sudo sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config;
sudo systemctl restart sshd;

A: The isssue is the username for most publickey errors on centos instances on AWS.
For Permission denied (publickey,gssapi-keyex,gssapi-with-mic):
its pretty simple. Just change your username from centos to ec2-user and the issue is solved.
Thank me later :)

A: Nobody has mention this in. above answers so i am mentioning it.
This error can also come if you're in the wrong folder or path of your pem file is not correct. I was having similar issue and found that my pem file was not there from where i am executing the ssh command
cd KeyPair
ssh -i Keypair.pem ec2-user@244.255.255.255

A: I know this is an old question, but thought I'd add my fix in the pot.
I was getting the same error trying to connect to Amazon Linux from Ubuntu. The solution was to simply change this:
ssh-add -c <key_location>.pem

to this:
ssh-add "<key_location>.pem"

... pretty simple change there got me in.

A: fixed by setting GSSAPIAuthentication to no in /etc/ssh/sshd_config

A: Maybe you should assign the public key to the authorized_keys, the simple way to do this is using ssh-copy-id -i your-pub-key-file user@dest.

A: And I think this will clearify the cause of posted problem, actualy this is bug of pssh itself (contains inside "askpass-client.py"). It is pssh's lib file. And there is documented issue for -A case:
https://code.google.com/archive/p/parallel-ssh/issues/80
There are two possible resolutions to use version of pssh containing this bug in case you forced to use passphrase for private key access:

*

*Correct your "askpass-client.py" as described in link listed before in my post.

*Using your favorite pass keeper.

Thnks for attention, hope it helps!

A: I try
rm ~/.ssh/id_rsa.pub

then it work!

A: First a password login has to be established to remote machine

*

*Firstly make a password login

you have to enable a password login by enabling the property ie) PasswordAuthentication yes in sshd_config file.Then restart the sshd service and copy the pub key to remote server (aws ec2 in my case), key will be copied without any error

*

*Without password login works if and only if password login is made first

*copy the pub key contents to authorised keys, cat xxx.pub >> ~/.ssh/authorized_keys

A: This can happen if you are missing the correct id_rsa key set up in authorized_keys for an AWS instance.
Exact error I got (this article came up when I googled the error):
ec2-user@X.X.X.X: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
Note: If you have many keys, you have to either specify the key on the ssh command line or else add it to you ssh-agent keys (see ssh-add -l). Only the first 6 keys from ssh-agent may work - the default sshd MaxAuthTries config value is 6.

A: Hope, this will help someone. Problem I encountered is, I was completely using wrong key with the IP. Make sure you are using the right key for the right IP

A: For me it is a completely mistake, someone copy paste the key into the same row with another key, after separating them into two different lines then it works again, so check if your authorized_key file has similar mistakes !

A: I had same issue Permission denied (publickey, gssapi-keyex, gssapi-with-mic) earlier.
I had to go /etc/ssh/sshd_config to add the user user into AllowUsers section, then restarted sshd service.

A: Let me share with you how I did it and I am sure you will find good answer here.
Make sure the following

Step 1. You have Public DNS (IPv4) from aws   E.g ec2-IPV4.us-east-2.compute.amazonaws.com

Step 2. You remember where your your_secret_key_is.pem  E.g its better to keep it far from root of the known folders like Downloads, Desktop or Documents

Step 3 Open terminal and add the command sudo ssh -v -i path-to-key.pem ec2-user@host

ec2-user is important because it for some linux server it is the username
sudo it needs permission to execute
host It is Amazon Public DNS (IPv4) (copy step 1)
Find more info here

A: Permission denied (publickey)

seems like an issue generated by the ssh client rather than the ssh server in my case.
Here's what caused my problem and how I solved.
The problem source is I used sudo to generate the keys like this:
sudo ssh-keygen -t ed25519 -f ~/.ssh/serverA_ed25519_key

This automatically set the owner of these key files to root only, so my current user doesn't have permission to read the keys.
Now solution #1 is change the file ownership to your current user. This's what I did.
sudo chown CURRENT_USER ~/.ssh/serverA_ed25519_key

Solution #2 would be just run ssh client with sudo when you try to connect to the ssh server.
Finally, a trick to find the source of problem with ssh client.
ssh -v -o IdentitiesOnly=yes -i ~/.ssh/serverA_ed25519_key me@serverA

This let me focus on the problem by:

*

*show verbose info by -v flag.

*the -o option and -i ~/.ssh/serverA_ed25519_key force ssh client to try with this key ONLY, not all the keys you have.

A: I also have this error info : Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
Using cmd: ssh -i "~/.ssh/old.pem" user@ip cause the error.
Problem is old.pem has been deprecated, after changing to newest pem file,
the error disappears.

A: In my case, I was using wrong username. Fixed that and the issue got resolved.

A: The issue is simple, the owner for the key should be one in case if windows ( Just remove other users and keep only one or deny other users permissions) for linux/Mac just do a chmod 400 as this will only give read permission only to the user and no permission to groups or public.

A: I run into this strange error whiles connecting from my Mac(host) to a CentOS(7.9) guest. I had to explicitly passed the key file to the ssh client ssh root@ip -i private_key_file before connection was successful.
Earlier on, I had enabled the following after the usual key generation with ssh-keygen and copying with ssh-copy-id

PermitRootLogin yes #Logging in with root, it was set by default
PasswordAuthentication no

I decided against using the default name provided by ssh-keygen though the generated file was saved at the same location as the default.
I left the other default values untouched.
Don't forget to restart sshd on the remote machine.

A: I got Sucess !!
I've copied my ssh_keys from my other machine and tryed to log to my AWS EC2, but it failed:
sign_and_send_pubkey: signing failed for RSA "/home/xxxx/.ssh/my_rsa" from agent: agent refused operation
ec2-user@bla-blah-blah.zzzzz.amazonaws.com: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
The solution was:
cd $HOME/.ssh
ls -l
-r-x------ 1 xxxx xxxx 1766 May  4 09:13 id_rsa
-r-x------ 1 xxxx xxxx  405 May  4 09:13 id_rsa.pub
-rw-r--r-- 1 xxxx xxxx  444 May  6 17:18 known_hosts
Optional command:
rm known_hosts
chmod 400 id*
ssh -i ./id_rsa.pub ec2-user@bla-blah-blah.zzzzz.amazonaws.com
Last login: Fri May  6 19:09:48 2022 from 123.456.77.9
   __|  __|_  )
   _|  (     /   Amazon Linux 2 AMI
  ___|\___|___|

A: Just run this to add your key to localhost of current user.
 ssh-copy-id localhost

A: In my case the problem was selinux.
It was just disabling it.
vi /etc/sysconfig/selinux
SELINUX=disabled
setenforce 0;
sestatus;

A: I know this reply is drowned into the abyss of answers, but I think it's still relevant to share my team's use case : the error can also be triggered because the target instance is incorrect.
As simple as that.

A: GIT_SSH_COMMAND="ssh -v" git clone
This will help debug the issues by printing a detailed log.


text:
Q: SignalR hub check if a connection is still alive We have a hub that manage clients like a chat.
On some occasions we have noticed that there are "dead" connections that no disconnect event has been invoked.
On ASP .NET framework 4.5.2 SignalR, we used ITransportHeartbeat to check the current connection state:
// SignalR connection state check - .NET framework 4.5.2
var heartBeat = GlobalHost.DependencyResolver.Resolve<ITransportHeartbeat>();
var connectionId = appConnection;
var connection = heartBeat.GetConnections().FirstOrDefault(
                                   c => c.ConnectionId == connectionId);

if (!connection.IsAlive)
{
     //...
}

I don't see ITransportHeartbeat anymore on SignalR .NET Core. Is there any way to find the current specific connection state?


text:
Q: How to restrict direct access from internet to Azure Public LoadBalancer backend pool VM with NSG As the question at title, I'm setup the following architecture on Azure Cloud and having trouble at restricting direct access from the internet to VMs.

Here are architecture requirements:

*

*Both VMs must have public ips (for SysAdmin to access via SSH)

*Direct traffics from Internet to WebService on VMs (via port 80) must be denied

*The web traffics from Internet must go thru Public LB to VMs

Suppose that both VMs are in WebASG (Application Security Group), in the NSG setting that applied to VM's Subnet, I've add some rules (which have higher priority than 3 Azure NSG default rules):

*

*Scenario A (adding 1 custom rule):

Port: 80 - Protocol: Tcp - Source: Internet - Destination:
  WebASG - Action: Allow

With this NSG setting, I could access WebService from LoadBalancer IP (satisfy #3 requirement), but WebService on port 80 of both VMs will be exposed to Internet (that violates #2 requirement)

*Scenario B (adding 2 custom rules):

Port: 80 - Protocol: Tcp - Source: AzureLoadBalancer -
  Destination: WebASG - Action: Allow
Port: 80 - Protocol: Tcp - Source: Internet - Destination:
  WebASG - Action: Deny

With this NSG setting, #2 requirement is satisfied, but I could not access WebService when visit LoadBalancer IP (violates #3 requirement)
Please note that: using  AGW (Azure Application Gateway, I could make all the requirements happened by these NSG configuration:

RuleName: AllowSSH Port: 22 - Protocol: Tcp - Source:
  sys-admin-ip-address - Destination: WebASG - Action: Allow
RuleName: DenyInternet2Web Port: Any - Protocol: Any -
  Source: Internet - Destination: WebASG - Action: Deny
RuleName: AllowProbe2Web Port: 80 - Protocol: Tcp -
  Source: VirtualNetwork - Destination: WebASG - Action:
  Allow
RuleName: AllowProbe2Web Port: 80 - Protocol: Tcp -
  Source: VirtualNetwork - Destination: WebASG - Action:
  Allow

I dont want using AGW because it would cost more money than Azure LoadBalancer (actually the Basic LoadBalancer is free). So, how could I change NSG to satisfy all requirements when using LoadBalancer?
Thank in advance for any help!

A: I don't think there are NSG rules that will satisfy all requirements because of the #1 and #2 requirements are contradictory.
If the VMs must have public IP addresses, it actually has a chance to expose to the Internet. Any clients could access the VMs via the public IP. It works the same if you want to access the VMs through the load balancer frontend IP. Read the https://learn.microsoft.com/en-us/azure/load-balancer/load-balancer-overview#load-balancer-concepts

Load Balancer doesn't terminate or originate flows, interact with the
  payload of the flow, or provide any application layer gateway
  function. Protocol handshakes always occur directly between the client
  and the back-end pool instance. A response to an inbound flow is
  always a response from a virtual machine. When the flow arrives on the
  virtual machine, the original source IP address is also preserved.

In this case, you could remove the backend-instance IP address, just use the load balancer frontend for the web traffic and SSH connection. If so, You could configure port forwarding in Azure Load Balancer for the SSH connections to individual instances and a load balancer rule for the web traffic following this quickstart, which works with standard LB. You can only allow port 80 and 22 from your clients' IP addresses. The NSG will look like this,
Port: 80,22 - Protocol: Tcp - Source: client's IP list - Destination: WebASG - Action: Allow


text:
Q: Calculate values only for specific values I have function that calculates difference between current and previous rows
Here it is
function distanceDifference() {
    var rowsDistance = $('#tbody tr');
    for (j = 1; j < rowsDistance.length; j++) {

        // Get the rows
        var previousDistanceRow = rowsDistance.eq(j - 1);
        var currentDistanceRow = rowsDistance.eq(j);

        var previousDistance = previousDistanceRow.find('td').eq(5).text();
        var currentDistance = currentDistanceRow.find('td').eq(5).text();

        //alert(previousDistance);

        var difference = currentDistance - previousDistance;
        //alert(difference);
        currentDistanceRow.find('td').eq(6).text(difference);

    }
}

It works well for all values
But I have column
@data.Datatype

Value of it can be 0,1,2
I need to calculate difference only if it ===2
I try to do it like this
function distanceDifference() {
    var rowsDistance = $('#tbody tr');
    for (j = 1; j < rowsDistance.length; j++) {
        var value = $('#dataType').text();
        if (value === 2) {
        // Get the rows
        var previousDistanceRow = rowsDistance.eq(j - 1);
        var currentDistanceRow = rowsDistance.eq(j);

        var previousDistance = previousDistanceRow.find('td').eq(5).text();
        var currentDistance = currentDistanceRow.find('td').eq(5).text();

        //alert(previousDistance);

        var difference = currentDistance - previousDistance;
        //alert(difference);
        currentDistanceRow.find('td').eq(6).text(difference);
      }
    }
}

but it not works. How I need to write code correctly?

A: Use if (value == 2) instead of if (value === 2).
Because equality operator === compares also the operands data types.
But the data type for the value '2' is string and you comparing with integer 2
Operator == will compare only value 2 == 2, without comparing the operands data types!

A: Even though a non-strict comparison would work it is - in my opinion - better practice to validate and convert user input to a specific data type.
So if you expect the users input to be an integer, use this
var value = parseInt( $('#dataType').text(), 10 );

If you expect it to be a number with a floating point, use this instead:
var value = parseFloat( $('#dataType').text() )

Then you can use a strict comparison like you already did.
But always validate if the user input has the right format.

A: So trouble was in that I get only first value from column
Here is valid code
function distanceDifference() {
    var rowsDistance = $('#tbody tr');
    for (j = 1; j < rowsDistance.length; j++) {
        //var value = parseInt($('.dataType ').html());
        var test = $('.dataType');
        if (parseInt($(test[j]).html()) === 2) {
        // Get the rows
        var previousDistanceRow = rowsDistance.eq(j - 1);
        var currentDistanceRow = rowsDistance.eq(j);
        var previousDistance = previousDistanceRow.find('td').eq(5).text();
        var currentDistance = currentDistanceRow.find('td').eq(5).text();
        var difference = currentDistance - previousDistance;
        currentDistanceRow.find('td').eq(6).text(difference);
     }
    }
}


text:
Q: Sum IFs of total count without recounting Multiple instances, only the closest date prior to the AS OF DATE I need a formula that will SUM the amount of, let's say, animal types AS OF DATE given WITHOUT adding the previous animal type count, only for the closest date prior to or on the AS OF DATE. Different animal types maybe added to or taken away. So list is not set.
I prefer not to do this in VBA or with a Pivot Table, But any help will be appreciated.
    A            B          C
 DATE        ANIMAL TYPE  COUNT
 JAN 01        DOG          1
 JAN 02        CAT          2
 JAN 04        Fish         1
 JAN 12        DOG          2
 JAN 20        CAT          3
 FEB 01        PIG          1
 FEB 02        CAT          2

 AS OF DATE TOTAL ANIMALS
 JAN 03          3
 JAN 13          5
 JAN 21          6
 FEB 01          7
 FEB 02          6

So.
As of Jan 03, there was 3 animals total. 1 Dog and 2 cats.
As of Jan 13, there was 5 animals total. 2 Dogs, 1 Fish and 2 Cats,,,,,, NOT 6
As of Jan 21, there was 6 animals total. 2 Dogs, 1 Fish and 3 Cats,,,,,, NOT 9
As of Feb 01, there was 7 animals total. 2 Dogs, 1 Fish 1 Pig and 3 Cats, NOT 10

A: So far this is what I have. By using a helper column to filter the Animal Types I get a list without duplicates. Then I put that in a cell with Data Validation to pick the Type. Same for the Dates. However I would like to drop the Type input and just choose the Date. And be able to get a total.
Here is what works but not what I need.
=SUMIFS(TabData1[Count],TabData1[Date],MAX(IF(TabData1[Animal Type]=$G$2,IF(TabData1[Date]<=$F$2,TabData1[Date]))))

I want to do away with the Single Cell reference ($F$2) of a single Animal Type and replace it with a Range to get the latest count of Animals for all Animal Types as of a certain date. Like this but this does not work.
=SUMIFS(TabData1[Count],TabData1[Date],MAX(IF(TabData1[Animal Type]=(OFFSET($J$2,0,0,COUNT(IF(ListAnimalType="","",1)),1)),IF(TabData1[Date]<=$F$2,TabData1[Date]))))

To simplify (OFFSET($J$2,0,0,COUNT(IF(ListAnimalType="","",1)),1)) you can use $J$2:$J$5
=SUMIFS(TabData1[Count],TabData1[Date],MAX(IF(TabData1[Animal Type]=$J$2:$J$5,IF(TabData1[Date]<=$F$2,TabData1[Date]))))

And it looks like this
=SUMIFS(TabData1[Count],TabData1[Date],MAX(IF({"Dog";"Cat";"Fish";"Dog";"Cat";"Pig";"Cat";0;0;0;0;0;0;0;0;0}={"Cat";"Dog";"Fish";"Pig"},IF(TabData1[Date]<=$F$2,TabData1[Date]))))

Like I said, I want one formula that will take each Animal Type find the latest date from a specified cell and return the sum for each Animal Type then sum them all up.


text:
Q: Kendo UI - Texfield not showing in MultiSelect when Value is 0 I'm using Kendo Multiselect for angular 2.
here's my template code:
<kendo-multiselect #groupingsDropdown
                   [data]="fixedData.PossibleValuesForGroupingsAndSortings"
                   [filterable]="true"
                   [textField]="'Name'"
                   [valueField]="'Type'"
                   [value]="definitionDetails.Groupings"
                   (valueChange)="setGroupingsArray(groupingsDropdown.value)">

</kendo-multiselect>

and here's my controller code:
public setGroupingsArray(values: any) {
    if (values) {
        if (values.length <= 3) {

            this.definitionDetails.Groupings = values;
            this.setGroupBreakArray();
            console.log(this.definitionDetails.Groupings);

        } else {
            this.definitionDetails.Groupings = this.definitionDetails.Groupings.map(item => item);
        }
    }
}

It works great, however I found an error. when my valueField equals 0, it doesn't show the object in the box, however it will show that it's been selected.

voornaam has a valueField = 0, and while it still correctly adds it to my this.definitionDetails.Groupings it's not showing it in the MultiSelect (it only shows the user selected it). When I change [valueField]="'Type'" to [valueField]="'Name'" it does show it in my MultiSelect.
Any fix for this?


text:
Q: jQuery event attached to one element sharing the same class I am trying to find a good way to attach an event to a specific element of the DOM. This element shares the same class than others (real case: generating 20 divs by looping through a DB for example).
In order to make it as simple as possible, I created a JSfiddle available here:
jsfiddle.net/1a27t3u4/
the event is simple and just adds a class to the specific div:

$('.bouton').click( function(){
  $('.mother').addClass('red');
});
.mother
{
 width: 400px;
 height: 100px;
 margin-top: 20px;
 margin-left: auto;
 margin-right: auto;
 border: 2px solid red;
 text-align: center;
}

.red
{
     background: red;
}

HTML:

     <button class="bouton"> Click me! </button>

     <button class="bouton"> Click me! </button>

     <button class="bouton"> Click me! </button>

     <button class="bouton"> Click me! </button>

     <button class="bouton"> Click me! </button>

Basically, all I want to know is how I can color the div containing the button I clicked and not all the divs by using class tags and not id tags.
I've tried adding stopPropagation() or return false at the end of the script without any success :(

A: Instead of targeting all the elements with the class of .mother, use the keyword this to refer to the element being clicked on, and select its parent with .parent():
$('.bouton').click( function(){
    $(this).parent().addClass('red');
});

jsFiddle example

A: Use the jquery .closest() function:
$('.bouton').click( function(){
    $(this).closest('.mother').addClass('red');
});

This will search up the DOM and find the closest element that matches the given selector.  See the working fiddle:  http://jsfiddle.net/1a27t3u4/3/


text:
Q: Pass 1 sync and 1 async variables to next async function I am using mongodb realm with a simple custom query function to return DB data
  function mongo(data) {
    return fetch(
      apiurl,
    {
      method: "POST",
       headers: {
          "Content-Type": "application/json",
       },
        body: JSON.stringify(data),
       }
    )
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      console.log("Success:", data);
      return data;
    })
    .catch((error) => {
      console.error("Error:", error);
    });
  }

  mongo({
    collection: "metadata",
    action: "find",
    criteria: { query: {}},
  }).then((metadata) => {
    for (var i = 0; i < metadata.length; i++) {
      var oneMeta= metadata[i];
      var subjectName = oneMeta.name;
      var subjectCode = oneMeta.code;
      var blockHTML =
        `

        ` + subjectName + `
        ` + subjectCode + `

`;
      var oneSubject = document.createElement("div");
      oneSubject.id = "sub_"+subjectCode
      oneSubject.innerHTML = blockHTML;
      subjectOutput.appendChild(oneSubject);
    }
  });

I was trying to do another mongo({collection: "actualData", action: "count", criteria: { query: {subjectId: XXX}}}) query for each metadata where XXX would be subjectCode from metadata[i]
The goal is to append another count to the DIV created above using its id, where the count is the result of the second mongo function.
I was only able to do it without looping metadata.length
I need to do the next function for every time in the loop, while using i and metadata
Any help appreciated!

A: Just map your metadata to an array of mongo promises, await all of them, then the count result will be in the same position of the array:

mongo({
    collection: "metadata",
    action: "find",
    criteria: { query: {}},
  }).then(async (metadata) => {
    const counts = await Promise.all(metadata.map((oneMeta) => {
      return mongo({collection: "actualData", action: "count", criteria: { query: {subjectId: oneMeta.subjectCode}}});
    }));
    for (let i = 0; i < metadata.length; i++) {
      const count = counts[i];
      const oneMeta = metadata[i];
      const subjectName = oneMeta.name;
      const subjectCode = oneMeta.code;
      var blockHTML =
          `

          ` + subjectName + `
          ` + subjectCode + `
          ` + count + `

`;
      var oneSubject = document.createElement("div");
      oneSubject.id = "sub_"+subjectCode
      oneSubject.innerHTML = blockHTML;
      subjectOutput.appendChild(oneSubject);
    }
})


text:
Q: Why isn't text box expanding to fit text I have a VStack that contains multiple lines of text, but for some reason the second line of text won't expand to fit the frame

My code is shown below - it's actually pretty simple.
        VStack(alignment: .leading) {
            Text("PS5").font(.custom("Kufam Regular", size: 24))
                .foregroundColor(CustomColor.lightGrey)
                .padding(.top, 10.0)

            Text("A Sony Playstation 5").font(.custom("Kufam Regular", size: 15))
                .foregroundColor(CustomColor.lightGrey)
                .padding(.top, 10.0)

            Text("PS5").font(.custom("Kufam Regular", size: 15))
                .foregroundColor(CustomColor.lightGrey)
                .padding(.vertical, 10.0)

            Spacer()
        }
        .frame(width: .infinity, height: 120.0)
        .padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 90))

A: This is because of the .trailing padding on your entire VStack. Notice how no text goes beyond. Remove the padding, reduce its size, or scale it to fit the size given. Take a look at the example code below - this removes the .padding on that trailing edge.
 VStack(alignment: .leading) {
            Text("PS5").font(.custom("Kufam Regular", size: 24))
                .foregroundColor(CustomColor.lightGrey)
                .padding(.top, 10.0)

            Text("A Sony Playstation 5").font(.custom("Kufam Regular", size: 15))
                .foregroundColor(CustomColor.lightGrey)
                .padding(.top, 10.0)

            Text("PS5").font(.custom("Kufam Regular", size: 15))
                .foregroundColor(CustomColor.lightGrey)
                .padding(.vertical, 10.0)

            Spacer()
        }
   .frame(width: .infinity, height: 120.0)
        .padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10))
//Important parts. Either reduce the frame size, or reduce the padding like here.


text:
Q: The relation between Weyl character formula and Frobenius characteristic map Let $\mathfrak{gl}(n)$ be the general linear Lie algebra of rank $n$, and $\mathfrak{S}_d$ be the symmetric group of rank $d$. It is well-known that the Schur-Weyl duality provide a equivalence between $\mathfrak{S}_d$-mod and a subcategory of category of finite-dimensional modules over $\mathfrak{gl}(n)$.
Furthermore, for a given partition $\lambda$ of $d$, Weyl character formula says that the character of the simple $\mathfrak{gl}(n)$-module $V(\lambda)$ of highest weight is Schur function $s_{\lambda}$, while the Frobenius character formula says that the Frobenius characteristic map of the Specht module $S^{\lambda}$ is the Schur function $s_{\lambda}$ as well.
$\textbf{My Question:}$  With Weyl character formula and Frobenius character formula, how can derive one from the other? Thanks very much in advance!


text:
Q: Issue running c++ code from 2013 using Clion [I have very little experience with c++, and this is the first time I use it after more than 10 years].
I need to run some c++ code from 2013, and I am having issues doing so. I am using Clion on OSX Monterey (M1 Silicon chip). If I run a very simple script (main.cc below), I get the error
Undefined symbols for architecture arm64:
  "Hair::read(char const*, bool)", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture arm64

Is this because the code I am trying to run was written in a different version of c++ than the one I am using to compile it? Or is it an issue related to the architecture I am using? Thanks!
The dataset and the original code is available here.
main.cpp
#include <opencv2/opencv.hpp>
#include <iostream>
#include <Hair.h>

using namespace cv;
using namespace std;

int main() {
    const char *path = "strands00001.data";
    Hair hair;
    hair.read(path, false);
    return 0;
}

Here is the function I'm trying to call:
bool Hair::read(const char *filename, bool flip_strands /* = false */)
{
    bool ok = ends_with(filename, ".data") ?
        read_bin(filename) : read_asc(filename);

    if (!ok)
        return false;

    if (flip_strands) {
        int nstrands = strands.size();
        for (int i = 0; i < nstrands; i++)
            reverse(strands[i].begin(), strands[i].end());
    }

    // Look for a .xf file, and apply it if found
    xform xf;
    if (xf.read(xfname(filename)))
        apply_xf(xf);

    return true;
}

CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project( OpenCVTest )
find_package(OpenCV REQUIRED)
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable( OpenCVTest main.cpp )
target_link_libraries( OpenCVTest  ${OpenCV_LIBS})

A: The problem has nothing to do with architecture or the version of C++. The definition of Hair::read couldn't be found because your CMakeLists.txt wasn't compiling the file that contained it. You need to tell it to compile Hair.cpp in addition to main.cpp, like this:
add_executable( OpenCVTest main.cpp Hair.cpp )


text:
Q: TypeError: Cannot set property 'key' of undefined class Discount {
    discount;
    constructor() {
        this.key = '';
        this.code = '';
        this.discountValue = 0;
    }
    checkData(searchCode) {
        fetch('discount.json').then ((response) =>{
            return response.json()
        }).then ((obj)=>{
           Object.keys(obj).forEach(function(key) {
                obj[key].forEach((data)=> {
                  // console.log(data.code);
                   // console.log(obj[key]);
                    if (data.code === searchCode) {
                        console.log(key);
                        console.log(data.code);
                        console.log(data.discount);
                       this.key = key;
                       this.code = data.code;
                       this.discountValue = data.discount;
                    }
                });
           });

            console.log(this.key);
            console.log(this.code);
            console.log(this.discountValue);

        }).catch((error)=>{
            console.error('Wrong');
            console.error(error);
        });
    }

}

document.addEventListener("DOMContentLoaded", () =>{
    document.getElementById('calcDiscount').addEventListener('click', ()=>{
        const codeInput = document.getElementById('codeInput').value.toUpperCase();
        const myName = new Discount();

        myName.checkData(codeInput);
    });
});

    at main.js:20
    at Array.forEach (<anonymous>)
    at main.js:13
    at Array.forEach (<anonymous>)
    at main.js:12
(anonymous) @ main.js:34
Promise.catch (async)
checkData @ main.js:32
(anonymous) @ main.js:47

Why this code does not work? please help me, i can't understand. Please explain to me the solution of this problem if you know how. It's a discount, taking data from the json, it should return key, code and the value, but does not work.

A: this inside the forEach loop i:e this.key = key, is not pointing to the Discount class instance.
The normal function as callback will create it's own this i:e Object.keys(obj).forEach(function(key) {
Instead use arrow based function, which do not have it's own this and will refer to the this from the outer immediate scope, which is pointing to the class instance.
Object.keys(obj).forEach(() => (key) {.
checkData(searchCode) {
    // here `this` points to the class instance
    fetch('discount.json').then ((response) =>{
        // this is retrieved from the outer scope, which is class instance
        return response.json()
    }).then ((obj)=>{
       // this is retrieved from the outer scope, which is class instance
       Object.keys(obj).forEach(function(key) {
           // The normal callback function, will create it's own this, so `this` won't point to the class instance.
            obj[key].forEach((data)=> {
                // Here, this refer to newly created `this` from the immediate enclosed function.
                if (data.code === searchCode) {
                    console.log(key);
                    console.log(data.code);
                    console.log(data.discount);
                   this.key = key;
                   this.code = data.code;
                   this.discountValue = data.discount;
                }
            });
       });

A: Try Using ES6 arrow functions.
class Discount {
    discount;
    constructor() {
        this.key = '';
        this.code = '';
        this.discountValue = 0;
    }

    checkData = (searchCode) => {
        fetch('discount.json').then (res=>res.json()).then ((obj)=>{
           Object.keys(obj).forEach((key) => {
                obj[key].forEach((data)=> {
                  // console.log(data.code);
                   // console.log(obj[key]);
                    if (data.code === searchCode) {
                        console.log(key);
                        console.log(data.code);
                        console.log(data.discount);
                       this.key = key;
                       this.code = data.code;
                       this.discountValue = data.discount;
                    })
                });
           });

            console.log(this.key);
            console.log(this.code);
            console.log(this.discountValue);

        }).catch((error)=>{
            console.error('Wrong');
            console.error(error);
        });
    }

}

A: Try this below :
You need to use async await since the call is asynchrounous , the execution doesnt wait for your response and thats why you are getting undefined in your Object.keys(obj)
async checkData(searchCode) {
        await fetch('discount.json').then ((response) =>{
            return await response.json()
        }).then ((obj)=>{
           Object.keys(obj).forEach(function(key) {
                obj[key].forEach((data)=> {
                  // console.log(data.code);
                   // console.log(obj[key]);
                    if (data.code === searchCode) {
                        console.log(key);
                        console.log(data.code);
                        console.log(data.discount);
                       this.key = key;
                       this.code = data.code;
                       this.discountValue = data.discount;
                    }
                });
           });

            console.log(this.key);
            console.log(this.code);
            console.log(this.discountValue);

        }).catch((error)=>{
            console.error('Wrong');
            console.error(error);
        });
    }


text:
Q: shallow and deep cloning in C# .net class CloneExample : ICloneable
{
    private int m_data ;
    private double m_data2 ;

    public object Clone()
    {
        return this.MemberwiseClone();
    }

    public CloneExample()
    {

    }

    public CloneExample(int data1, int data2)
    {
        m_data = data1;
        m_data2 = data2;
    }

    public override string ToString()
    {
       return String.Format("[d1,d2] {0} {1}", m_data, m_data2);
    }
}
class Program
{
    static void Main(string[] args)
    {
        CloneExample aEx = new CloneExample(10,20);
        CloneExample aEx2 = (CloneExample)aEx.Clone();

        Console.WriteLine("the first object value is {0}", aEx.ToString());
        Console.WriteLine("the first object value is {0}", aEx2.ToString());

        Console.Read();

    }
}

*

*I wrote a exmaple to understand how shallow cloning works.In the above example in the
clone method I am calling this.MemberWiseClone() , since in the class I have not implemented the memeberwiseclone . who will provide the default implementation?

A: Memberwiseclone first create instance probably using Activator.CreateInstance which then iterates over all the fields within the type and set the value to the corresponding member/field.
But I would rather not use ICloneable at all. If I needed to use Cloning I use BinaryFormatter to serialize an object graph then deserialize it so that I would get new deeply cloned instance.

A: Every object inherits from "Object", even if you didn't specify.
So it's there.

A: The default implementation of MemberwiseClone comes from the Object class in .NET.
The MemberwiseClone method uses reflection to do the job.

A: That's provided by the base Object class. Check the documentation here.


text:
Q: Pharo gitFileTree: how to block commit (stage only) How can I config gitFileTree/Monticello don't commit on project save ?
I have some out-of-tree files in local git repo (autogenerated sources)
and I want to do commit manually:

*

*first stage all changes in Smalltalk system, then

*stage all external files and

*commit all changes at once

A: Say you want to "export" package called Somewhere to GitFileTree repository called breaking-mcz.
"get the package"
package := 'Somewhere' asPackage.

"find the repo"
repo := MCRepositoryGroup default repositories detect: [ :each | (each isKindOf: MCFileTreeGitRepository) and: [ each location includesSubstring: 'breaking-mcz' ] ].

"working copy is the current in-image state"
workingCopy := package mcWorkingCopy.

"this will create an in-memory only version; the message doesn't matter"
pseudoVersion := workingCopy newVersionWithMessage: 'Message will not be used' in: repo.

"this will file-out the current state to disk, and `git add` it to git index (no commit)"
repo internalStoreVersion: pseudoVersion.

Note 1: keep in mind that the way GitFileTree works is that it clears the old code on the disk and dumps everything again, so if you already have some uncommitted modifications in the code (on the disk), you should git stash them first.
Note 2:  I am assuming you are using metadata-less GitFileTree (which has been the default for a year or so), otherwise I am not sure what would happen to history/ancestry
Note 3: This is not a typical use case, so there's no GUI for this, but we could consider in Iceberg at some point

A: You could simply add a filetree repository which will just store the package to disk and not do any git versioning. Then you commit that manually. This actually used to be the workflow before GitFileTree.


text:
Q: Resx resource files updating without recycling app pool we heavily rely on resx files for content and translations which work well. However we would like to enable changing content without users losing their sessions by having the app pool recycled. Is there a way to do this, or is there a better approach in which we can still use the resx files.
Cheers


text:
Q: SQL: How to build complex query from 3 tables I have 3 tables with data and I need to select sum of sales (SalesAmount) per country(CountryRegionName) in 2014 fiscal year (FiscalYear).
The first table is Geography.
There are data with CountryRegionName and also SalesTerritoryKey (number which means some districts of CountryRegionName).
The second table, anong others, has information about OrderDateKey, SalesTerritoryKey and SalesAmount. The OrderDateKey field include records in the following format: "20130828".
The third table, among others, has fields DateKey (in the same format as OrderDateKey from second table and FiscalYear (format like: "2012").
I dont't understand how I can select needed data using all 3 tables because second table has information about year (OrderDateKey) in different format which third table supports in field FiscalYear.
Currently I stopped which following statement:
`SELECT CountryRegionName, SUM(SalesAmount) FROM FirstTable  GROUP BY SalesTerritoryKey`

I know that we need to join all tables and make some subqueries but don't understand how to compare dates and countries which are in different formats.
Thanks for your help!

A: SELECT t1.CountryRegionName, SUM(t2.SalesAmount)
FROM ThirdTable  t3
LEFT JOIN SecondTable t2
ON t3.DateKey = t2.OrderDateKey
LEFT JOIN FirstTable t1
ON t1.SalesTerritoryKey = t2.SalesTerritoryKey
WHERE t3.FiscalYear = "2014"
GROUP BY t1.CountryRegionName


text:
Q: Check if value of an array is present in another array I am trying to check if value of an array $spam is present in array $get_mail.
I have following code, but it doesnt seem to work or I dont understand it properly.
$spam_exists = !array_diff($spam, $get_mail);

if ($spam_exists !== FALSE) { ... }

Any idea why this doesnt work?
Thank you for any reply.

A: Use the array_intersect function.
$result = array_intersect($spam, $get_mail);

Which will return the values in both arrays as an array, or an empty array if there are no shared results.
So rather than using !array_diff($X,$Y) you could use !empty(array_intersect($X,$Y)) or simply if(array_intersect($X,$Y))


text:
Q: Need to choose ASM performance for production database We have a 1.5 TB of data (nonasm) and we plan to move into ASM by choose normal redundancy.
Normal Redundancy ==> Two Way Mirroring , So we need 3TB data storage for 1.5TB data including mirroring(SAN disk).
Please clarify below:
A) If we choose single RAW disk 3TB.
How many disk group we can split?
either each 500gb into 6 parts? (1 disk group)
This will be efficient for asm operation?
If the failure group we need to specify mandatory?
In our case, we have a single 3TB disk for storage, so no need to specify failure group right?
From blogs,
((For small numbers of disks (<20) it is usually best to use the default Failure Group creation that puts every disk in its own Failure Group))
so It can take by default itself. So no need to specify right?
B) If we have separate two disks each 1.5 TB
How many disk group we can split, either each 500gb into 3 parts?
(Total 2 disk group a and b)
If the failure group we need to specify mandatory?
Shall we specify manually failure group of A disk group is B and failure group of B is A?
Its a better performance?
If you cause a failure group specification it causes a spindle failure?
Either A or B case, which one is better performance approach for I/O operation in ASM?

A: ASM is not magic.
Each disk has a maximum number of IOPS it can support.  Each disk has a maximum throughput.  The more spindles (HDDs) you have, the more I/O you can get.  If one disk decides to take a permanent vacation and you don't have data on another disk.... I really hope you have viable tested backups.
From my tests, partitioning a single HDD into multiple LUNs and then using those LUNs for ASM will have a negative effect (albeit, ~-1%).
If you want performance, you will buy 6+ 500GB HDD (or SSD).  Each disk will have 1 LUN - the whole thing.  ASM will take care of the stripe and mirror.

A: *

*You have a storage with several disks.

*You then group them in a single logical entity which is a disk pool, or whatever it is called by the vendor of the storage.

*Then you create multiple small logical entities called virtual disks, volumes, whatever, then present them to your host.

*Then again, you group these small disks again into a single logical entity called an ASM diskgroup.
What's the point of step 3 + 4? Whats the point of logically splitting your disks into small virtual disks then grouping them again?
Just create 2 x 1.5TB disks, done.

A: I think you should read the Oracle Admin Guide.
One of the points there:

The number of LUNs (Oracle ASM disks) for each disk group should be at least equal to four times the number of active I/O paths. For example, if a disk group has two active I/O paths, then minimum of eight LUNs should be used. The LUNs should be of equal size and performance for each disk group.
An I/O path is a distinct channel or connection between storage presenting LUNs and the server. An active I/O path is an I/O path in which the I/O load on a LUN is multiplexed through multipathing software.

Please note, that in older versions of the documentation a minimum of four disks/LUNs per disk group was recommended, so 18c is more strict.
You need to decide who is doing the redundancy. If your SAN/Storageteam does it, then use external redundancy.
Partitioning a disk (SAN or local) and feeding these partitions to ASM is really a bad idea for real servers, but it's fine for playing around within the desktop virtualization of your choice.

A: We choose a 3TB for a diskgroup.(Normal redundancy for 1.5TB data)
Below disk range:
1.5 TB * 1 = 1 Disks
500 GB * 3 = 3 Disks
For an even size, we can give as 500 Gb for the diskgroup consist of 4 disks.
So in this case, we split one 1.5TB disk into 3 parts and will provide a normal redundancy.
we did not split all the 4 disks. 3 disks are as same, only one disk we split into parts for the same size. Is this ok?
Please confirm.


text:
Q: Excel macro crashes after running for a few minutes My code runs for about 5min and the goes into recovery error/message. I have posted 3 Call macros but have 40 in the code.
During the macro the cells need to calculate and I tried a time delay to help but no good.
 Private Sub Worksheet_calculate()

    If Range("$be8").Value = 1 Then
    Application.EnableEvents = True
    Call Macro1
    Application.EnableEvents = False
    End If
    If Range("$bf8").Value = 1 Then
    Application.EnableEvents = True
    Call Macro2
    Application.EnableEvents = False
    End If
    If Range("$bg8").Value = 1 Then
    Application.EnableEvents = True
    Call Macro3
    Application.EnableEvents = False
    End If

 Sub Macro1()
'
'

     Macro1 Macro
    '

    '

            Sheets("Calc. 1").Select
            Rows("11:11").Select
            Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
            Application.Wait (Now + TimeValue("0:00:05"))
            Rows("7:7").Select
            Selection.Copy
            Rows("11:11").Select
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                :=False, Transpose:=False
            Range("B1").Select
            Application.CutCopyMode = False
            ActiveCell.FormulaR1C1 = ""
            Range("B2").Select
            Sheets("Calc.").Select
            Range("A7:Q50002").Select
            Selection.Copy
            Range("A3").Select
            ActiveSheet.Paste
            Calculate
            Range("AZ3").Select
            Selection.Copy
            Range("BA3").Select
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                :=False, Transpose:=False
            Range("A1").Select
            Application.CutCopyMode = False
            ActiveCell.FormulaR1C1 = ""
            Range("B1").Select
            Workbooks.Add
            DoEvents
        End Sub

        Sub Macro2()
        '
        ' Macro2 Macro
        '

        '
            Sheets("Calc. 1").Select
            Rows("11:11").Select
            Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
            Application.Wait (Now + TimeValue("0:00:05"))
            Rows("7:7").Select
            Selection.Copy
            Rows("11:11").Select
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                :=False, Transpose:=False
            Range("B1").Select
            Application.CutCopyMode = False
            ActiveCell.FormulaR1C1 = ""
            Range("B2").Select
            Sheets("Calc.").Select
            Range("A8:Q50002").Select
            Selection.Copy
            Range("A3").Select
            ActiveSheet.Paste
            Calculate
            Range("AZ3").Select
            Selection.Copy
            Range("BA3").Select
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                :=False, Transpose:=False
            Range("A1").Select
            Application.CutCopyMode = False
            ActiveCell.FormulaR1C1 = ""
            Range("B1").Select
            Workbooks.Add
            DoEvents
        End Sub

        Sub Macro3()
        '
        ' Macro3 Macro
        '

        '
            Sheets("Calc. 1").Select
            Rows("11:11").Select
            Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
            Application.Wait (Now + TimeValue("0:00:05"))
            Rows("7:7").Select
            Selection.Copy
            Rows("11:11").Select
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                :=False, Transpose:=False
            Range("B1").Select
            Application.CutCopyMode = False
            ActiveCell.FormulaR1C1 = ""
            Range("B2").Select
            Sheets("Calc.").Select
            Range("A9:Q50002").Select
            Selection.Copy
            Range("A3").Select
            ActiveSheet.Paste
            Calculate
            Range("AZ3").Select
            Selection.Copy
            Range("BA3").Select
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                :=False, Transpose:=False
            Range("A1").Select
            Application.CutCopyMode = False
            ActiveCell.FormulaR1C1 = ""
            Range("B1").Select
            Workbooks.Add
            DoEvents
        End Sub

A: First, this is just a big pack of recorded macros, and therefore nearly unreadable, as hinted by Matt Webb in its excellent comment. That being said, I went to do some analysis.
The macros are strictly the same, besides the column of the Range("A7:Q50002").Select, which varies from 7 to 9 (and probably up to 46, if you really have 40 of those). Time to make a proper sub with a parameter :
Private Sub Worksheet_calculate()
    If Range("$be8").Value = 1 Then
    Application.EnableEvents = True
    Call Macro(myRow)
    Application.EnableEvents = False
    End If
    If Range("$bf8").Value = 1 Then
    Application.EnableEvents = True
    Call Macro(myRow)
    Application.EnableEvents = False
    End If
    If Range("$bg8").Value = 1 Then
    Application.EnableEvents = True
    Call Macro(myRow)
    Application.EnableEvents = False
    End If
End Sub

 Sub Macro(myRow)
    Sheets("Calc. 1").Rows("11:11").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Application.Wait (Now + TimeValue("0:00:05"))
    Rows("7:7").Copy
    Rows("11:11").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("B1").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = ""
    'Range("B2").Select
    Sheets("Calc.").Range("A" & CStr(myRow) & ":Q50002").Copy
    Range("A3").Select
    ActiveSheet.Paste
    Calculate
    Range("AZ3").Copy
    Range("BA3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("A1").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = ""
    'Range("B1").Select
    Workbooks.Add
    DoEvents
End Sub

it'still ugly, but now, you just have 1 main procedure instead of 40, and I cleaned a little bit. I also did comment the useless selects.
Next question : what does it do? Seems like it

*

*inserts the row 11, then copies the row 7 into. That one shall not be problematic.

*Copies a specific cell from another sheet to the current sheet. Well, why not.

*Calculates. Here we have a problem. I have no clue of your calculations, and there very well might be circular things here, or insane amounts of calculations to do. Especially when I see hard-coded values going to the 50000th row... The wolf may hide here. Depends on your worksheet. This is my first suspect.

*Copy another cell in the main sheet. No risk here.

*Add an empty workbook. Without anything. Hum, are you sure? If your 40 values are positive, you dynamically open 40 workbooks, without naming them, or putting any data in them??? This is my second and last suspect.

Now, you have to troubleshoot yourself to know which suspect is guilty. For that, you can add breakpoints on a few strategic lines of the macro, to see what takes time(my bet on the calculate, but I may be wrong). Especially before & after the calculate & the Workbook.add
But ask yourself is everything I listed is useful, especially the calculate part, and especially the workbook.add part. Your macro might very well flood the computer memory with all those workbooks open in memory that are still useless.


text:
Q: Change layout of a ConfirmDialog depending on users choises I have a program which registers Cows, Dogs and Cats of the superclass Animal into a DataCollection of some sort. The user presses a button "Add animal" and from there I would like to open a ConfirmDialog with a JPanel as parameter that first only had 3 checkboxes: Cow[] - Dog[] - Cat[] and depending on what the user picks add the appropriate textfields for the data this type of animal needs.
Is there a way to add a listener for when a checkbox gets "checked" and then just add the new fields that i want for that type, or is there a smarter way to do this?

A: For each animal type, create a panel with specialized input components, and place all three panels in a separate JPanel that uses a CardLayout.  CardLayout displays one and only one of its children at any given time;  each child is identified by a String identifier of your choosing, which you must specify when you add the child.
This is better than adding components dynamically, because CardLayout will always make sure a container's preferred size is large enough to accommodate all of the children, so the dialog won't shuffle things around when you change which components are visible.
private static final String COW_CARD_ID = "cow";
private static final String DOG_CARD_ID = "dog";
private static final String CAT_CARD_ID = "cat";

void buildConfirmDialog() {

    JPanel cowFieldsPanel = new JPanel();
    // Add cow-specific components here

    JPanel dogFieldsPanel = new JPanel();
    // Add dog-specific components here

    JPanel catFieldsPanel = new JPanel();
    // Add cat-specific components here

    final CardLayout cardLayout = new CardLayout();
    final JPanel animalSpecificFieldsPanel = new JPanel(cardLayout);
    animalSpecificFieldsPanel.add(cowFieldsPanel, COW_CARD_ID);
    animalSpecificFieldsPanel.add(dogFieldsPanel, DOG_CARD_ID);
    animalSpecificFieldsPanel.add(catFieldsPanel, CAT_CARD_ID);

    JRadioButton cowButton = // ...
    JRadioButton dogButton = // ...
    JRadioButton catButton = // ...

    cowButton.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent event) {
            if (event.getStateChange() == ItemEvent.SELECTED) {
                cardLayout.show(animalSpecificFieldsPanel, COW_CARD_ID);
            }
        }
    });

    dogButton.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent event) {
            if (event.getStateChange() == ItemEvent.SELECTED) {
                cardLayout.show(animalSpecificFieldsPanel, DOG_CARD_ID);
            }
        }
    });

    catButton.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent event) {
            if (event.getStateChange() == ItemEvent.SELECTED) {
                cardLayout.show(animalSpecificFieldsPanel, CAT_CARD_ID);
            }
        }
    });

    ButtonGroup buttonGroup = new ButtonGroup();
    buttonGroup.add(cowButton);
    buttonGroup.add(dogButton);
    buttonGroup.add(catButton);
}

It's probably worth mentioning that when expecting a user to choose exactly one item from a list of many items, you should use radio buttons, not checkboxes.  In Swing, JRadioButtons are almost always added to a single common ButtonGroup so they will have that one-of-many functionality.


text:
Q: How to append custom code to the generated service worker file I'm using Webpack and swPrecache. swPrecache generates a service-worker.js file for me and I now want to append custom code to the generated file.
I created a Webpack plugin that appends the babel transformed code to the service-worker.js file, like so:
swPrecache.write(filePath, options, (function(err) {

  // If we want to append an additional file.
  if (options.appendFile) {
    var sync = fs.readFile(options.appendFile, (error, code) => {
      if (error) {
        throw error;
      }
      let transformed = babel.transform(code, options.babelConfig || {});
      fs.appendFile(filePath, transformed.code);
    });
  }

  callback(err);
}));

This however does not include the code to make require() work in the file i'm appending. I believe I need to use Webpack to generate the service-worker.js file but i'm unsure how to do that, possibly via a custom entry point?

A: To include your custom script into generated serviceWorker, recommended way is to use the importScripts option in sw-precache config.You can find more details here.


text:
Q: schedule a php page which calls a stored proc in mysql to run every x seconds i have a stored procedure in mysql, accessed by a php page. this page is not visible to the visitor (as this page will not any of the links in the site). this php page will just reside in the server. i am wondering if i can have the php page automatically run/loaded/.. every say 1minute by the server, so that the page will call the stored procedure every 1 minute.
i can have a scheduler run the stored proc, but since i would be doing a lot of other things using php page on the stored proc, i would like to have the php page to be scheduled for every 1minute.
is this possible? i may be wondering too much here! i do not know much about schedulers, may be thats y.
thanks!

A: PHP has a command-line executable, named php. You can schedule that to process a page. E.g. php myfile.php will run the file myfile.php. You can use the server's scheduling tools (linux cron, windows task scheduler) to run that command for you.

A: Add a cron job:
  $ crontab -e

To run the job every minute, inside the crontab, add the entry :
  * * * * * /usr/bin/php pathtoyourscript.php

The Wikiedia entry on Cron has the information about what each star means.


text:
Q: ArmDeploymentCollection Not in Azure.ResourceManager.Resources Namespace I am following the new Azure.ResourceManager SDK examples here.
I'm not seeing classes I'd expect to see in Azure.ResourceManager.Resources. Specifically, ArmDeploymentCollection and ResourceGroupResource doesn't have a GetArmDeployments() method.
Azure.ResourceManager installed is Azure.ResourceManager.1.0.0. I'm targeting .NET framework 4.8.
I've tried uninstalling/re-installing Azure.ResourceManager several times, but doesn't change anything.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.IO;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.KeyVault;
using System.Threading;
using Azure;
using Azure.Identity;
using Azure.Core;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Resources.Models;

    public static void Initialize()
    {
        try
        {
            // Authenticate
            var credentials = new DefaultAzureCredential();

            await RunSample(credentials);
        }
        catch (Exception ex)
        {
            Utilities.Log(ex);
        }

    }

    public static async Task RunSample(TokenCredential credential)
    {

        try
        {
            var deploymentName = "bradDeployment";
            var rgName = "rg-percipience-test-002";
            var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
            var templateJson = Utilities.GetArmTemplate("ArmTemplate.json");

            ArmClient armClient = new ArmClient(new DefaultAzureCredential());
            SubscriptionResource subscription = await armClient.GetDefaultSubscriptionAsync();
            ResourceGroupCollection rgCollection = subscription.GetResourceGroups();
            // With the collection, we can create a new resource group with an specific name
            AzureLocation location = AzureLocation.EastUS;
            ArmOperation<ResourceGroupResource> lro = await rgCollection.CreateOrUpdateAsync(WaitUntil.Completed, rgName, new ResourceGroupData(location));
            ResourceGroupResource resourceGroup = lro.Value;

            Utilities.Log("Created a resource group with name: " + rgName);

            // Create a deployment for an Azure App Service via an ARM
            // template.

            Utilities.Log("Starting a deployment for an Azure App Service: " + deploymentName);

            // First we need to get the deployment collection from the resource group
            ArmDeploymentCollection armDeploymentCollection = resourceGroup.GetArmDeployments();
            // Use the same location as the resource group
            // Passing string to template and parameters
            var input = new ArmDeploymentContent(new ArmDeploymentProperties(ArmDeploymentMode.Incremental)
            {
                Template = BinaryData.FromString(File.ReadAllText("storage-template.json")),
                Parameters = BinaryData.FromString(File.ReadAllText("storage-parameters.json"))
            });
            ArmOperation<ArmDeploymentResource> lro2 = await ArmDeploymentCollection.CreateOrUpdateAsync(WaitUntil.Completed, deploymentName, input);
            ArmDeploymentResource deployment = lro2.Value;

            Utilities.Log("Completed the deployment: " + deploymentName);
        }
        finally
        {
            try
            {
                Utilities.Log("Deleting Resource Group: " + rgName);

                await (await resourceGroups.StartDeleteAsync(rgName)).WaitForCompletionAsync();

                Utilities.Log("Deleted Resource Group: " + rgName);
            }
            catch (Exception ex)
            {
                Utilities.Log(ex);
            }
        }

    }

A: I resolved the issue by adding a reference to Azure.ResourceManager.Resources.dll. Not sure why this reference isn't added when the nuget package is installed.


text:
Q: Endless booting loop of MacBook Pro My Mac Book Pro 2011 17" recently started to endlessly boot, gets about 2/3s the way into booting then shuts down and starts booting again.
Will not accept the original disks. Will not restart in safe mode? Does this mean I need a new HD or something else?

A: It would be a good time to swap the HD for another startup system.
You could do that with a thumb drive startup disk that you or someone else setup already, and you could use a USB cable connected to any external drive that had this. You could probably get one online if you've never made one. You could pull that drive out and connect it to another Mac, then use Disk Utility on it. Here is an article with some helpful stuff.


text:
Q: Should I use mysqlnd over libmysql? I bought VPS from Hostgator to download mysqlnd (because I used a lot get_result method) but they said that they will delete libmysql and will install mysqlnd and also it will be my responsibility to maintain mysqlnd (I have no experience to maintaining it yet).
I want to learn what I will lose when they delete libmysql? What are the cons of mysqlnd? Why is it hard to maintain mysqlnd?

A:
what I will lose when they delete libmysql?

Nothing.

What is the cons of mysqlnd?

Didn't you say yourself that you're using get_result all over the site? Is it not enough benefit for you?

Why is it hard to maintain mysqlnd?

It's not. There is nothing to maintain.

I don't use PDO because it is slow a little bit

Oh, that nasty rumor again.
However, if mysqli functions are wrapped in a good helper library, there is nothing wrong with it.
But in case either mysqli or PDO are intended to be used raw, right in the code without any intermediate wrapper, then for a programmer PDO is the only choice. Yet I have to admit that for a regular PHP user mysqli is better because resembles the only way for database interaction they learned once and for all.


text:
Q: Listbox not opening handler I am trying to create a menu in a listbox format where user chooses an option and then another uiapp is shown with the info they selected. I am having an issue here that when I opened google gives me an error that says Error encountered. An expected error occurred. I think it has to do with the setId part, if I remove one of the setId's the error doesnt happen. is this even possible?
 function doGet(e) {
 var app = UiApp.createApplication().setTitle("Services");
 var dropDownList = app.createListBox().setName('list').setId('list');
 var infoLabel = app.createLabel('Scroll around to select the service   desired').setId('infoLabel');
 var panel = app.createVerticalPanel();
 //addItem fills the list
 dropDownList.addItem("Option 1").setId("add");
 dropDownList.addItem("Option 2");
 panel.add(dropDownList);
 panel.add(infoLabel);
 app.add(panel);
 var info = app.getElementById("add");
 var handler2 = app.createServerHandler('display2');
 info.addClickHandler(handler2);

 app.add(dropDownList);
 app.add(infoLabel);
 var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
 spreadsheet.show(app);
}

 function display2(e) {
 var app = UiApp.createApplication();
  var html = app.add(app.createHTML("

You have selected this option
")).setHeight(220).setWidth(220);

 var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
 spreadsheet.show(app);
 return app;
 }

A: Are you deploying this as a web app or a script within a Spreadsheet?
If you are deploying this as a web app, then SpreadsheetApp.getActiveSpreadsheet() will not work - replace it with SpreadsheetApp.openById(id) where id is your spreadsheet ID which you will find in the URL when you open the file in the browser.
If you want to deploy this w/in a spreadsheet through a menu item or a simple button, then that works as is.
I was able to just copy paste your code and get the listbox part working fine -
https://docs.google.com/spreadsheet/ccc?key=0AkJNj_IM2wiPdHRYQThlaGVVSk04R052ZGNqclhEZWc#gid=0

Update -
I now understand what you are trying to do. Couple of things - you want to make sure you are adding a callback element via handler.addCallbackElement(myWidget) otherwise, you will not be able to read the value of the element. Second thing is that you don't need a server handler on each option in a dropdown list. Just having one handler will fire it for every change and you'll be able to get the option you selected.
I've cleaned up the code here below and also updated the spreadsheet to use this code.
function showUI() {
  var app = UiApp.createApplication().setTitle("GeekSquad Services");

  var infoLabel = app.createLabel('Scroll around to select the service desired');

  var dropDownList = app.createListBox().setName('list').setId('list');
  dropDownList.addItem("Option 1");
  dropDownList.addItem("Option 2");
  //you can add as many options here manually or dynamically

  var handler = app.createServerHandler('dropDownCallback')
  handler.addCallbackElement(dropDownList);
  dropDownList.addClickHandler(handler);

  var panel = app.createVerticalPanel();
  panel.add(dropDownList);
  panel.add(infoLabel);
  app.add(panel);

  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  spreadsheet.show(app);
}

function dropDownCallback(e) {
  var app = UiApp.createApplication();
  var html = app.add(app.createHTML("You have selected this option " + e.parameter.list));

  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  spreadsheet.show(app);
}

Update #2 -
If you want to fork off and create different app instances thats easy (though its unclear why wouldn't just change panels).
    function dropDownCallback(e) {
      if(e.parameter.list === 'Option 1'){
        var app = UiApp.createApplication();
        var html = app.add(app.createHTML("Here for option!"));

        var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
        spreadsheet.show(app);
      }
      else if (e.parameter.list ==== 'Option 2'){
        //create and show other App here or whatever else
      }
      //refactor this better to not repeat code.
    }


text:
Q: Unknown MySQL server host After a php verison change i have the following error
Warning: mysqli::mysqli(): (HY000/2005): Unknown MySQL server host
'clouddb.myhost.gr:3306' (2) in
/var/www/vhosts/mywebside.gr/httpdocs/system/library/db/mysqli.php on
line 7Warning: DB\MySQLi::__construct(): Couldn't fetch mysqli in
/var/www/vhosts/mywebside.gr/httpdocs/system/library/db/mysqli.php on
line 10Warning: DB\MySQLi::__construct(): Couldn't fetch mysqli in
/var/www/vhosts/mywebside.gr/httpdocs/system/library/db/mysqli.php on
line 10 .

And i cant understand what is the problem

A: You might be passing the clouddb.myhost.gr:3306 all together, on the mysqlcli, the port have its own parameter:
mysql:host=clouddb.myhost.gr;port=3306;

Related question:
SQLSTATE[HY000] [2005] Unknown MySQL server host 'mysql1.alwaysdata.com:3306' (2)


text:
Q: Installing Realm via CocoaPods I am trying to install Realm (Objective C) via Cocoapods.
However I keep getting the following error:
Pods/Realm/Realm/module.modulemap:1:18: Redefinition of module 'Realm'

Has anyone faced this problem?
I've tried downloading their CocoapodsExample project but I get the same error.

A: This is a known issue with CocoaPods 0.38.1, being tracked at https://github.com/CocoaPods/CocoaPods/issues/3886. In the meantime, you can gem install cocoapods -v 0.38.0 and run pod _0.38.0_ install to use CocoaPods 0.38.0, which does not have this issue.

This should now be fixed in CocoaPods 0.38.2.


text:
Q: How could an expression of enumeration type fall outside that enum's range? The C++ standard on enums says

For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type. Otherwise, the values of the enumeration are the values representable by a hypothetical integer type with minimal width M such that all enumerators can be represented. The width of the smallest bit-field large enough to hold all the values of the enumeration type is M. It is possible to define an enumeration that has values not defined by any of its enumerators. If the enumerator-list is empty, the values of the enumeration are as if the enumeration had a single enumerator with value 0.

A footnote then clarifies that

This set of values is used to define promotion and conversion semantics for the enumeration type. It does not preclude an expression of enumeration type from having a value that falls outside this range.

I understand these promotion and conversion semantics to be referring to what happens when you convert to and from enums as defined in 7.6.1.9.10

A value of integral or enumeration type can be explicitly converted to a complete enumeration type ... If the enumeration type does not have a fixed underlying type, the value is unchanged if the original value is within the range of the enumeration values, and otherwise, the behavior is undefined ...

When the footnote says that it does not preclude an expression of enumeration type from having a value outside of the enum's range, is it only referring to the possibility of undefined behavior, or is there some other way of having an expression of enum type that falls outside of the enum's range? It would seem odd to me for the standard to describe a scenario that's only possible through undefined behavior, because undefined behavior is unpredictable by definition.
My main goal is to learn how to better read and understand the C++ standard, so I'm not looking for practical advice on using c++ enums, but I welcome any tips on better understanding or citing the standard.


text:
Q: Is it possible to hook up a more robust HTML parser to Python mechanize? I am trying to parse and submit a form on a website using mechanize, but it appears that the built-in form parser cannot detect the form and its elements. I suspect that it is choking on poorly formed HTML, and I'd like to try pre-parsing it with a parser better designed to handle bad HTML (say lxml or BeautifulSoup) and then feeding the prettified, cleaned-up output to the form parser. I need mechanize not only for submitting the form but also for maintaining sessions (I'm working this form from within a login session.)
I'm not sure how to go about doing this, if it is indeed possible.. I'm not that familiar with the various details of the HTTP protocol, how to get various parts to work together etc. Any pointers?

A: reading from the big example on the first page of the mechanize website:
# Sometimes it's useful to process bad headers or bad HTML:
response = br.response()  # this is a copy of response
headers = response.info()  # currently, this is a mimetools.Message
headers["Content-type"] = "text/html; charset=utf-8"
response.set_data(response.get_data().replace("