How to redirect non admins to homepage if trying to view mysite.com/wp-admin/?

Question: I want all my users (contributors and authors too) but the admin to be redirected to the homepage if they try to view  mysite.com/wp-admin/.
Contributors and Authors must be able to add and edit posts as usual, along with others they've to be forced to be redirected...
I've already removed the link to the dashboard...
I've also tried some plugins but the one that gets closer (Remove Dashboard Access) redirects to main page but prevents the contributors and authors from adding, editing and deleting posts.
Thanks!
Answer: I been using this code for a while I think it was originaly on a plugin called wp block admin but this works. You just have tho change the required compatibility so that it does what you need, look at this
$required_capability = 'edit_others_posts';
$redirect_to = '';
function no_admin_init() {
    // We need the config vars inside the function
    global $required_capability, $redirect_to;
    // Is this the admin interface?
    if (
        // Look for the presence of /wp-admin/ in the url
        stripos($_SERVER['REQUEST_URI'],'/wp-admin/') !== false
        &&
        // Allow calls to async-upload.php
        stripos($_SERVER['REQUEST_URI'],'async-upload.php') == false
        &&
        // Allow calls to admin-ajax.php
        stripos($_SERVER['REQUEST_URI'],'admin-ajax.php') == false
    ) {
        // Does the current user fail the required capability level?
        if (!current_user_can($required_capability)) {
            if ($redirect_to == '') { $redirect_to = get_option('home'); }
            // Send a temporary redirect
            wp_redirect($redirect_to,302);
        }
    }
}
// Add the action with maximum priority
add_action('init','no_admin_init',0);

Comment: It's not the way it's meant to be done, but +1 for considering the `admin-ajax.php` file.
Answer: One addition: ALWAYS check to see if there is a logged in user otherwise you will prevent secured items from displaying on login screen:
function redirect_non_admin_user(){
    if ( is_user_logged_in() ) {
        if ( !defined( 'DOING_AJAX' ) && !current_user_can('administrator') ){
            wp_redirect( site_url() );  exit;
        }
    }
}
add_action( 'admin_init', 'redirect_non_admin_user' );

Thank you so much for offering this solution :-)
Comment: Perfect Answer!
Answer: There're only two things you need to check:

If the user is in the admin interface
If he got the capability or not

As long as we're using the template_redirect hook we don't have to check the login/register/password pages as the redirect will happen invisible to the user.
Here's the idea wrapped up as a little (mu-)plugin.
<?php
/**
 * Plugin Name: (#90535) Redirect Non-Admin users to the "Home"-page.
 * Description: Checks if we're in the admin UI and if the user has the admin only 'manage_options' capability
 * Version:     2013.03.12
 * Author:      Franz Josef Kaiser
 */
add_action( 'template_redirect', 'wpse90535_admin_denied' );
function wpse90535_admin_denied()
{
    is_admin()
    && ! current_user_can( 'manage_options' )
        and exit( wp_redirect( home_url(), 302 ) );
}

Comment: hehe I usually don't remember what I had for dinner 2 days ago, so I totally understand ;-)
Comment: Not sure exactly what OP was looking for but I'm now wondering when `is_admin()` is true within `template_redirect`? (Maybe it's just too early in the morning for me to see that  ;-)
Comment: @birgire I have no idea … this answer is 4 years old :)
Answer: Unfortunately none of the above codes worked for me as they just redirected non admin to homepage even if I wanted authors and contributors to be able to add/edit and delete their posts...
I've ended removing the boxes in the dashboard and I solved (partially) my issue.
I added this in functions.php
function disable_default_dashboard_widgets() {

    remove_meta_box('dashboard_right_now', 'dashboard', 'core');
    remove_meta_box('dashboard_recent_comments', 'dashboard', 'core');
    remove_meta_box('dashboard_incoming_links', 'dashboard', 'core');
    remove_meta_box('dashboard_plugins', 'dashboard', 'core');

    remove_meta_box('dashboard_quick_press', 'dashboard', 'core');
    remove_meta_box('dashboard_recent_drafts', 'dashboard', 'core');
    remove_meta_box('dashboard_primary', 'dashboard', 'core');
    remove_meta_box('dashboard_secondary', 'dashboard', 'core');
}
add_action('admin_menu', 'disable_default_dashboard_widgets');

Comment: Oh, seems like we both misread your question... Take our answers, modify them and then try again. Or make your question more clear with A) where the login/registration/password should redirect too and B) what _exact_ page the user should get access too and to which one not.
Answer: I know this is still a old question but you can have a look.
function redirect_non_admin_user(){
    if ( !defined( 'DOING_AJAX' ) && !current_user_can('administrator') ){
        wp_redirect( site_url() );  exit;
    }
}

add_action( 'admin_init', 'redirect_non_admin_user' );

This checking is very IMPORTANT "!defined( 'DOING_AJAX' )" when you use admin ajax call in frontend.


How to create a serial key (Registration key)

Question: We're designing a PIC based system. We would like that users enter a serial key (registration key) like the one commonly found in desktop software. For our system, we will have the user's email address and/or his cellphone number. The system is a standalone device with a keyboard and display. The system will allow the user to pay by punching in a specific registration code that he purchased via SMS. The user will send a SMS to a server. The server would use the provided user's email or/and phone number and generate a unique registration key.
Does anyone has clues on how to get started?
Comment: From your current question, it's not clear at all what kind of system you want to design. Be more specific!
Comment: To clarify, you want a stand-alone device (your PIC, not network connected) to be able to accept a key and allow a user access to the device?  And the key is generated on a separate system using their email address and/or phone number?
Comment: Yes, the system is a standalone device with a keyboard and display. The system will allow the user to pay by punching in a specific registration code that he purchased via SMS. The user will send a SMS to a server. The server would use the provided user's email or/and phone number and generate a unique registration key.
Comment: @Nirupama, does the registration code ever expire? Also, if I acquire a registration key to use for one of these devices, should I now be able to use that key on any other deployed device?
Comment: @Nirupama, also, what do you mean by: "The system will allow the user to pay by punching in a specific registration code"?  But they've made a purchase via SMS already? They're paying for something twice?  How do they make the purchase for a registration code?
Answer: I am targeting this answer at what can realistically be achieved on a PIC microprocessor.
I would generate a random number on the PIC, the common way to do this is to use the A2D as a noise generator and repeatedly sample the LSB. Once you have this, append a check digit or two and display it to the user. The check digits will allow you (on the server that receives the text) to guard against billing the user for a miss-typed code.
On the server, take the users code, strip the check digits, run it through a Linear Feedback Shift Register that is pre-loaded with a secret value. Charge the user, if the payment clears, text back the output code.
Your PIC chip needs to know the secret too, and repeats the calculation. You might want to try Microchips CRC Generator hardware eg. AN1148 shows how to use the hardware LSFR. Load in the secret, then clock in the random challenge. Compare this to what the user keys in - a result that matches most likely means a purchase.
I'd have a supervisor mode if this is a kiosk, rather than single device, to allow the re-loading of another secret code, or pattern of LFSR taps, secured by physical access and store this in the NVRAM. This way you can at least change the encoding over time, or in response to a break. Add NVRAM counters to compare local purchases against server approvals to monitor slippage. Watch your wear-levelling though!
This is only as 'secure' as your secret and technique staying private. It would be relatively trivial for anyone who can dump a hex image from your machine to reverse the algorithm from the assembler, although presumably anyone with physical access has simpler techniques to get the product without paying. Similarly anyone willing to guess the technique, buy a code and another for validation could guess the technique and do a brute force search for the secret.
I don't think full public key cryptography is viable on these machines, so this is a compromise. Porting OpenSSL is going to be non trivial and use up a significant portion of your developer time and code space. If it's not a missile launch code, or you need to protect users details, or guarantee votes in an election, public key cryptography is probably more than required for your revenue protection case. Caveat emptor.
Comment: This is probably the best answer so far given the constraints.
Answer: Use an MD5 hash. This will create a 128-bit key, so you can represent that as 32 hex characters. A hash never can guarantee uniqueness, but the length will decrease the chances of coinciding hashes. If 32 hex characters is too long you can truncate it to the desired length.
If you need a unique serial key you have to append a unique number, like customer number, to the hashed user data, so that it's not included in the hash calculation.
Comment: If possible, don't use MD5. MD5 is vulnerable to several collision attacks. SHA-1 or SHA-2 are more robust.
Comment: Are you suggesting to simply hash the phone number? Unless we are hashing with a secret salt known on both sides, how would we stop someone from generating their own MD5 hashes?
Comment: @Jon L - I supposed the system has the same identification data as the code-issuing party, so the code could be verified.
Comment: @Toby - I know MD5 has been cracked, SHA-1 is also considered to have weaknesses. I tried to keep the length practical. And like I said in the other comment I presumed that the plaintext is available in the system, so the hash can be verified. I don't have the impression this is a secure cryptographic application (for which hashes are useless anyway).
Answer: If a registration code must work on one and only one device and no other devices, then this could be a good use for public/private key architecture.
It works like this: Your server will have a public key and a private key. The private key is always kept secret.  The public key is viewable to anyone who wants to see it (although we won't be needing to do that in this case).  If the server encrypts something with its private key, then only its public key can decrypt it.  If somebody else encrypts something with its public key, then only the server can decrypt it with its private key.
This accomplishes two things

By having the server encrypt ("sign") something with its private
key, we can verify that it's really coming from the server by
decrypting it with its public key.  We can authenticate the source
of the message.
If we encrypt something with its public key, then only the server
can ever decrypt it, thus we can send it messages that no one else
but the server can read.

If we have the device have its own set of public and private keys, and a copy of the server's public key, then we can establish messages between the two that no-one else can read.
So you could have a system that work like this:
Server side, a database schema that maps device serial numbers to their public keys.  When someone makes a purchase, they must provide this serial number.  When a purchase request comes in via SMS, the server stores the phone number and looks up the device's public key from the provided serial number.  When it is found, it will hash, then encrypt the SMS phone number using the device's public key, then that entire cipher would then be encrypted again using the server's private key.  It sends this back to the user via SMS.
When the user punches in this hex string, the device will first decrypt using the server's public key - this is to ensure that it actually came from the server.  That removes the first layer.  Then it decrypts using its own secret private key, this should give you the hashed SMS number.  Get the user to enter in their phone number and hash it.  If the hashes match, then procede.
If you need to have sessions that expire, include a time stamp along with phone number hash before the encryption on the server side and have the device make the decision of whether or not that key is still fresh.
Here is a primer on public/private key architecture: https://en.wikipedia.org/wiki/Public-key_cryptography
What you would be interested in is:

Choosing a method to generate public/private key pairs
Choosing an encryption method to encrypt data using this keys.
Answer: If the system will have a serial number that you generate burned into a protected area of the code space, you could simply program each unit with an activation key along with the serial number.  This would require you to ensure that you keep track of the issued serial numbers and associated activation codes, but if the codes are generated randomly, you could avoid the risk of someone discovering the algorithm used to generate the keys.  If you don't want to worry about keeping track of all the issued keys, you could use an algorithm to generate them, and have some attribute of the algorithm set differently for each batch of devices (you could, for example, encrypt the keys for each batch with a hash of the lottery numbers drawn for the New York State Lotto the Friday before the batch was produced.  Even if your own records were destroyed, you would be able to go back and find out what the numbers were, but it's unlikely someone would be able to reverse-engineer the fact that the lottery numbers were the source data for the hash, especially since the number of discrete batches would be small compared to the number of units.
If you will be using a serial number which you are not supplying (e.g. a device serial number burned into a flash chip) then you have two main choices: have the device use the serial number to compute what the key should be, or have software in the factory (outside the device) munge the serial number in a confidential way to yield a key which, when munged a certain way by the device, will yield the serial number.  The latter approach has the advantage that even if someone were to reverse-engineer the key-validation code in the device, they would be unable to generate keys that would work for arbitrary serial numbers.  It would, however, have the disadvantage that keys would probably have to be a minimum of 128 bytes to have anything resembling security (given today's advances in CPU technology, 256 bytes would be better).  Not a problem if your device would be connected to a PC or portable memory device for purposes of activation, but not so great if people are entering a code via thumbwheel.
Comment: Er, those 128 and 256 bytes, shouldn't that be bits? (though 2048 bits will surely be secure! ;-))
Comment: @stevenvh: No, bytes.  For all public-key systems I'm familiar with, the encrypted message cannot be shorter than the key.  Advances in numerical horsepower are such that a 512-byte key would seem to be a "toy"; from a practical perspective, if one needs at least 512 bits, I don't see much difficulty going up to 128 bytes.
Answer: You could generate a digital signature from the users user's email or/and phone number using the OpenSSL libary that has public key cryptography functions that would be suitable.
It might be hard to find space for code for verification in a PIC chip in which case
a simpler and much less secure system based on a checksum/hash on the email/phone number may have to suffice- in that case be sure to salt the email/phone number to prevent users from discovering the checksum algorithm by trial and error.


How to emit events idempotently

Question: If I have a service that consumes events of type A and emits events of type B, how can I make sure that event B is only emitted once for every event A?
Should the service also subscribe to events of type B to see that an event B with a same correlation ID/with a reference to the A event wasn't written yet?
Seems like a lot of extra responsibilities for the service.
Comment: In the question title you use the term "idempotent", but you are asking about processing events only one - which is something quite different. Processing events in an idempotent way is actually lifting that restriction that an event must be processed only once. You do that by ensuring that processing the event twice has the same result as processing it only once, so you can make delivery reliable at the expense of duplicates in cases of trouble.
Comment: In general, exactly-once message-passing is hard. It's easier to make the end consumer of events (i.e. the consumer of event B) idempotent.
Comment: @Hans-PeterStörr I'm looking to idempotently process my duplicate event of type A to not publish a duplicate event of type B.
Comment: @MihailMalostanidis I still think this is misleading. A proper use of idempotency would be to make your distributed system indifferent against duplicated events B. See my answer, and MikeFHay's comment.
Comment: It's indifferent in every aspect other than performance.
Answer: Making sure events are processed once and only once in a distributed system is really really hard.
But, we are talking network failure and program crashes. In a normal message queue system, if you emit B when you get A and set your queues up correctly and have no major bugs you shouldnt worry overly.
Having said that, when you have outages it will be a possibility. So you should have systems in place to pick up on significant duplicate events, say taking payment twice, after the fact and correct them.
Comment: Would some sort of journaling transaction system be effective for implementing this?  For example, if you keep a record of having emitted event B for a given event A (assuming it has some sort of unique transaction ID)? Then you can check the journal to see if you've already emitted the event after a crash has occurred.
Comment: sure, but then your system is checking that central log all the time and you have lost the advantages of a distributed system
Comment: Well, you haven't lost *all* of the advantages.  Many distributed systems have a central gateway that distributes messages; you could put your journaling there.  See https://microservices.io/patterns/apigateway.html
Comment: @RH hmm, not so sure about that
Answer: This is possible with the aid of Activities. Pat Helland discusses about Activities in his paper Life beyond Distributed Transactions: an Apostate's Opinion. Vaughn Vernon also talks about this in this video.
The idea is that a receiver of a message should store in it's localstorage the IDs of all the messages that it has seen. If it receive a message that it has already seen then it ignores it. If the received has not seen the message then it processes it and then emit its new own messages.
In Event sourcing this means that the new messages should contain in their body the ID of the message that was the cause of those new messages.
So, in your case, message B should contain the ID of message A. So, when the message A is retried, the service replays all the previous messages that it has emitted, including the message B and then it sees that it has already processed the message A and ignores it.
This technique, combined with at least one delivery, gives you what you want, in the most scalable way.
Comment: But why would a sender ever send two messages with the same ID?  Or for that matter, why would any other sender ever send a message having the same ID as some other message in the system?
Comment: @RobertHarvey when it retries it
Comment: @RobertHarvey `Or for that matter, why would any other sender ever send a message having the same ID as some other message in the system?` - I don't get this question.
Comment: @RobertHarvey the OP whats to know how to not "re-do" a message
Comment: Yes, I understood his question.  I got confused when you said that " If it receive a message that it has already seen then it ignores it," which suggests the presence of two messages with the same ID.  But then you clarified by saying that the retry message actually has its own ID, and that you're storing the origination ID in the body of the new message.  Sounds like that might actually work, though it does complicate the messaging infrastructure a bit.
Comment: @RobertHarvey what gets more complicated are the Aggregates (supposing we are using DDD) or the Event store. Vaughn Vernon suggests that the Activities should be part of the Domain. I think we could implement this outside of the Domain, more exactly inside the Eventstore
Comment: I'll have to read the article.
Comment: @RobertHarvey in the video he says that
Comment: I'm not in a place where I can watch a video.
Comment: @ConstantinGalbenu so, the publisher of Bs should also be subscribed to Bs, to make sure that a B caused by the given A hasn't been previously published? Also, wouldn't the memory required to store the IDs of seen As tend to infinity? Should I drop them some time after they were seen?
Comment: @MihailMalostanidis the publisher should retry until the receiver acknowledge. The receiver Aggregate should store only the IDs, which are small. Maybe an optimisation can be made, to clear the ID of events older than some amount of time.
Answer: It seems you are mixing up two quite different ideas for event processing here. You can either

try hard to both transmit/process each event at least once, and at most once, even under the most exotic failures. These are two hard problems which both are only solvable to some extend in distributed systems.
try hard to transmit/process each event at least once, and design your events so that it doesn't matter when you receive several events for one domain change. For this, idempotency of the event processing is a good approach.

The second solution is often easier and (sometimes much) more performant, at the expense of having to think hard about the structure and meaning of your events. You'll probably also have to design your distributed system so that the order, in which the events are received, doesn't matter, too. And that additional events triggered as the result of the second arrival of an event are OK, too.
One way to do this would be to keep all event IDs received in a reasonable timeframe, and discard duplicates. But you could also stucture your events so that it doesn't matter if they are received twice. That's where idempotency comes in: an operation (the event processing) doesn't change anything, anymore, when it is repeated more than once. For example, if you receive an "user adds street address" event, and the user already has that address, you can naturally just discard that event.
In your example, this means that you could make sure that the service emits a type B event for each type A event, but you can omit any special precautions that it never ever emits two type B events in the case of failures, since you have designed your events so that this wouldn't do any harm (besides a little more data being transmitted). You arrange things that events normally get received once,  but in the case of failures it can happen that it's received two or more times.
Answer:
If I have a service that consumes events of type A and emits events of type B, how can I make sure that event B is only emitted once for every event A?

The only way I know to do that is to ensure that all consumers of event B are part of the same transaction as event A.
In a distributed world?  no chance.
At most once delivery is trivial -- just swallow event B without ever emitting it.
At least once delivery is manageable.
Exactly once delivery is beyond economically viable.
In most cases, the important points are (a) to make best effort to ensure that consumers recognize events that have been successfully processed, and (b) to have protocols in place to handle circumstances when events have been processed more than once.
(Example: on airplanes, we are legally limited to one passenger per seat.  But it may sometimes happen that two passengers are assigned to the same seat.  Even in this crisis, the plane usually manages to reach its destination....)

With just at least once delivery, it seems like this would cause an amplification of duplicate messages?

It certainly could - I think that depends on what synchronization points follow, and what strategies are applied by the handlers when they recognize a duplicate message.
For instance, if a receiver is processing messages in batches, then it might receive two copies of a message, and recognize the duplication.
On the other hand, the duplicated message may be an indication that an acknowledgement was lost in transit, in which case that acknowledgement should be resent, so that the upstream participant can know that the at-least-once requirement has been met.
A good starting point for this sort of thing is Udi Dahan's Reliable Messaging Without Distributed Transactions.  You may recognize some similarities to the Pat Helland paper referenced by Constantin
Comment: The problem, as I see it, is not the idempotency of messages (most messaging systems like this can be made pretty durable), but rather the idempotency of the database transactions.  In your airline reservation system, the need to consult a central database before assigning a seat seems unavoidable.
Comment: With just at least once delivery, it seems like this would cause an amplification of duplicate messages? Two `A`s are emitted before the emitter of `A`s understands it's been heard. Then, for each `A` two `B`s are emitted. Then for each `B` two `C`s. Now we already have 8 `C`s corresponding to the same real world event coursing through the system, all causing checks and computations. And who says they will be treated the same each time? We might get one successful reservation and 7 rejections. How will we know to ignore so many rejections and learn we were actually successful, if unordered?

How to emit events idempotently


How to use Tensorflow and Qiskit to make a quantum neural network and recognize handwriting?

Question: How to use Tensorflow and Qiskit to make a quantum neural network and recognize handwriting?
Answer: Instead of combining Tensorflow and Qiskit, you can use the Tensorflow Quantum package. It provides seamless integration of quantum simulation in the tensorflow framework. You can build layered approaches as you would with classical neural networks, and use the standard loss functions and optimizers that you might be used to.
A tutorial on how to build a QNN using Tensorflow Quantum for MNIST (recognize hand-written digits) is available at https://www.tensorflow.org/quantum/tutorials/mnist.


Have a new Samsung dishwasher that emits a sewage smell while running

Question: My new Samsung dishwasher emits a sewage odor (started with the 1st use) through the dishwasher air vent, but only while it's running.  I think its pulling air through the drain hose while its running.  It actually smells up all the surrounding cabinets too. The installer felt that running the drain hose up and over the cabinet wall to connect with garbage disposal would create a sufficient air trap. Shouldn't the drain hose have an actual 'loop' before connecting to the garbage disposal? I did not notice this odor with the old dishwasher. Thanks for any advice.
Comment: Pictures of how the dishwasher drain is attached would probably help.
Comment: Could the strange smell be from the water ? If you are in a drought part of the country the reservoirs have become filled with algae-bloom.
Answer: You need a loop (it should go above where the dishwasher enters the disposal) or an airgap to prevent the backflow of drainage water into the dishwasher. The smell could be coming from the inside of your garbage disposal.
The line should definitely be arranged like this photo, where a portion of the line curves above where it enters your disposal.


MO scheme for coordination complexes (tetrahedral) - Heteroligand vs. homoligand

Question: How is the MO diagram drawn for a tetrahedral complex with heteroligands (e.g. $\ce{[NiCl2(PPh3)2]}$) different from a tetrahedral complex with the same type of ligand? Do we consider the same "a1 and t2" SALCs as in the case of same ligand type tetrahedral?
Answer: Bis(triphenylphosphine)nickel chloride can have be tetrahedral or square planar depending on conditions. In any case the SALCs for a tetrahedral complex with heteroligands will depend on the point group of the complex. For [NiCl2(PPh3)2], the point gorup is C2v and not Td like for same ligand tetrahedral. You need to check the character tables
Comment: Why does [NiCl2(PPh3)2] have a C2v point group? Wouldn't it be more logical if it have Td point group? If so, did you not include the two Cl ligand in determining the point group because I think the only way the complex would be a C2v is that when its geometry is similar to water.


Is there a name for a distribution where I can take log of its histogram and get back the same histogram?

Question: I am imagining some data distribution where taking the log over and over again yields a distribution that has the exact same shape.
Comment: Please explain what you mean by "take log of [a] histogram."
Answer: To put this in more mathematical form, you want to be able to start with a random variable $X$, take a logarithm, then perhaps add and multiply by some numbers and get back the same distribution. $Y=a+b\log X$ and $X$ have the same distribution.
This is possible for a distribution that puts all its probability on two points. The logarithm puts all the probability on two different points, and you can rescale it back to the original distribution.
It's not possible otherwise. Let $x_1$ and $x_2$ be two values of $X$ and consider the point halfway between them: $x_m=\frac{1}{2}(x_1+x_2)$. Because $\log$ is a concave function, $\log x_m$ will always be less than $\frac{1}{2}(\log x_1+\log x_2)$.  If we write $y_1$ and $y_2$ for the transformed values of $x_1$ and $x_2$, we can choose the scaling so that $y_1=x_1$ and $y_2=x_2$. But $y_m<x_m$, rather than $y_m=x_m$. So we can only get the same shape back if there is no probability at $x_m$.  Basically the same argument works for a point 1/3 of the way between $x_1$ and $x_2$, or any other intermediate position.
Answer: A logarithm can be thought of as a function that stretches/squeezes along the number line. Given a series of values, taking the log will stretch the lower end of the range, and squash the upper end of the range - small values like 0.001, 0.01, and 0.1 that are "nearby" one another get stretched to cover a larger range of -3, -2, and -1, while large values like 1000, 10000, and 100000 that are "distant" from one another get squeezed to cover a smaller range of 3, 4, and 5.
When taking the log of a histogram, you're modifying distances between bars, but are doing so unevenly along the length of the histogram - you're stretching the left half of the histogram and squeezing the right half. Except in the case of very simple histograms with few values, this will always result in a different shape from what you started with. To preserve the shape, you'd need to shift or scale all values by the same amount, but the log effectively applies a scale factor that varies with the value being scaled.


C# Problems With Sending/Receiving Size of bytes (Sockets)

Question: I've made these codes to send and receive an Image with a TCP socket but the receive code didn't work.
This is the send code:
public void SendImage()
{
    int ScreenWidth = Screen.GetBounds(new Point(0, 0)).Width;
    int ScreenHeight = Screen.GetBounds(new Point(0, 0)).Height;
    Bitmap bmpScreenShot = new Bitmap(ScreenWidth, ScreenHeight);

    Graphics gfx = Graphics.FromImage((Image)bmpScreenShot);
    gfx.CopyFromScreen(0, 0, 0, 0, new Size(ScreenWidth, ScreenHeight));
    bmpScreenShot.Save(Application.StartupPath + "/ScreenShot.jpg", ImageFormat.Jpeg);
    byte[] image = new byte[1];
    bmpScreenShot = ResizeBitmap(bmpScreenShot, 300, 300);

    image = ImageToByte(bmpScreenShot);
    //get the length of image (length of bytes)
    int NumberOfBytes = image.Length;
    //put the size into a byte array
    byte[] numberofbytesArray = BitConverter.GetBytes(NumberOfBytes);

    //send the size to the Client
    int sizesend = sck.Send(numberofbytesArray, 0, numberofbytesArray.Length, 0);
    if (sizesend > 0)
    {
        MessageBox.Show("Size Sent");
    }
    //send the image to the Client
    int imagesend =sck.Send(image, 0, NumberOfBytes, 0);
    if (imagesend > 0)
    {
        MessageBox.Show("Image Sent");
    }
}

And here is the receive code:
public void ReceiveImage()
{
    if (sck.Connected)
    {
        {
            NetworkStream stream = new NetworkStream(sck);
            byte[] data = new byte[4];

            //Read The Size
            stream.Read(data, 0, data.Length);
            int size = (BitConverter.ToInt32(data,0));
            // prepare buffer
            data = new byte[size];

            //Load Image
            int read = 0;
            while (read != data.Length)
            {
               read += stream.Read(data, read, data.Length - read);
            }
            //stream.Read(data, 0, data.Length);
            //Convert Image Data To Image
            MemoryStream imagestream = new MemoryStream(data);
            Bitmap bmp = new Bitmap(imagestream);
            pictureBox1.Image = bmp;
        }
    }
}

The problem is when i send the size, its sent as 5kb but when i receive it i find it 2GB and this error comes up:

Unable to read data from the transport connection. An operation on a socket could be performed because the system lacked sufficient buffer space or because a queue was full.

The error is at this statement read += stream.Read(data, read, data.Length - read);
Comment: You should definately tackle the situation where the sender closes the connection while the receiver still expects additional data (`stream.Read()` would return `0` in that case).
Answer: I would try getting smaller chunks of data.  In your code you're starting off with all the data (2GB at a time in the case that fails.  Drop that down to something smaller--the data is sent in chunks anyway.  For example:
read += stream.Read(buffer, read, 20480);

this will read about 2k at a time so as to not be larger than the buffer space or be too large for the queue.
If you've allocated a buffer of 2GB in size, your application likely has very little memory left.  The underlying framework is probably unable to allocated 2GB of data for itself (4GB total allocated) to transfer data.
Comment: i know but why does it receive 2GB , its supposed to only receive 5kb
Comment: Are you sure 5k is being sent?  what are the values in the `numberofbytesArray`?  Also, are you sure nothing else reads anything from the stream before calling `ReceiveImage`?  The user of `BitConverter` is right, so the only way you wouldn't get the right values is if the `Image.Length` isn't 5K, or something already read all or some of those bytes which corrupts how you read the lenght...
Comment: YEA IT WAS 5KB , BUT I DIDNT READ `numberofbytesArray` , how can i read the value in it??
Comment: There's something more going on that you haven't provided, the code you posted should work; I'm trying to get the root of the problem--guessing at possibilities because you haven't provide code that reproduces the problem.
Comment: do you think it might be the imagetobyte() function??
Comment: @TarekAdel You said that `numberofBytesArray` has the correct value in it.  so, it shouldn't matter what ImageToByte does w.r.t to this problem. If the other side isn't getting 5k; there's something wrong with the way it's reading the data sent before ImageToByte.  Or something else was sent before the sck.Send(numberofBytesArray,...


Best practice for two site Active Directory through VPN

Question: Currently we have a site-to-site VPN setup between our two locations A and B. Location A has the domain controller; all hosts in location B connect via the site to site VPN to the DC in A. I was wondering if this is not ideal because if either Internet connection goes down, or the VPN/firewall server gets messed up, ii) the hosts in B cannot connect to DC on A, and more importantly, ii) the primary/secondary DNS servers on the domain are both located in A. Please advise on the best practice to alleviate this potential issue.
Comment: curious as to what is in Site A? if the link dies, then the ability to  find the IPs for remote services is useless anyway. if you only have a few users in Site B then DC/DNS isn't really needed, logins/local network will be unaffected for short outages. if you're trying to keep the internet accessible when the link dies then why not make Site B's clients' primary DNS = SiteA and secondary DNS = the local router/ISP - need more info...
Answer: Promote a DC in Site B, create two sites in AD, then assign each domain controller to its appropriate site. Also, install DNS on this server, and use it as the primary for all hosts in Site B.
Ideally, the hosts in site A would use the local DNS server as primary and the DNS server at the opposite site as secondary. Vice-versa for hosts in Site B.
Comment: You can actually set up the sites and assign subnets before promoting the DC at the other end :)
Comment: Yes, for sure. I suppose that would lessen the time required for everything to sync up.
Answer: While you could set up a DC/DNS server in site B, I have to ask: where are the resources that the users use located? If the resources are in site A then it really doen't add any value to set up a DC/DNS server in site B. If site A is unavailable and that's where email, file, database, etc. services are then the clients ability in site B to log on to the domain via a local DC doesn't do much good.
Comment: +1 for this. Yay for DFS and Exchange DAG's.


Is it possible to make an application skip a call?

Question: I have an application that calls a subroutine before sending the data over socket and in that subroutine the packet is being encrypted. Is there any way to make application skip that subroutine and send the packet as non-encrypted ?
Comment: Replace the call by a NOP if the encryption is in-place, or modify the function to just copy the input if it's not. Without more information about how the program & the call work, it's hard to help you further.
Comment: Here's a screenshot from IDA: http://i.imgur.com/zurZc9f.png
Comment: There are two calls in you screenshot. **edit** : I guess it's `encoder_func`
Comment: Yeah that's the subroutine i want to skip.
Answer: As Dillinur wrote, you need to NOP out this call. To do that you may need a hex editor, like WinHex. To NOP out the subroutine, you have to determine from which address it is called. To see that address, in IDA go to Options -> General and mark Line Prefixes.
It's also nice to see which Opcodes you would like to NOP out. Go to Options -> General and write 6 in the field Number of opcode bytes. Then your IDA graph mode will look like that:

In my example, if I want to skip the foo-subroutine while execution, I need to set the opcode bytes E8 DF E6 FF FF to 90 90 90 90 90 (E8 is the call mnemonic and the rest are the offset bytes). 0x90 is the NOP opcode.
To NOP out these bytes I open the executable in WinHex and search the offset 0x31CC (not 0x4031CC, because 0x400000 is the load address of my executable in IDA). Finally, when I've found the offset 0x31CC I look for the sequence of bytes E8 DF E6 FF FF and then edit them to 90 90 90 90 90. Save it.
Also you may think about NOPing out of the PUSH-instruction(s) preceding your subroutine in order to avoid errors in the succeeding code.
Comment: Just a note, it is also possible to edit the function within Ollydbg then save the modified ("patched") executable. The advantage with olly is that you can see the instructions you are changing, while with a plain hex editor it can be difficult.
Comment: I don't know if it's still prevalent (in days of DEP - data execution prevention), but with many programs of old, while you could find such a block of code during execution, but it wouldn't appear that way on disk, so you couldn't (easily) make permanent changes (essentially, the "code" was a block of data that was decrypted during the start-up phase).  Also, doesn't the `add esp,8` balance the `push`es, so they should stay?
Comment: You don't need to nop the preceding pushes as there as an add esp, 8 after the function call.
Comment: In general, you may need to NOP the preceding pushes if the called function uses *stdcall* as calling convention, where the called function is responsible for cleaning up the stack. That is why I wrote "you may think about NOPing".
Answer: There is an ida tag, but your question doesn't mention it, so let's do that with radare2 instead ;)

aa to analyse the binary, pdf to show the current function, wx to write hexpairs, and pdf again to check the result. It's also possible to use "wa nop;nop;nop;nop;nop" instead, if you prefer writing instructions, or even better, the magical wao nop command, to replace the current
 opcode with nop.


Primary ps4 and game sharing

Question: My brother and I both own a ps4. His account is the primary account on his system, and my account is the primary on my system. If I log into his account on my ps4, can I play his games while I'm on my account WITHOUT making his account the primary on my ps4?
Answer: You can only play his games while logged into his account anywhere, or on any account while on his primary PS4. To play his games on your PS4 you will need to be using his account, not your own.

Primary ps4 and game sharing


Phosphates Functional Group

Question: In my text book it states that a phosphate group is considered to be $\ce{-OPO3^{2-}}$. However, online it states that phosphate is $\ce{PO4^{3-}}$. Why do these contradict? Am i confusing phosphate the chemical with the phosphate group? Please see image for reference.
Answer: Phosphate $\ce{PO4^3-}$ is an anion of the phosphoric acid $\ce{H3PO4}$. Term phosphate comes from a salt, for instance a sodium phosphate $\ce{Na3PO4}$. $\ce{Na+}$ are bound with a $\ce{PO4^3-}$ through ionic bonds. No electron sharing.
To annotate specific moieties of a molecule skeleton, a chemical group term is used. The phosphate has donated one pair of electrons on the oxygen to have a covalent bond with other molecule, for instance sugar in the image, and becomes a phosphate group in the molecule. Since the electron pair does not sit on the oxygen any more, but is shared with carbon, the phosphate charge is lowered to −2.
Comment: Edl, please see below as I had to reply in the form of an answer to post an image in regards to your comment.
Comment: AMP is charged (-2) in physiological conditions (aqueous solution with pH~7). Both -OH groups are easily deprotonated (lost H+). The picture you have found shows a neutral molecule (which is right as well), and can be isolated in this state.
Comment: so the picture below (AMP with the OH- groups) are AMP outside of an aqueous solution where as the picture you originally gave in your answer is AMP deprotonated in water which is basically the phosphate anion?
Comment: Yes, that is right!
Answer: @ EDL, thank you. Im still confused on how the image above had a 2- charge. Im assuming the whole molecule is a formal charge of 0, correct? But if the 2 O atoms indicated in your drawing each have a 1- charge I would think the molecule would have a net charge of 2-? Also, why online does your image contradict the AMP I found. Please see below for image. Why are there H's where the phosphate group is and on your image the O's are alone with a "-" sign? Is what I have below the true AMP and what you were showing me was for the purpose of the functional group?
Comment: @Atticus283blink It's probably best to either integrate it into your question or host the image on imgur and link to it in the comment.
Comment: Please use the edit link on your question to add additional information. The Post Answer button should be used only for complete answers to the question. - [From Review](/review/low-quality-posts/36517)
Comment: Doesnt seem as efficient they need to add an option to add photos to a response hence why i added an answer

Phosphates Functional Group


Showing thumbnails or some kind of preview in the Gnome workspace switcher popup?

Question: The workspace switcher popup doesn't provide previews by default. Is there any way to enable them? The Workspace List that shows up on the right when super key is pressed does have preview.
Answer: You could do that via a gnome-shell extension:
workspace-switcher-popup-thumbnails
Download the zip file and either use gnome-tweak-tool to install it or extract the archive and move the resulting directory to
~/.firstname.lastname@example.com

note the name of the extension directory (it has to match the uuid in metadata.json)
then inside that directory, edit the  metadata.json and replace 3.8 with your gnome-shell version, e.g.
"shell-version": ["3.18.2"]

save, restart both gnome-shell (Alt+F2 then r) and  gnome-tweak-tool and use the latter to enable the extension:
Comment: Thanks, now coupled with https://github.com/bulletmark/libinput-gestures Gnome 3 on Arch is rocking.
Comment: I've been looking for exactly this for so long, but there are two problems: I use 9 workspaces in a 3x3 grid (using the extension ``Workspace Grid``) and I think this messes things up. I get a 9-box long column of workspaces on the far left of the screen that doesn't go away unless I restart gnome-shell. I *really* want something like this to work with my current grid!
Comment: While the extension still seems to work, and still seems to be maintained as of early 2019, @AmagicalFishy's concern remains valid and a recent [comment](https://github.com/sustmi/gnome-shell-extension-workspace-switcher-popup-thumbnails/issues/1#issuecomment-443557382) from the maintainer suggests that it's unlikely to be fixed anytime soon. Alternative solutions (might!) include [this extension](https://extensions.gnome.org/extension/1485/workspace-matrix/) or others mentioned in [this issue thread](https://github.com/zakkak/workspace-grid/issues/4) on the Workspace Grid page.
Comment: @AmagicalFishy - well, I saw your Q but since I'm not familiar with _Workspace Grid_ I just skipped. It's not even clear from the Q (for someone like me, not familiar with that extension) whether showing thumbnails should just work or is a missing feature...
Comment: Extension no longer seems to work in gnome-shell 3.30.1
Comment: @ChrisBillington - no wonder, it hasn't been updated in five years.


How can I show that the stochastic integral of a jump process w.r.t. Brownian motion is a local martingale by using this special localizing sequence?

Question: Suppose that $Y$ is a pure jump process with $N_t$ jumps in $(0,t]$ and $E[N_t]<\infty$. Denote the jump times by $T_i$. Let $W$ be a Brownian motion. If $T_0=0$, then
\begin{equation}
M_t=\int_0^t Y_s\,dW_s=\sum_{i=0}^{N_t-1} Y_{T_i}(W_{T_{i+1}}-W_{T_i})+Y_t(W_t-W_{T_{N_t}}).
\end{equation}
The process $M$ is continuous. I want to show that $M$ is a local martingale by using the sequence $\tau_n=\inf\{t: |M_t|>n\}$. That is, I have to show that $\{M_{\tau_n\wedge t}\}$ is a martingale. I have read that one can use the above sequence of stopping times for continuous local martingales. But why or how?
Answer: I guess you could use the sequence $\tau_n=\inf\{t\,:\, N_t=n\}$ and then Corollary 6.14 (or 7.14 depending on the edition, it is called "martingale transforms") from Kallenberg's Foundations of Modern Probability yields the result.
The corollary states that $Y_t(W_t-W_{T_{N_i}})$ and
$$\sum_{i=0}^{n}Y_{T_i}(W_{T_{i+1}}-W_{T_i})$$
are martingales for all (fixed / deterministic) $n\in \mathbb N$.
But in your case, you need that
$$\sum_{i=0}^{N_{t-1}}Y_{T_i}(W_{T_{i+1}}-W_{T_i})$$
is a local martingale for random $N_{t-1}$. This is why you need to stop the process.
With the stopping time suggested above, you obtain
$$M_t^{T^n}=\sum_{i=0}^{n-1}Y_{T_i}(W^{T_{i+1}}_t-W^{T_i}_t)$$
which is a martingale.
Of course, you could also use the well known fact, that a stochastic integral with respect to continuous local martingale is always a local martingale. Then you still need to show, that stopping at $\tau_n=\inf\{t\,;\,|M_t|>n\}$ yields a uniformly integrable martingale. Because of the continuity of the process $M_t$, you get that $M_t^{\tau_n}$ is bounded by $n$ and any bounded local martingale is a uniformaly integrable martingale. Hence the result follows.
Comment: This would imply that $M$ is even a martingale, not just a local martingale, which makes me sceptical about this answer.
Comment: You need to stop the process $M$ in order to make the sum consist of a fix number of summands. Without stopping the number of summands is random and thus you can't apply the corollary from Kallenberg. Thus you have only shown that $M$ is a local martingale. I don't know whether $M$ might even be a martingale. I can imagine that you need more information about the distribution of $N$ to determine whether it is only a local martingale or even a true martingale.
Comment: Then I didn't understand how you would use the corollary. Could you please explain that a bit more precisely?
Comment: I edited my answer above.


Alternative data providers

Question: What data vendors/providers have you come across or used for alternative datasets? Not talking about market data here. Things like rainfall, coronavirus stats, new car production in China etc. I
Answer: There is a website called AlternativeData that have aggregated data vendors for alternative datasets (eg. weather data, mobile phone location data, satellite data, and much more). Often, specific datasets come with a (hefty) price. You can try and look around and see if you find something interesting. Personally, I don't know any free alternative data providers. Hopefully this helps.
Answer: You can try looking around Datarade.ai. It's technically an online catalogue for all sorts of data covering a range of categories including Geospatial, Environmental, Web, Healthcare and etc

Alternative data providers


Hot water flow is slow from 3 L/3KW instant geyser (hot water heater)

Question: Yesterday we installed a 3 liter instant water heater which uses 3 KW. After the install, hot water is coming through the tap, albeit very slowly. The cold water is coming fast. Our geyser was installed by an electrician who told us that instant geysers do not require pressure. How can I get the hot water to flow quickly?
Comment: I am very confused as to whether this is a *tanked* or *tankless* hot water heater.  If tankless, the 3-litre figure makes no sense, unless it's 3 litres/minute (a slow rate, and a tick slow for a 3000W heater unless the goal is to make water hot enough for tea).  If tanked, 3000W seems *rather excessively large* for a 3-litre tank.
Comment: Googling *3kw 3 litre geyser* reveals this is an *Indian* idiom: probably a "Flora", which sells for R2800 or about US$42.  I don't know how Indian labor or market protectionism works, but Americans wouldn't expect much at that price.  It seems to be marketed for *bathing*, offering a quick recovery time (true) so the whole family can bathe.  All this tends to suggest it is a *tanked* heater.
Comment: 3kw instant hot water to me would mean tankless and that is quite small. Of the point of use tankless electrics I have installed the units thermostat reduces the flow to keep the water warm, if you increase the flow the water will be cold or cooler the only way to increase the flow would be to reduce the temp setting or get a larger unit.
Answer: 30°C temp raise (10°C to 40°C) for 1L/min requires about 2,1kW of power. So with a 3kW POU you can't expect a big flow. An 'adequate' shower consists in about 6L/min. These are the numbers. Especially if main water is cold, instant POU are not enough, better to install a under-sink tanked heater (10L), it delivers much better flow even at higher temperatures.
Answer: Electric 'point-of-use' hot water heaters have a water flow rate much less than the cold water line. The behaviour you describe may be normal operation for this unit.
Is this unit being used for a shower or to heat water for the kitchen sink faucet for dish washing?
From this unit one could get a small amount of very hot water on demand and by mixing with cold get a low volume stream of barely warm water which would last several minutes, until the 3 L of very hot water in the mini tank was used up, then the water would go cold and one would have to stop the flow for maybe 10 or 15 min until the water in the tank got hot again. It seems that this unit is what is called in the US a 'mini tank'; the water in the tank will be very hot (~>60 C), but will not have a high flow rate.


How to ensure the user is logged into the system at the controller level?

Question: I'm using spring MVC, and I have a custom authentication/security system that I had to build.
NOTE:  I know of spring security, but my requirements were to do this in a custom way so please not looking for suggestions about using spring's security modules.

When the user logs into the system, it creates a session cookie.  When the user visits a page, a interceptor looks for the existance of that cookie, and looks up the session guid in mysql and if it is present that it loads some data and stores it in the request's attributes.
Now for pages where the user has to be logged in, how can I restrict access at the controller level?
I could do this in an interceptor:
if url.contains("projects/") ...

If I want to restrict access to only logged in users in the ProjectController, but this isn't really something I want to do.
But I am looking for maybe a annotation I could add at the controller level, or maybe somehow create a BaseController that all controllers that require a loggedin user will inherit from.
What are my options for something like this?
In ASP.NET, I created a baseController, and the controller has an event cycle, and in the before-action fired event I checked to see if the user was logged in.
So looking for suggestions for spring mvc?
Update
For example, in ASP.NET you have 2 methods, 1 that fires just before the controller's action method and one that fires after:
Controller.OnActionExecuting
Controller.OnActionExecuted

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onactionexecuting.aspx
So in the OnActionExecuting, I can actually see exactly which controller I am in, and which action is about to get called in a programatic way, not by looking at the request URL and then doing string compares to see if it is a particular controller etc.
So in this event, I can simply check for things in cookies or in my request attributes etc.
This is a much more stable way to do it, does spring have anything similiar?
Comment: Take a look at Spring AOP, it provided the same functionality as provided by `Controller.OnActionExecuting` and `Controller.OnActionExecuted` using `Before` and `Afer` Advices.
Answer: If you need this at the controller level, you could:
1) declare a java.security.Principal parameter in the controller method signature, which Spring will fill in with a Principal object, or
2) implement a PermissionEvaluator, which can be called on a controller method using the @PreAuthorize annotation, and which would have access to a Authentication object.
Answer: Similar to what you did in ASP.NET, you can take advantage of OncePerRequestFilter and chain it to the chain of filters you have in web.xml or Spring application context. The good point about this filter is that it's independent of the MVC approach that you take and no need for a "base controller".
On the other hand, if you're also using Spring security module, you can use a custom filter configuration and place it in the correct place that it should be.
If the check fails, then you'd probably want to raise exceptions or redirect user to the correct navigation.
Based on the last comment, you can also use mapped interceptors:
<mvc:interceptors>
    <mvc:interceptor>
        <mapping path="/myFirstPath/*"/>
        <mapping path="/mySecondPath/*"/>
        <bean class="org.example.SomeInteceptor" />
    </mvc:interceptor>
    <mvc:interceptor>another one</mvc:interceptor>
</mvc:interceptors>

Comment: Thanks, it seems the OncePerRequestFilter is the same thing as an interceptor no?  I don't see any difference?
Comment: As also suggested in Spring documentation, an interceptor provides a more _fine-grained_ control than a filter. Originally a filter is configured through `web.xml` however interceptors are configured through application context which makes them more configurable. In a general case, interceptors may overcome filters. Still think that in your case combined with custom filters in Spring security could also be a choice.
Comment: either case, it doesn't tell me which controller will be firing in a precise manner, I have to sort of guess my looking at the url structure which is too hacky for me.
Comment: I updated the answer which is close to what you described in the updated version of question from ASP.NET. There is also a [ticket](https://jira.springsource.org/browse/SPR-6570) to also add exclusion paths.


Canon 50d live view shutter on the "star" button

Question: When I try to use Live View on my Canon 50D, for some reason the AF-ON button doesn't focus the image, but the star button in the middle does. I have that star button set as my Back Focus button to match the button layout on my Canon BG-E2N battery grip, which has no AF-ON button. Is this causing the conflict? Just trying to get Live View to operate as described in manual, you tube tutorials, etc. Thanks in advance.
Answer: If you have the [*] button reassigned as the [AF-ON] button, it will perform that function in both viewfinder and Live View modes.
The custom menu in the 50D has a single menu item (C.Fn IV:2 - AF-ON/AE lock button switch) for swapping the functions of the [AF-ON] and AE lock [*] buttons.
If you've assigned Autofocus start to the [*] button, then you've also assigned AE lock to the [AF-ON] button.
If you have (C.Fn IV:2 - AF-ON/AE lock button switch) set to enable, when any instructions in the manual, youtube tutorials, etc. say to press the [AF-ON] button you should press the [*] button instead.
Conversely, you should press the [AF-ON] button when manuals or instructional videos tell you to press the [*] button. This would also include, for instance, zooming out when reviewing images.


Simple stochastic differential equation

Question: Solve the following stochastic differential equation:
$$
dX_t=X_t\,dt+dW_t.
$$
Thank you very much for help! I even don't know where to start...
Answer: The usual tool used here is Ito's Formula. To use it, you'll want to propose a possible solution, say
$$X_t = e^{t}\left(X_0 + \int_0^t e^{-s} \, dW_s\right),$$
and use Ito, by defining a function, say, $g(t,y)$ that is a function of deterministic $t$ and stochastic $y$. For a nice introduction to SDEs I half-heartedly recommend Oksendal.
Indeed, I do not respond directly to your question. Readily available is not my intuition about generating this solution (I happened to have it "in my back pocket"), but I think it derives from intuition you might have developed in ODE (notice the exponential term, a common term in the solution to ODEs).
Comment: are you sure? Let's calculate $d\,X_t$ for your $X_t$, assuming that $X_0=0$: $$d\,X_t=-e^{-t}\cdot\int_{0}^{t}e^s\,dW_s+e^{-t}e^t\,dW_t$$ and this is not $X_t$ but $-X_t$. Am I right?
Comment: So finally the solution is $-X_t$, not $X_t$, am I right? But I am not sure my calculations are correct: what about the equality $$\frac{d}{dt} \int_{0}^{t}e^s \,dW_s=e^t\,dW_t?$$
Comment: Indeed, the notation you give is just shorthand. The right hand side is shorthand for the left.
Comment: Soren, thank you for assuring me about correctness of my calculation - now I understand it. You have also to edit $e^s$ into $e^{-s}$ in your first answer.
Answer: (Shreve: Stochastic Calculus for Finance Volume II, Exercise 4.8). This is a specific case of the Vasicek SDE,
$$
dR_t = (\alpha - \beta R_t)dt + \sigma dW_t.
$$
Use Ito's formula to compute
$$d(e^{\beta t} R_t)= \beta e^{\beta t} R_tdt + e^{\beta t} dR_t = \cdots $$
the right side will not involve $R_t$.
Integrate this answer to obtain the solution.
Comment: Outside of finance the [Vasicek model](http://en.wikipedia.org/wiki/Vasicek_model) is also known as an [Ornstein-Uhlenbeck process](http://en.wikipedia.org/wiki/Ornstein–Uhlenbeck_process). I believe the analytical solution is first due to [Doob 1946](http://venus.usc.edu/PAPERS/MultiScaleMechanics/Doob-BrownianMotionStochasticEquations.pdf).
Comment: @MattPhillips, $R_t$ is an unknown stochastic process that you are trying to solve for.
Comment: Hi,  what is $R_t$ here?  Is it just any random variable?

Simple stochastic differential equation


What chemicals would an atmosphere unbreathable by humans (yet allowing alien life to thrive) contain?

Question: (first question, hi!) At the moment, I am trying to bring a planet which contains an atmosphere that can barely be breathed by humans (14% oxygen to be precise), to life. This planet is abundant with lush ecosystems of (mainly) turquoise and blue flora and fauna, and orbits the Goldilocks zone of an orange dwarf 0.8 times the size of our Sun. What could make up the other 86% of the atmosphere? and how would it affect a human's perception of the color of the sky?
Comment: You're going to need to describe your aliens and what they can and cannot breathe for us to be able to answer this question. Please remember that we have a strict one question per post limit. Your question title has one question but the body of your question ask two separate questions as well.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Maybe the same stuff we have on Earth?
Imagine 100 people at a concert.  14 are from Iowa.  That crowd is 14% Iowans and it is ok because they are into it.  Then the van from Council Bluffs shows up just in time for the main act with 14 more Iowans.  Now the crowd of 114 with 28 Iowans is 24% Iowans.  Higher % of Iowans and also a bigger crowd.
So too oxygen.  Atmosphere is not an absolute number.  You can get more of it, or you can lose it to chemistry or to space.  If you don't want to get too creative just have it be what we have now:  mostly nitrogen, a squidge of CO2, some argon.  Lower % O2 and less total atmosphere.

Or have a bucketload of CO2.
You want a green world where it is hard to breathe?  Add a bunch of CO2.  The ancient atmosphere might have had a lot of CO2 - maybe as much as 70%.  That would make it tough to breathe normally because CO2 is what triggers our breathing,.  Everyone would be hyperventilating like mad and feel like they were suffocating, oxygen notwithstanding.  Also the CO2 dissolves into body water and makes it acidic.
But the plants dig it.  Plants need CO2 to make their bodies and everything else.  When there is a lot, they can keep pores closed more and they lose less water.  A high CO2 world could be (and maybe was!) a very happy plant world.
Answer: Hydrogen Cyanide
Lots of plants can readily withstand a moderate amount of atmospheric hydrogen cyanide.  Some even produce the stuff, albeit as a non-volatile glycoside.
But humans... not so much.  Most other species with red blood also don't fare so well.  You need to be noble, have the bluest of blue blood... in that you don't want an iron-based oxygen mediation molecule, and copper-based (like the horseshoe crab or Spock) is typically blue.
You needn't have too much hydrogen cyanide in circulation, just enough to exceed the LD50 by means of skin absorption.
Comment: Cyanide is highly reactive and will leave the atmosphere after a very short time scale.
Comment: Note that "_highly reactive_" and "_leave the atmosphere_" is likely to mean "_the entire atmosphere catches fire and all the oxygen gets used up_". Somewhere around 10%+ gaseous HCN will be explosive in a 14% O2 atmosphere. It will also condense in the upper atmosphere and rain out, and liquid HCN is flammable too.
Answer: The main constituent of the remainder of the atmosphere is likely to be nitrogen. There's apparently oxygen-producing photosynthetic plants which would have consumed most of the CO2 by the time there were "lush ecosystems" on land, most of the CO2 the atmosphere started with was probably the source of the O2 it has now. There aren't many other options that are both stable in an oxygen-rich atmosphere and likely to be found in quantities large enough to produce an atmosphere. Additionally, nitrogen is necessary for protein chemistry, and unlike CO2 it is unreactive enough that it's unlikely for life to have consumed most of it.
Trace gases can still render the atmosphere unsuitable for humans. Another answer mentions hydrogen cyanide, other options are hydrogen sulfide and carbon monoxide, or even formaldehyde. HCN, HS, and CO are all lethal at levels of a couple hundred ppm. Formaldehyde, CH2O, is irritating to the eyes and respiratory tract at a fraction of a ppm and can cause sensitization with allergic reactions on later exposure, and long term exposure to low levels can cause nervous system damage and increase risk of cancer. It's also quite easy to produce biologically. Or the local plant life could fill the atmosphere with pollen and spores that cause allergic reactions.
The trace gases wouldn't have any visible effect. Pollen/spores can be visible in high densities, and could cause redder sunrises/sunsets at lower concentrations.


Range of FM and Power

Question: Why is the range of an FM signal shorter than AM signal? I thought it was due to the high frequency of FM signal getting absorbed by physical barriers. Is it so? Does power of a signal has any role to do with range?
Comment: FM and AM are just modulation techniques and have nothing to do with frequency.  Please be more specific.
Answer: If you are comparing AM and FM standard broadcast bands then there are a couple of reasons. AM broadcast is typically about 1MHz and FM about 100MHz and this makes a big difference.
In free space (no obstacles like the earth), the power loss from a transmiting antenna to a receiving antenna (assuming perfect isotropic antennas) is: -
Loss (dB) = 32.45 + 20\$log_{10}\$(f) + 20\$log_{10}\$(d)
Where f is in MHz and d is in kilometres. This equation tells you how many dB of power loss you can expect at a given distance with a given carrier frequency.
If f = 1MHz the 1st term becomes 0dB. However, if f = 100MHz then the 1st term becomes 40dB i.e. 100MHz transmissions incur 40dB more loss at the receive antenna compared to 1MHz transmissions.
It's not that less power is transmitted but that the receiving antenna has a smaller aperture to capture power heading its way. The aperture is a measure of surface area i.e. an antenna operating at lower frequencies has a bigger effective surface area in which to capture power and convert to an electrical signal.
The 2nd reason is due to the ionosphere - signals at or about 1MHz can readily bounce off the ionosphere back to earth whereas at 100MHz, there is very little signal reflection back to earth.
See also this answer and this answer for further info.
Comment: In addition to the greater free path loss already mentioned, the limited diffraction of high frequency EM waves also hinders the FM reception. On the other hand, diffraction is more pronounced in the case of AM frequencies. Thus AM radio can bend over obstacles like mountains more easily. So, although an AM receiver may seem to be in the 'shadow' of mountains, reception is still possible.
Answer: The range of FM transmission depends on the transmission power, channel conditions and the antenna gain. AM medium wave broadcasting uses 300 Hz to 3 MHz band while FM radio is associated with VHF band. Path loss is generally high for FM radio broadcast.
At night time,the shortwave AM radio signals can travel farther due to ionospheric reflection and this is not possible with FM radio.
With only a transmit power of 0.2 W, considering station frequency of 106.4 MHz and station bandwidth 30 kHz with AWGN model, a broadcast distance of 500 m can be possible provided the antenna gains are huge, of the order of 14.5 dBi. The range can further be extended and relaxations be made on antenna gains if transmit power is made high.

Range of FM and Power


What would cause this

Question:  first I replaced a motor mount on my 2001 Honda Odyssey and then a few weeks later that plug was like that but I did not blow it all the way out of the cylinder it was still partially threaded in which an end result I had to Helo coil the head And I solve that issue but I'm still like to know what would cause a spark plug to do that then a few weeks later I'm coming down the highway and getting off an exit and take the vehicle just dies lost power and could not get it started after that try to have a jumped it wouldn't start when I had the starter tested they said the starter was bad I replaced the starter still no starting I need help
Comment: Welcome to Motor Vehicle Maintenance & Repair! That is just about the most ugly plug I've EVER seen. As far as the engine running (or not), are you getting any action out of the engine? I mean, does it feel like it wants to fire, or is it just spinning without anything happening? What have you done to diagnose? Is there spark/fuel?
Answer: I've never seen anything quite that bad, even on Ford "Trident" modular V engines that were notorious for such things.
Either the plug was or became loose, and many miles of combustion eroded away a groove that later allowed hot gas/exhaust to melt the boot.
The fact it's down one channel suggests the threaded part of the plug may have developed or had a crack in the threads, which eventually provided an erosion path which digested the plug.  Another possibility is a crack in the center electrode insulator, which caused the arc to jump midway from the ceramic to the steel side of the thread.  The arc would find the shortest path to ground.  Since the arc would be jumping to steel and not platinum, it would erode quickly.  If you can clean the center electrode insulator carefully, you may be able to discover this crack.
Pure speculation, as that plug does not look like it would fire at all - which means there would be no hot combustion products along with a host of rough running, fuel consumption, and check engine light problems.
Make certain the vehicle has the right plugs.  The wrong brand and/or heat range may have contributed to the issue.  That Honda will most likely have come with platinum or Iridium plugs made by NGK as the OEM fitment.  Denso and Bosch would work as well, but I would be very hesitant to throw in cheap 99 cent Autolites.  Modern Asian OEMs use small electrode platinum plugs as a mandate.  What parts store claim "fits", may cause a bunch of problems later.  It's painful, because the factory Iridium plugs might cost 14-16 bucks each.
Comment: Plug was loose for sure.
Comment: @Moab hard to tell, but the center electrode appears to be gone.  I'm leaning more towards the spark leaping of the threaded steel bore, and carrying metal away on every spark.  In any case, pretty ugly.  Might have even caused a fire.
Comment: Nah, it was loose and hot combustion gases escaping up the very loose threads did the damage, not electricity.
Comment: @Moab You're probably right, but I'm surprised it's up one channel and not uniformly melted around the threads.  Back to a possible vertical crack in the threaded portion from the start.  After all, the plug itself is *always* exposed to hot combustion gasses, so why don't they all melt?  I suppose if it was loose the heat transfer away from the plug may have been compromised.
Comment: Hot gases are much hotter when concentrated and moving through a high pressure leak, its like a blow torch.
Answer: i have seen this happen on A track where nitro is being used . absolutly can melt the plug body from intense firing . also can damage the engine .. other than what i suggest the plug may have been faulty and just melted  . either way the plug melted and has caused deeper engine probably piston big end damage.

What would cause this


move/copy file using an ftp server

Question: Is it possible (and how) to copy a file on a remote machine to a different place on the same remote machine using FTP?
Answer: I suspect it would depend on the ftp server, but you can accomplish a move with the ftp rename command.
Comment: I have total control on the kind of server I use, which one supports `copy`?
Answer: Do you specifically need to make a copy of the file, so that a full copy of it exists in each of two paths, as opposed to just moving/renaming a single instance of the file?
If so, the FTP protocol does allow it, in a couple of different ways:

FTP has for a very long time allowed a user to coordinate server-to-server FTP transfers from one client.  You could use this method via two separate control connections to the same server to get the server to "talk to itself" via FTP to transfer the file.  See RFC 959 section 2.3 (specifically Figure 2), and section 5.2.
The FTP "SITE" command allows any FTP server to provide "site specific" features, which could include allowing you to do copies.
Answer: Why do you want to use FTP instead of the OS copy|cp|whatever command for this?  Do you only have FTP access to the server?  Can you not telnet|ssh|RDP|etc instead?
Anyway, with FTP the name is giveaway: "transfer" and "protocol" should tell you that it's for transferring files across a network, and will have limited capability to interact with the filesystem.  FTP isn't a general purpose filesystem tool.
Answer: You can rename file using RNFR and RNTO FTP commands (see Rename function in your favorite FTP client).
Most FTP servers does support renaming '/folder/file' to '/another/folder/another-file' as long as target directory does exists.

move/copy file using an ftp server


Can I Connect dashcam Blackvue DR900S on OBDII connector in Volvo XC70 2015?

Question: Do I get 12V on OBDII pin 16 without ignition ON?
Comment: OBD is not a good way to power anything. What are you trying to accomplish, to keep your dashcam running all the time? You will run your battery down faster.
Comment: I am aware of running the battery down, but this will not be an issue on a short time (3-4 hours). My concern is about OBDII-pin 16 gives batterypower without ignition ON.
Comment: @GdD nah they have sleep and wake up mode on good ones. I leave mine powered all the time, no issue's. Its a great security camera for my van. I don't see nothing wrong with powering from OBD2, its usually the same fused line that is going to one of the cig lighter plugs anyway.
Answer: Not a good idea - leave the OBD connectors for OBD. Instead, a simpler solution is to look for an add-a-circuit device in your local car spares store. Plug it into a known 12V supply in the cars cabin fusebox, and run the power lead to the dashcam.
This is a much quicker solution than trying to find switched 12V in the OBD connector, and is completely reversible if you want to remove the dashcam when you sell the car.
Answer: Yes you get constant voltage from pin16 on a OBD2 even with out ignition on. It is a direct fused line in most cases and a lot of the times it is also the same fused line as the main cigarette lighter plug (many people use to plug in accessories).


Python for a Perl programmer

Question: I am an experienced Perl developer with some degree of experience and/or familiarity with other languages (working experience with C/C++, school experience with Java and Scheme, and passing familiarity with many others).
I might need to get some web work done in Python (most immediately, related to Google App Engine). As such, I'd like to ask SO overmind for good references on how to best learn Python for someone who's coming from Perl background (e.g. the emphasis would be on differences between the two and how to translate perl idiomatics into Python idiomatics, as opposed to generic Python references). Something also centered on Web development is even better.
I'll take anything - articles, tutorials, books, sample apps?
Thanks!
Comment: http://www.python.org/doc/2.5.4/tut/tut.html
Answer: I've recently had to make a similar transition for work reasons, and it's been pretty painful. For better or worse, Python has a very different philosophy and way of working than Perl, and getting used to that can be frustrating. The things I've found most useful have been

Spend a few hours going through all the basics. I found the official tutorial quite good, if a little dry.
A good reference book to look up basic stuff ("how do I get the length of a string again?"). The ones I've found most useful are the Python Pocket Reference and Python Essential Reference.
Take a look at this handy Perl<->Python phrasebook (common tasks, side by side, in both languages).
A reference for the Python approach to "common tasks". I use the Python Cookbook.
An ipython terminal open at all times to test syntax, introspect object methods etc.
Get pip and easy-install (to install Python modules easily).
Learn about unit tests fast. This is because without use strict you will feel crippled, and you will make many elementary mistakes which will appear as runtime errors. I recommend nose rather than the unittest framework that comes with the core install. unittest is very verbose if you're used to Test::More.
Check out Python questions on Stack Overflow. In particular, Python - Things one MUST avoid and Python 2.x gotcha's and landmines are well worth a read.

Personally, I found Dive Into Python annoying and patronising, but it's freely available online, so you can form your own judgment on that.
Comment: Can you explain the "different philosophy and way of working"?
Answer: If you happen to be a fan of The Perl Cookbook, you might be interested in checking out PLEAC, the Programming Language Examples Alike Cookbook, specifically the section that shows the Perl Cookbook code translated into Python.
Answer: Being a hardcore Perl programmer, all I can say is DO NOT BUY O'Reilly's "Learning Python". It is nowhere NEAR as good as "Learning Perl", and there's no equivalent I know of to Larry Wall's "Programming Perl", which is simply unbeatable.
I've had the most success taking past Perl programs and translating them into Python, trying to make use of as many new techniques as possible.
Answer: Check out the official tutorial, which is actually pretty good. If you are interested in web development you should be ready at that point to jump right in to the documentation of the web framework you will be working with; Python has many to choose from, with zope, cherrypy, pylons, and werkzeug all having good reputations.
I would not try to search for things specifically meant to help you transition from Perl, which are not to be of as high of quality as references that can be useful for more people.
Answer: This is the site you should really go to. There's a section called Getting Started which you should take a look. There are also recommendations on books. On top of that, you might also be interested in this on "idioms"
Answer: If what you are looking at is succinct, concise reference to python then the book Python Essential Reference
might be helpful.
Answer: I wouldn't try to compare Perl and Python too much in order to learn Python, especially since you have working knowledge of other languages. If you are unfamiliar with OOP/Functional programming aspects and just looking to work procedurally like in Perl, start learning the Python language constructs / syntax and then do a couple examples. if you are making a switch to OO or functional style paradigms, I would read up on OO fundamentals first, then start on Python syntax and examples...so you have a sort of mental blueprint of how things can be constructed before you start working with the actual materials. this is just my humble opinion however..
Comment: Psst.  Modern Perl developers use OO just as much as anyone else.  And, as usual, TMTOWTDI. ;)
Comment: @jellyfishtree - i'll try to not be offended, but really, that assumption was a bit uncalled for. I write fully OO code in Perl (as well as C++) - I did say I was an experienced Perl developer, not a script monkey - in addition I can do functional programming although with far less experience/quality :)
Comment: Perl and Python OO systems are very similar - Perl'
s one was copied from Python.
Comment: Robert P: Not modern too - OO appeared in Perl long ago.
Comment: ahh, snap..i forgot. Perl packages right? no offense intended, just so used to people using it for procedural scripts I forgot about the possibility.

_| ̄|○

Python for a Perl programmer


Non parametric density estimation

Question: In general it's possible to estimate a given multivariate density function $f(x)$  using some non-parametric methods such as kernels or histogram. What are the conditions on a function $g$ such that the estimation of $g(f(x))$ will be consistent as well?
Comment: It all depends on the convergence properties of $\hat f_n$ the estimator of $f$. Under strong uniform consistency, the property is preserved by continuous transforms.
Comment: It's hard for me to see why this is tagged "regression" or "multiple-regression". I removed those tags and added "kernel-smoothing" and "histogram".
Answer: Let $x$ be a fixed vector, the estimate of its density, $\hat{f}_{n}\left(x\right)$.
Let $g\left(\cdot\right)$ be a differentiable function where the derivative of $g$ is bounded in an open neighborhood of $f\left(x\right)$. From the mean value theorem:
$g\left(\hat{f}_{n}\left(x\right)\right) - g\left(f\left(x\right)\right) = g'\left(y_{n}\right) \times \left[ \hat{f}_{n}\left(x\right) - f\left(x\right)\right]$, where $y_{n}$ is a value between $\hat{f}_{n}\left(x\right)$ and $f\left(x\right)$.
Because $\hat{f}_{n}\left(x\right) \overset{p}\rightarrow f\left(x\right)$.  With probability $1$ in a large enough sample, $y_{n}$ will be close enough to $f\left(x\right)$ that $g'$ is bounded.  Say $|g'| \le M$ in the neighborhood of $f\left(x\right)$.
$\text{pr}\left\{|g'\left(y_{n}\right) \times \left[ \hat{f}_{n}\left(x\right) - f\left(x\right)\right]| > \epsilon\right\} \le \text{pr}\left\{ M \times |\hat{f}_{n}\left(x\right) - f\left(x\right)| > \epsilon\right\} \rightarrow 0$.
Where the limit holds because $\hat{f}_{n}\left(x\right) \overset{p}\rightarrow f\left(x\right)$.

Non parametric density estimation


How can I test if a particular alias is defined?

Question: I have a bash script that needs to behave differently if a particular alias is defined. Is there a way to test if a particular command is an alias in bash?
Comment: `type -t `
Comment: @jimmij: You should make that into an answer.
Answer: If alias is passed an alias name without =value, it just prints the alias definition if that alias is defined, or fails with an error if there's no such alias.
So you can just do:
if alias your_alias_name >/dev/null 2>&1; then
  do_something
else
  do_another_thing;
fi

(replace your_alias_name as required)
Answer: I'm gonna make @jimmij's comment from 5 years ago into an answer:
type -t is designed for exactly that purpose. It will output alias if the given command is an alias. If the command does not exist, it won't output anything, which means you don't need to redirect its stderr or something.
Example:
if [ "$(type -t foo)" = 'alias' ]; then
    echo 'foo is an alias'
else
    echo 'foo is not an alias'
fi

Note that the -t switch is not defined in POSIX. Shells other than bash might not implement it.
Answer: Word of warning:

Shell functions and aliases are limited to the shell and do not work
in executed shell scripts.

Found in https://askubuntu.com/a/98796 , confirmed by my own bitter experience.
Somewhat annoyingly this is not mentioned explicitly in the relevant section of the Bash user manual, the only hint is that

Alias expansion (see Aliases) is performed by default.

which was not intuitive enough for me; YMMV.
In short, all the technologies mentioned in the other answers work only if you check aliases defined in the same script (or in another file you source-d into your script). You cannot check from within a (non-interactive) script whether an alias was defined in the shell where you invoked said script.
Here is a little script aliastest.sh that demonstrates the issue:
#!/usr/bin/env bash

shopt -s expand_aliases

is_alias() {
    if [[ "$(type -t $1)" == "alias" ]]; then
        echo "$1 is an alias"
    else
        echo "Cannot find $1"
    fi
}

# == MAIN ==

if [[ $# -lt 1 ]]; then
    echo "Usage: $0 <command> [ <command> ...]"
    exit 1
fi

for cmd in $@; do
    is_alias $cmd
done

Let's assume you defined the popular ll alias in your shell with the command alias ll='ls -alF' (you may have it already). If you run ./aliastest.sh ll it will tell you Cannot find ll.
But despair not, there is a workaround:
If you tell Bash to run your script as "interactive", then it'll "see" the aliases defined in the shell you invoked it from:
bash -i aliastest.sh ll

It will answer ll is an alias.
Answer: You can write like this
[[ $(type your_alias) == *"alias" ]] && echo "alias defined" || echo "alias undefined"

Example:
[[ $(type fd) == *"alias" ]] && echo "fd is an alias" || echo "fd is not an alias"

Another option can be
[[ -z $(alias | grep 'll=') ]] && echo "alias not found" || echo "alias found"

Comment: Your modified answer would say that `ll` was an alias if the string `ll=` occurs in any alias definition, regardless of whether `ll` was an alias or not. (A solution for `zsh` would look identical to a solution for `bash`, BTW).
Comment: Deb 11, not working as presented. `ll` is alias to `ls -l`, but `[[ $(type ll) == *"alias" ]] && echo "alias defined" || echo "alias undefined"` results `alias undefined`. If is isn't the way your suggested answer should be understood, you should [edit](https://unix.stackexchange.com/posts/740904/edit) it so that how this is supposed to be done is clear.
Comment: This does not work in `bash` as the `type` command never outputs anything that starts with the string `alias`.


Getting your nested div to behave like table cell

Question: I know about display: table/table-row/table-cell styles.
What if I want to apply table-cell style to deeper element in DOM structure and get the same effect.
Please, look at r2c1 cell. As you see it has other width then other cells in this column.
http://jsfiddle.net/forus/G6daP/3/
Is it possible to get autoresizing for this cell as well?
Answer: I tried with this approach.
I don't know if you need the table display properties for that particular element, since you talked only about anto resizing.
If that's what you are looking for, I think this could be a solution.


Number of faces in a 3D multi-type unstructured grid

Question: Given a 3D unstructured grid consisting of mixed types of shapes (hex, tet, ...), is there a method to know how many faces (including boundary faces) are contained in the grid?
Comment: Besides counting them? For instance, 3D tet mesh generators will return lists of faces. I'd be surprised if face information weren't returned, because it is useful for surface integration.
Comment: I think Shibli is asking about the number of all faces (boundary and interior). In my experience, mesh generators usually don't output this information.
Comment: @MartinVymazal: Yes, I interpreted the question as calculating the total number of faces. TetGen, for instance, returns a list of faces as a list of 4-tuples of vertices. If only elements are returned, it is straightforward -- if tedious -- to decompose elements into faces.
Comment: Is the grid conforming? If that is true, and you have the number of boundary faces available, you can iterate over all grid cells, accumulating the total faces, add the number of boundary faces and divide by two (since each internal face is shared between exactly two cells, and you explicitly double-counted the boundary faces).
Answer: You might be interested in Euler's characteristic, which relates the number of vertices, edges and faces in a planar graph, that you can also interpret as a 2D mesh. There is a similar relation for 3D meshes (see for example here (section about tetrahedral meshes) or here. The problem is that in 3 dimensions, this (single) formula relates the number of vertices, edges, faces and elements in your mesh. Most mesh generators give you immediately number of elements and vertices, but not the number of faces and edges, so you are left with one equation and two unknowns. I'm afraid there's no easier way than counting the edges or faces.


How many elementary particles are there?

Question: I was reading QED by Feynman (a dated book) and he seemed to be suggesting we have discovered hundreds of particles. But I thought there were only the ones we saw in the standard model (ie leptons, quarks, gauge bosons, higgs boson)? Why aren't all those hundreds of particles included in the typical "periodic table" for elementary particles?
Comment: [The particles were composite particles.](https://en.wikipedia.org/wiki/List_of_particles#Composite_particles)
Comment: In Feynman's time, physicists didn't fully realize that among the 100s of particles they thought existed, many of which were in fact the same.
Answer: After  the quark model was established and the standard model was accepted as the theoretical framework for elementary particles, it became obvious that the great number of resonances could be organized into group representations of the standard model's group structures.
These are still recorded and sought after according to the predictions of the standard model. The particle data group does a good job of keeping the records.
Answer: Part of the problem lies with the definition of "elementary". Before the discovery of nuclear physics atoms were considered elementary. This chemical definition overlooked the (then unknown) fact that most naturally occurring elements are mixtures of different isotopes. After nuclear physics was established, the electron, proton and later neutron were considered elementary, although that didn't last long. Soon it became clear that protons and neutrons themselves are made of constituents. Now we consider quarks elementary. This, of course, is a very good definition up to the TeV energy range because the current experiments show no sign of there being an internal quark structure (and much less so an internal structure for electrons).
While some are sufficiently confident that we have peeled back the last layer of this onion, it's a good idea to keep in mind that our predecessors thought the same thing after they had discovered atoms etc.. On some level, of course, we have become more cautious with the use of the word, as string theory shows, which tries to reduce the current zoo of "elementary" particles to an even smaller one, in which everything can be described as vibrations of strings.
I think it's a pretty good bet that today's "elementary particles" will be modeled as excitations of something even more fundamental tomorrow.
Comment: Although the difference is "stuff" smaller than the SM has not been proven to exist and I am asking questions about known to exist "stuff". Still point taken. One should always keep an open mind.
Comment: @StanShunpile: Good point. One can still consider atoms elementary for the purposes of chemistry and we will probably continue to consider quarks and electrons as elementary for sub-TeV physics purposes, so the definition is not just a matter of history, but also one of the hierarchy of models to describe reality in increasing level of detail. Anna basically gave you the correct answer to that... the grailskeepers of the standard model like the PDG are keeping track of the properties of these particles.


In Vmware Workstation Guest, how to identify which network connection is hostonly and which is NAT?

Question: I'm using Vmware Workstation for my lab environment. I added two network interface cards for a Guest OS. In the Guest Os (Win 2016 server), I can see there are two network connections. But how can I identify which connection is for the hostonly card and which is for the NAT card? Thanks.
Answer: If I understand your question properly, you are asking: how can I distinguish between two different external network interfaces/connections from within the guest OS ? (aside from IP address assigned)
The simplest way: adapter in VMware appear to the guest OS in the order they are defined in the VM settings. but it may not be the most reliable in windows environment.
The proper way
Well, for the guest OS, the only way is to rely on the MAC address of the virtual interface. The guest will see virtual network MAC address, but you can change it/assign it yourself in VMWARE settings.
if you go to your virtual machine settings, select the 1st network adapter (let's say it is the one set to host-only), click "advanced" button,  you can note or change the MAC address listed at the bottom of the dialog box.
you can do the same for the 2nd adapter. now you can use these MAC addresses to distinguish between the two adapters in the guest OS.


Intonation on a classical guitar

Question: Aaaagh, it's driving me crazy! My yamaha is massively sharp on two strings at 7,9 and 12 and flat on 1 string.           I know how to fix the flat (using a diamond nail file etc) but not the sharps, can it be done with a thicker saddle? Effectively shortening the string length by a mm and then filing it to correct the other strings
Comment: The thickness/mass/gauge of a string will affect its intonation. Be sure you have the correct strings, or maybe change to a different gauge first.
Comment: @Tim because of varying stiffness?
Comment: @phoog - depends what 'stiffness' means. All strings on my guitars are about the same *tension*, but beause they're different *gauges*, their intonation is sorted by them being different speaking lengths.
Comment: It would be very unusual to have three strings playing out of tune and three that are okay. Occasionally strings are badly made, so that might be one possibility. Otherwise I'd suggest visiting a luthier. . .
Answer: Solved! After much trial and fail with the saddle I found a brilliant luthier at my local shop who gave me (and yes I do mean gave me) a set of d'addario Pro arte strings, the D which with d'addario classic strings was a semi tone sharp at 12th fret is now perfect as are all the strings. Who would believe that strings could make SO much difference!
Note to other Yamaha C40 owners:They don't love D'Addario classic strings! And yes I went back to the shop and thanked and paid the brilliant Luthier Richard.
Comment: Hi buddy, I fitted EJ49 strings to remedy my intonation problem, I'd suggest a visit to the excellent music shop too but Plymouth, England may be a bit far!
Answer: You can adjust the intonation either sharper or flatter by filing on the back or front of the saddle.
To adjust flatter, file the front side of the crown of the saddle to move the point of contact back and lengthen the sounding portion of the string.
To adjust sharper, file the back side of the crown of the saddle to move the point of contact forward and shorten the sounding portion of the string.
(Be sure to mark the saddle when you remove it so you can reinstall it with the same orientation.)
Comment: Yeah that's the way I know but I think I've run out of adjustment with the saddle that's fitted. Some of the strings are way out on the 12th fret.
Comment: Sadly, that's about the limit of my expertise. It may be that more extreme measures are called for, like repositioning the bridge or making a custom saddle piece that extends farther in the needed direction. But I've never done anything like that so I can't really advise further. I've seen luthier videos on YT where these things are done.
Comment: Yeah that's the direction I seem to be heading, I'm a cabinet maker so custom anything is right up my boulevard, but I'd rather there was a simple remedy such as lighter strings or devine intervention, thanks buddy.

Intonation on a classical guitar