What settings does Windows use to determine network location?

Question: Windows has the concept of network location awareness (NLA), which means that you can configure a network as "public" (i.e. home/work), "private", etc..
What information does it use to "fingerprint" a network for this purpose?
Answer: Source: http://msdn.microsoft.com/en-us/library/ms740558%28VS.85%29.aspx

The Network Location Awareness (NLA) service provider is vital for computers or devices that might move between different networks, and for selecting optimal configurations when more than one is available. For example, a wireless computer roaming between physical networks can use NLA to determine the proper configuration based on information about its available network connection. NLA also proves valuable when a multihomed computer has a physical connection to one network while also connected to another network through a dial-up connection or a tunnel.
In the past, developers had to obtain information about a logical network interface, and therefore make decisions about network connectivity, based on a multitude of disparate network information. In those circumstances, developers had to choose the appropriate network interface based on the IP address, the subnet of the interface, the Domain Name System (DNS) name associated with the interface, the MAC address of a NIC, a wireless network name, or other network information. NLA alleviates this problem by supplying a standard interface for enumerating logical network attachment information, correlating it with physical network interface information, and then providing notification when previously returned information gets invalidated.
NLA provides the following network location information:

Logical Network Identity
NLA first attempts to identify a logical network by its DNS domain name. If a logical network does not have a domain name, NLA identifies the network from custom static information stored in the registry, and finally from its subnet address.

Logical Network Interfaces
For each network to which a computer is attached, NLA supplies an AdapterName that uniquely identifies a physical interface such as a NIC, or a logical interface such as a RAS connection. The AdapterName can then be used with functions available in the IP Helper API to obtain further interface characteristics.

NLA implements the logical network as a service class, with an associated class GUID and properties. Each logical network for which NLA returns information is an instance of that service class.
Answer: See http://msdn.microsoft.com/en-us/library/aa480195.aspx
JR
Answer: Based on recent experimentation (with Server 2012, but I suspect earlier versions are similar) on non-domain, statically configured networks the NLA service uses the link-layer (MAC) address of the default gateway to identify the network.
The details are unclear, though I suppose they could be worked out with a network analyzer.  If the configured default gateway does not respond, NLA does not recognize the network, so it's definitely doing some sort of query.  (That is, you can't just put in a dummy gateway address, or even a dummy gateway address plus static arp entry; the gateway MAC address associated with a particular network must actually respond in order for NLA to decide that the adapter is connected to that network.)
See also my blog entry on a way of fooling Windows 2012 into assigning an adapter to a unique network.
If the adapter is assigned an address by DHCP, the logic might be different.  I haven't looked into that yet.  The logic on a domain network is documented as per the existing answers.


Is it okay to have a dryer vent in the wall cavity?

Question: I'm redoing the wall of a utility room that, among other things, has the dryer vent embedded in the wall cavity with all kinds of stupid turns to go around the plumbing. Would it be a good idea to remove the vent from the wall and have it just out in the open to facilitate cleaning? Or is it okay to have it in the wall cavity?
Comment: Sharp turns cause reductions in airflow and can accumulate lint faster. Longer runs are also flow reducing.. It would be helpful to know how far your wall run is and how many 90 degree turns are used.
Comment: I'm more wondering if there's anything inherently wrong with having the vent inside the wall, even if, say, it was a perfectly vertical 5-foot vent. Seems like it would be more difficult to clean or notice a problem if it were in the wall. And indeed, once I tore the drywall off, I found that the vent wasn't actually sealed up inside the wall cavity and had been depositing moist air right onto a stud.
Answer: One of the leading causes of house fires is dirty or plugged clothes dryer vents. Dryer vents should not be installed in ways that make them difficult to clean and inspect.  Any vent in a wall cavity should be made of solid metal, with all joints sealed with metallic tape. There should not be any tight turns and they also need to be sized properly to the distance run. Flexible or corrugated plastic ducts should never be used in enclosed areas. When possible, it is safer to have vents exposed, as short as possible, made with metal duct with a minimum of bends. Ducts should be inspected for excess lint and vermin debris regularly and cleaned on regular intervals, usually every 6 months or annually depending on your usage. Also, anytime you see that your dryer is taking longer than usual to complete a drying cycle, it is a good idea to check the venting for problems.
Comment: **ALL** dryer ducting should be smooth walled solid metal ducting. **Not** flexible, **Not** corrugated, and **Not** plastic.
Comment: That's sounding like a "no" to me.
Comment: I don't believe it is against IRC as long it is sized properly, but I personally would not have one that could not be accessed and cleaned.
Comment: Yeah, I'm not really asking what the code says. I'm asking what's sanest.
Comment: the safest way is to leave it exposed. that is my advise to you.


How to find the page number from a paragraph using OpenXML?

Question: For a Paragraph object, how can I determine on which page this is located using the Open XML SDK 2.0 for Microsoft Office ?
Comment: Short answer: Not possible at the OOXML data level alone.  [See here for a detailed explanation.](https://stackoverflow.com/a/40139811/290085)
Answer: It is not possible to get page numbers for a word document using OpanXml Sdk as this is handled by the client (like MS Word).
However if the document you are working with is previously opened by a word client and saved back, then the client will add  LastRenderedPageBreak to identify the page breaks. Refer to my answer here for more info about LastRenderedPageBreaks. This enables you to count for the number of LastRenderedPageBreak elements before your paragraph to get the current page count.
If this is not the case then the noddy option to work around your requirement is to add footers with page numbers (may be with same colour as your documents to virtually hide it!). Only an option - if you are automating the word document generation using OpenXML sdk.
Answer: @Flowerking : thanks for the information.
Because I need to loop all the paragraphs anyway to search for a certain string, I can use the following code to find the page number:
using (var document = WordprocessingDocument.Open(@"c:\test.docx", false))
{
    var paragraphInfos = new List<ParagraphInfo>();

    var paragraphs = document.MainDocumentPart.Document.Descendants<Paragraph>();

    int pageIdx = 1;
    foreach (var paragraph in paragraphs)
    {
        var run = paragraph.GetFirstChild<Run>();

        if (run != null)
        {
            var lastRenderedPageBreak = run.GetFirstChild<LastRenderedPageBreak>();
            var pageBreak = run.GetFirstChild<Break>();
            if (lastRenderedPageBreak != null || pageBreak != null)
            {
                pageIdx++;
            }
        }

        var info = new ParagraphInfo
        {
            Paragraph = paragraph,
            PageNumber = pageIdx
        };

        paragraphInfos.Add(info);
    }

    foreach (var info in paragraphInfos)
    {
        Console.WriteLine("Page {0}/{1} : '{2}'", info.PageNumber, pageIdx, info.Paragraph.InnerText);
    }
}

Comment: **To all future visitors.. the op thinks this answers his question. But it fails in lot of cases. It fails when you are using multi-column layout. Also `run.GetFirstChild();` is going to give you all kinds of breaks which might include breaks other than just page breaks. So keep in mind these points when using the above code.**
Comment: doc where you have LastRenderedPageBreak will have Break as well, so just using Break check will be fine. But there are scenarios where there wont be any breaks but content to extended to multiple pages, How do you identify and separate the content by page?
Comment: Nice. I should be delivering similar code in my answer if you included  some code in your Q.
One catch =>  `var pageBreak = run.GetFirstChild();` in Open Xml - Not all `Break`s are pagebreaks!
Answer: Here's an extension method I made for that :
    public static int GetPageNumber(this OpenXmlElement elem, OpenXmlElement root)
    {
        int pageNbr = 1;
        var tmpElem = elem;
        while (tmpElem != root)
        {
            var sibling = tmpElem.PreviousSibling();
            while (sibling != null)
            {
                pageNbr += sibling.Descendants<LastRenderedPageBreak>().Count();
                sibling = sibling.PreviousSibling();
            }
            tmpElem = tmpElem.Parent;
        }
        return pageNbr;
    }

Comment: LastRenderedPageBreak is not always available
Comment: This will only count the number of inserted page breaks in an existing document, e.g. once it has been opened in Word, which will insert the breaks. If you are generating the document yourself, using the SDK, the only page breaks in the document, will be the ones you have inserted youself, which you would not need to count.


Can libnet be used to inject tcp packets/packet mangling?

Question: I just took a glance at the introduction of libnet,
seems it mentioned support for udp,ip,but not tcp?
Does it support tcp at all?
Answer: Looking here, there seems to be a function related to tcp, so I guess yes, you can inject tcp segments with libnet.
<code>int libnet_build_tcp(u_short sport, u_short dport, u_long seq,
            u_long ack, u_char control, u_short win, u_short urg,
            const u_char *payload, int payload_s, u_char *buf);
</code>

libnet_build_tcp() builds a TCP
  (Transmission Control Protocol)
  packet. Supplied is the source port,
  destination port, the sequence and
  acknowledgement numbers, the control
  bits (which can be logically OR'd
  together to set multiple flags -- see
  the example below), the advertised
  window size, the urgent pointer, a
  pointer to an optional data payload,
  the payload size, and lastly, the
  pointer to a pre-allocated block of
  memory for the packet. To just build a
  TCP header with no data payload, only
  TCP_H bytes need be allocated.


How to reduce LCD brightness if intel_brightness is unistalled?

Question: tried echo,xrandr and even xbacklight couldn't reduce backlight of my screen. Can anyone suggest any other way?
Answer: If you want to change the screen brightness in Ubuntu (I can't change it using the keyboard shortcuts or the Ubuntu Power Management menu), open a terminal and execute the following:
sudo setpci -s 00:02.0 F4.B=xx
Where xx is the desired brightness in hex ranging from 0 (brightest) to FF (no brightness at all). I usually change it to E0 when working on battery.
Answer: One such program that can dim a display which does not have backlight control built in is a program called Redshift
Redshift's purpose is to warm the colours of your screen during the night to make late-night computer use easier on your eyes.
It also has screen dimming functionality built into the app that does not require a dimm-able screen backlight, and if you so wish, you can use it purely for this purpose by disabling the colour-warming.

NOTE: To install redshift, you must have enabled Ubuntu's Community-maintained free and open-source software repository codenamed 'universe'
In Ubuntu 14.04, this should be enabled by default. If you have for some reason disabled the universe repository, you can follow the instructions in this thread to re-enable them!

To install and configure Redshift on Ubuntu 14.04 for the purpose of dimming your screen:

Enter the following command into a terminal window (open the terminal window by pressing ctrl+alt+t)
sudo apt-get install redshift-gtk
Go to latlong.net and find the appropriate latitude and longitude for your city. Then enter the following command into a terminal window using the location you find as lat:lon.
(you can skip this step if you don't want the brightness to change based on whether it is currently night or daytime)
redshift -l lat:lon
e.g. for Sydney, Australia you would enter:
redshift -l -33.867:151.207
Enter sudo nano ~/.config/redshift.conf in a terminal window to create a config file for redshift, this file is where you are going to set the brightness and temperature that Redshift is going to set your screen at.
Documentation for this file is sparse, but a full example can be seen on the project's website
You are going to want to type the following into the config file:

[redshift]
  temp-day=6500
  temp-night=6500
  gamma=1.0
  brightness-day=0.6
  brightness-night=0.6

If you wish to further customize the config, here is my config file with comments to explain each setting:

; Global settings for redshift
  [redshift]
  ; Set the day and night screen temperatures
  temp-day=5800
  temp-night=4600
; Enable/Disable a smooth transition between day and night
  ; 0 will cause a direct change from day to night screen temperature.
  ; 1 will gradually increase or decrease the screen temperature
  transition=1
; Set the screen brightness. Default is 1.0
  ;brightness=0.9
  ; It is also possible to use different settings for day and night since version 1.8.
  brightness-day=1.0
  brightness-night=1.0
  ; Set the screen gamma (for all colors, or each color channel individually)
  gamma=1.0
  ;gamma=0.8:0.7:0.8
; Set the location-provider: 'geoclue', 'gnome-clock', 'manual'
  ; type 'redshift -l list' to see possible values
  ; The location provider settings are in a different section.
  location-provider=manual
; Set the adjustment-method: 'randr', 'vidmode'
  ; type 'redshift -m list' to see all possible values
  ; 'randr' is the preferred method, 'vidmode' is an older API
  ; but works in some cases when 'randr' does not.
  ; The adjustment method settings are in a different section.
  ;adjustment-method=randr
; Configuration of the location-provider:
  ; type 'redshift -l PROVIDER:help' to see the settings
  ; ex: 'redshift -l manual:help'
  [manual]
  lat=-26.658006
  lon=153.053269
; Configuration of the adjustment-method
  ; type 'redshift -m METHOD:help' to see the settings
  ; ex: 'redshift -m randr:help'
  ; In this example, randr is configured to adjust screen 1.
  ; Note that the numbering starts from 0, so this is actually the second screen.
  [randr]
  screen=0
Comment: Its good but he don't want to install anything.
Comment: Incorrect. He said that intel_brightness is uninstalled. This solution does not require him to install intel_brightness.

Additionally, this will work even if his monitor does not have a variable brightness backlight.


Can we use sshfs or NFS for LVM?

Question: I want to create LVM using sshfs or NFS. Is it possible at all? I tried searching over web but did not find anything. Forgive me if this question is wrong for this community.
Comment: It's not the wrong community *per se*, but this looks very [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me.  Instead of asking us how/whether one can do something that is a Bad Idea, how about you tell us what you're actually trying to do, and we might be able to help.
Comment: What are you trying to achieve?
Comment: Even if you were able to get this to work, me thinks it would perform terribly.
Answer: According to Is there a way to do something like LVM over NFS? it is possible.
Sensible is another matter: as noted in the answer to that question, if NFS (and/or the network) has an issue at any point, there is a strong chance your LVM will get corrupted.
I would have to assume that same risk applies (possibly more so) to SSHFS.
A possibly less brittle solution might be to have LVM underpinning your NFS exports - that sounds less risky, but without knowing your use case, I don't know if it would do what you wanted it to.
Updated I would have to agree with @MadHatter this is a XY problem, then.
In this case, it does sound like using LVM on your NFS server, and then exporting the LVM volume using NFS would be functionally equivalent, while avoiding (some of) the potential for corruption.
I suppose sharding could be mentioned here - see https://stackoverflow.com/questions/5541421/mysql-sharding-approaches for discussion about that.
Comment: Thanks for your answer. I would rather not do it. I was trying to a very large partition for a big SQL database with smaller hard drives.

Can we use sshfs or NFS for LVM?


Nominalistically Finding Radioactive Half-Life?

Question: In Science Without Numbers by Hartry Field he talks about stating things nominalistically. What seemed obvious to me is "How would you find radioactive half-life without math?". I looked all around and all methods to compute radioactive half-life all involved math. So here it is: how do you compute radioactive half-life in the method of Hartry Field(attractively nominalistically).
Answer: One way to express the concept of half-life without math is to fill a see-through container with pennies, marking their volume on the side with a horizontal line. Shake the container and then spread them out on a flat surface, removing all pennies that landed tails-up. Then return the remaining heads-up pennies back to the container. Mark the volume again (it should be lower). That's the first 'event'.
Repeat the same identical procedure with succeeding 'events', marking the changed volume each time, until there are no more pennies left. The side of your container should have several horizontal lines positioned one above the other. Observe the distances between the lines. Are they regular? Irregular? Graduated?
Next observe the line at the midpoint, approximately equidistant between full and empty (just eyeball it), representing the concept of "half-life". Compare the number of lines above it with those below that point. Are there more lines above it than below? Less? Or the about the same?

Use pennies to simulate unstable isotopes. When the pennies are heads up, they are radioactive (unstable). When the pennies are tails up, they have decayed to become stable isotopes.

How can you simulate radioactive half-life? (Socratic.org)
Answer: You don't.  But that is not a defense of Platonism.
You cannot nominalistically determine that the pattern of decaying along an exponential curve exists in a way that meet's Fields' criterion of conservative derivation.  So you cannot begin to calculate a number that describes the parameter for a given curve relevant to a given instance of decay.  You have to bring the mathematical concept to the facts first, and then you can look at ways to instantiate its reference to your case.
The problem with the underlying theory here is that it does not provide a way of learning nominalistically.  It is fully acceptable that mathematics is fictional, but, as Hume pointed out forever ago all observed patterns are fictional.  They inject abstraction that is not even real most of the time, and even then is more than is warranted.  The exact rate after the half-life averages out to half the original rate, but in almost no instance is it going to be exactly half.  What puts these events into a pattern is the fact there is an average, a fiction we create for our own convenience.  The notion of a nominalistic pattern is approximation to some mathematical proposal that we bring to the problems, from within our minds, because it works.  With just the nominalism and no mathematics, there is no capacity to describe the pattern.
In the absolute, real world there are only events, not relations between events.  Humans observe relations because we have developed the technology of the story, and we abstract those patterns into concise, separable concepts because we want to share them and to verify that other humans share them.  All the patterns we observe are predictive guesses imposed on the world, which have content because they are symbolic.  They can be transferred between people because they activate related imaginary content that is at some level shared, and otherwise negotiated.
There is no nominalistic science because science is about patterns, you cannot really name nonexistent objects, you can only name their interpretations as rulesets and the related expectations.  I can name unicorns, but a unicorn is not a thing, it is a set of rules about something, and if a thing obeys those rules, it is likely to be perceived by others as a unicorn.  I can name a person, or a place, or a rock.  But the concept of a rock is not a thing that can be named until it is assembled as a pattern: a set of rules, which is made of other names, held together by our shared notion of logical combination, which is mathematics.
Those patterns don't have to pre-exist.  They can be created at need.  And they do not constitute a separate reality because they are in fact not real.  They are artifacts of our potential for language, which is the possibility of fiction.  When your dog learns to respond to the word 'food', it is because he has the capacity to generate fictional food, to have the same reaction to a symbol (in this case, of sound) that he would have to the presence of actual nourishment.  That does not make the imaginary food real.
Popper's notion of falsifiability, and therefore active skepticism, as the basis of science, captures something real.  We do science by bringing our biases to reality and having their usefulness disproved until we find the set that is hardest to refute.  We are the authors of the fiction that becomes our descriptive context.  But that does not keep it from being mere creative content.
Answer: Hartry Field's nominalism claims that mathematics is not merely consistent and convenient to use in calculations, but it is also "conservative". He describes this conservativeness property in this way (page x):

...any inference from nominalistic premises to a nominalistic conclusion that can be made with the help of mathematics could be made (usually more long-windedly) without it. This is a fundamental difference between the use of mathematical entities and the use of the theoretical entities of science: no such conservativeness property holds for the latter. The utility of theoretical entities in science is due solely to their theoretical indispensability: without theoretical entities, no (sufficiently attractive) theory is possible.

This would mean that one should be able to find a method to compute the half-life of radioactive elements without using math. Perhaps one method would be to place a certain amount of the material on a digital scale with a timer and collect weights and times until one reached half of the original weight.
There might be more practical ways to actually do that half-life calculation, but it did not involve the use of exponentials and logarithms to reach the result. They would have been more convenient to use, but they were not necessary.
Leon Horsten notes that this conservative property is controversial and Stewart Shapiro may have demonstrated that a counterexample should exist.

If the fictionalist thesis is correct, then one demand that must be imposed on mathematical theories is surely consistency. Yet Field adds to this a second requirement: mathematics must be conservative over natural science. This means, roughly, that whenever a statement of an empirical theory can be derived using mathematics, it can in principle also be derived without using any mathematical theories. If this were not the case, then an indispensability argument could be played out against fictionalism. Whether mathematics is in fact conservative over physics, for instance, is currently a matter of controversy. Shapiro has formulated an incompleteness argument that intends to refute Field's claim.

The question asks how one might compute the half-life of a radioactive element. One way to do that would be to take measurements over time.

Hartry H. Field, Science Without Numbers: A Defense of Nominalism, 1980 Princeton.
Horsten, Leon, "Philosophy of Mathematics", The Stanford Encyclopedia of Philosophy (Spring 2019 Edition), Edward N. Zalta (ed.), forthcoming URL = https://plato.stanford.edu/archives/spr2019/entries/philosophy-mathematics/.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/90800/discussion-on-answer-by-frank-hubeny-nominalistically-finding-radioactive-half-l).


Community user add link for off-topic/merge questions

Question: Much like the Community user already does with duplicates where a comment is auto-added linking to the duplicate.  If a vote-to-close is given for a question belonging to a different Stack Exchange site could a link be added in a comment saying something like:  "This question might be better suited on x".
Answer: Maybe; but 10% of the time the first Off Topic close vote is for the wrong site or the question is crap and shouldn't be migrated anywhere anyway.
I have no data to back this up, but I've seen a few cases of people saying "oh you should use [other site]", then the original questioner copy-and-pasting their question on the other site, and then there's a pile of cleanup work to be done to close with comment or migrate then close as duplicate...
I've personally stopped leaving comments about other sites most of the time and just vote to migrate on the theory that a single post migrated once is easier than questioners duplicating their content on multiple sites.


Dense Cloud col attribute not showing

Question: I'm using metashape agisoft to generate dense cloud from images and I exported the points in PLY and imported to blender.
then used attribute named it col to get the original color what calculated by metashape but still not showing up.
in the spread sheet the colors data is showing.
Answer: As far as I know, when exporting the Point Cloud from MetaShape, the vertex color is saved (somehow), but there are the following problems:

In the OBJ format, a vertex color is stored, but this format does not actually support vertex color, so Blender does not read it (OBJ files and vertex colours).
In PLY format, a vertex color is stored and Blender could theoretically read it as well (but it does NOT), but that wouldn't make much sense anyway, since MetaShape doesn't seem to store correct colors here either.

The alternative is the FBX format. Here you also have a lot of ballast in the package, but it works. With Geometry Nodes you can read the attribute for the vertex color and you can also convert the mesh back into a point cloud.

Dense Cloud col attribute not showing


Data access layer using Linq to SQL

Question: I am building a c# - linq - sql server winforms/asp.net application, accessing a database. I would like my business logic layer to be easily testable, and that means not littering it with Linq database queries everywhere. What design patterns/ best practices are available for the following use cases
- inserting/updating a new object
- searching for an object
- loading a bunch of related data into a sort of "presentation" object that could be displayed by various views ?
Comment: Do you mean Linq to SQL?
Answer: Here is a six part article about Architecting LINQ To SQL Applications
Answer: The Repository Pattern is the one I think you're looking for
Answer: I recomend to view video lessons http://www.asp.net/mvc/videos#ASP.NET%20MVC%20Storefront%20Starter%20Kit Part 1-3 about services/repositories/filters. It's good solution.
Answer: Look into putting your database calls into a set of classes implementing a common interface (Repository pattern is a common way to do this).  Then you can mock these objects when running tests.  Just make sure the repositories themselves are tested somewhere too :)

Data access layer using Linq to SQL


How many peaches in 桃是水果?

Question: How do we know if there is only one peach or multiple peaches in the sentence
桃是水果?
How do we know in general? With the use of measure words?
Comment: We can't, without contexts. Anyway, does it matter in this sentence?
Comment: Not really. Though this was a fill in the blank and the answer was peaches instead of peach.
Comment: The character 桃 in 桃是水果 and 我吃了个桃, likes the character 人 in 中国人 (the Chinese people, 中国人民) and 中国人 (a Chinese person, 中国的人), the former one means **people** but not a particular **person**. The meaning of 桃 here likes that the Chinese character 人 in 中国人民 equals to the English word **people** but not one **person**.
Answer: https://en.wikipedia.org/wiki/Chinese_grammar
Plurals
Chinese nouns and other parts of speech are not generally marked for number, meaning that plural forms are mostly the same as the singular. However, there is a plural marker 们 [們] men, which has limited usage. It is used with personal pronouns, as in 我们 [我們] wǒmen, meaning "we" or "us" (from 我 wǒ, "I, me"), and can be used with nouns representing humans, most commonly those with two syllables, like in 朋友们 [朋友們] péngyoumén "friends" (from 朋友 péngyou "friend"). Its use in such cases is optional.[13] It is never used when the noun has indefinite reference, or when it is qualified by a numeral.[14]
The demonstrative pronouns 这 [這] zhè "this" and 那 nà "that" may be optionally pluralized by the addition of 些 xiē, making 这些 [這些] zhèxiē "these" and 那些 nàxiē "those".
Since Chinese nouns usually do not have plural form, we have to use plural markers to indicate plural like the Wiki article stated, you can also indicate a noun is singular or plural with measure words like 一個(a /one), 兩個 (two); or predeterminer like 所有(all) 有些(some)
In the case of " 桃是水果" we can deduct from the context that we are talking about "all peaches" , because 一個桃是水果 (a peach is fruit) doesn't make sense.
In 桃都是水果, 所有 is implied
Comment: 桃 是 水果  can mean "a peach is a fruit"  cf. jukuu:1.  Is a tomato a fruit or a vegetable? 蕃茄是水果还是蔬菜?
Comment: "a peach is a fruit" in Chinese is "一個桃是一個水果"
Comment: "蕃茄是水果还是蔬菜?" in English is  "Is tomato fruit or a vegetable? " here 蕃茄 meant "tomato" in general, "is (all) tomato fruit or a vegetable?" is implied.
Comment: 桃 是 水果 "a peach is a fruit" or  "peaches are fruits" or "peach in general is a fruit"
Comment: Totally on board with @TangHo here. Contextually there is nothing else that it could be other than  "all peaches", because there is no possible circumstance that someone is going to say '桃 是 水果' to mean anything else. I would even say translating "蕃茄是水果还是蔬菜? " as 'Is a tomato a fruit or a vegetable?' is wrong. It wouldn't be 'Is a tomato' rather 'are tomatoes'

How many peaches in 桃是水果?


How can I restore GTA V to how it was before I modded it?

Question: I installed some mods that won't let me play GTA and I changed some files using OpenIV. I don't have the Steam version, I have the disc version.
Comment: Have you tried uninstalling and reinstalling the game?
Comment: You should just backup (copy somewhere) the game files before committing any changes so that you don't have to reinstall the whole game.
Comment: I really don't want to do that because I've had to do that 3 times now.
Answer: There's really no way to fix it now unless you reinstall the game, but in the future, when installing mods to GTA V, follow these steps:

Open OpenIV and install the ASI Loader and such under 'tools > ASI Manager'. Make sure you install all 3 items by clicking "install" next to each one
When you go to edit any RPF or important file, or you go to replace files that were included with the clean game, right click on the item you are going to edit/replace and click "add to mods folder". This will put that file in the mods folder of GTA V, which will be loaded by OpenIV when you start the game. So basically when it launches the game, instead of getting car models from: Grand Theft Auto V/.../.../.../vehcles.rpf, it would get them from Grand Theft Auto V/mods/.../.../.../vehicles.rpf.
When you want to return to the clean GTA V, just go back into openIV, go back to 'tools > ASI Manager' and click uninstall for all 3. Also make sure to delete any external ASI loader like ScriptHookV or ScriptHookDotNet which will crash your game before entering online.

If you didn't edit any stock files (Ex, you just added files in the scripts folder and places like that), then deleting the added files would work to restore, but it sounds like you edited some stock GTA V files, so you would have to reinstall. Being a modder myself, the reinstalling gets tiring, but sometimes it has to be done!


Why does light travel as waves?

Question: Why does light travel as waves instead of say just a straight line? What are the forces that make a light photon travel in a wavelike pattern?
Comment: possible duplicate of [Why do we think of light as a wave?](http://physics.stackexchange.com/q/30402/)
Answer: Your wording suggests a few misconceptions:

It seems you are thinking of light as having a corpuscolar nature (nothing wrong with that, you are in good company).
Well it turns out that things just do not work that way.
Phenomena like diffraction (to name one) tell us that we cannot describe the behaviour of light thinking of it as composed by (classical) particles.$^\dagger$
When we say that "light is composed of oscillating electromagnetic waves", we do not mean that some physical entity that we call "light" is literally going up and down in space. What oscillate are the electric and magnetic fields composing the electromagnetic field.
And when saying that an electrical/magnetic field oscillates we mean that the intensity of that field is going up and down in some complicated way at every point in space. This has nothing to do with actual motion induced by some force.

$^\dagger$ It is probably mandatory at this point to point out that light can't be described as "just" electromagnetic waves either.
It has in fact a quantum mechanical nature, which means that it can be both wave-like and particle-like, depending on what you want to measure.
The double slit experiment is the canonical example of this.
If you still wonder as to why does nature work this way, I suggest you this Phys.SE question regarding the Why vs How issue in physics, and of course the classical Feynman's video.
Answer: There's a few things to disentangle in this question. Let's talk about photons first. It is not true that a "light photon" travels in a wavelike pattern. If you talk about light in terms of photons the (basic) picture you get is light as billiard balls, moving in straight lines. This is how ray tracing and its ilk work, because (in many situations) you can indeed model light as traveling in straight lines.
Now, if that's true, why do we talk about light waves? The reason is because there's another way to look at light, from the perspective of electromagnetism. In EM, we discover that changing electric fields produce magnetic fields, and vice versa. So imagine you have an electric field that is changing, and the rate at which it changes, is also changing. That E-field generates a magnetic field next to it, and because the E-field isn't changing constantly, that magnetic field itself is changing. Which means next to the magnetic field, an E-field is generated, which generates a magnetic field, etc. You can perhaps imagine how this would produce a wave, as the electromagnetic disturbance in one place gets passed along to other places. The wave theory of light is appropriate to use when you need to talk about interference--light can "get in its own way" in some sense, and this can't be described in terms of light rays and billiard ball photons.
The full reconciliation here depends on quantum mechanics, but what it comes down to is that a proper combination of waves appears to be localized into a wave packet. This "wave packet" looks like a single particle, but is in fact somewhat smeared-out, if that makes sense. If you were far away and not able to measure better, it'd look like a single particle--which is why it sometimes does.
Comment: I'm ok with this except for the last paragraph.  A wave packet is not a model for a "photon".  For example, if an intense wave packet is used in a photoelectric effect experiment, one would find the release of many, many electrons.  The distribution in time of the number of electrons released would follow the distribution in time of the intensity of the wave packet.
Comment: Correct me if I'm wrong but basically what you are saying (in simplest form) is that light can be described as wavelike because of the disturbances it has when going through the alternating electric and magnetic fields.

Why does light travel as waves?


How to make End Portal?

Question: I made a 3 by 3 portal with End Portal blocks and eye of the Ender in each block but it doesn't work. I did this many times in Creative mode, with and without a friend
Answer: The eyes have to face the inside of the portal.
You can do that by inserting the eyes while standing in the center of the portal, just make sure you get out before adding last eye, or you will finish the portal and immediately activate it, sending yourself into a boss fight.
Some sources say that only the last placed eye has to face inwards, I am not sure if that's true or not. It looks better if they all face inwards anyway :P

How to make End Portal?


Combustion of NaCl(aq) when testing conductivity

Question: In a experiment that dealt with electric conduction of many concentrated solutions, NaCl(s) created an unknown, to me, substance after adding a drop or two of water. Furthermore, it isn't the reaction of water and NaCl(s) that I don't understand, but the reaction between the anode and cathode when they came in contact with NaCl(aq), sparks were present and it seemed to have "burned" NaCl(s). The question is: what is the correct name for the part that "burnt"?
Comment: Nothing was burnt. You have just had a dangerous experiment. Apparently you have connected the two electrodes to a generator before dipping them into the solution. If an electric spark happened when touching the solution, it means that, before touching the liquid, there was a tension between the electrodes and no current. This is dangerous. You also may have been crossed yourself by an electric current. With wet hands, you may have been dead. You should never do this. Please put the electrodes into the solution before engaging the generator.
Comment: What kind of voltage did you apply here?
Comment: Not sure what is wrong with this question! Have you never seen sparking of closely placed electrodes in electrolytes?
Comment: To answer both questions at once: the voltage was your normal household voltage, well at least I think it was; the professor asked us particularly about what the "burnt" part of the salt was and she also added, in the question, why were there sparks, that was my reasoning.
Comment: @Mate, Your question was initially voted to be closed. My comment was for the folks voting to close it. Your query was okay.
Answer: There is not "burning", one might see a spark. It is a well known phenomenon. Do you see lightening in the sky? Air is an insulator, yet when very high voltage is present it becomes a conductor. It is called dielectric barrier discharge. In the same way, discharge between two electrodes can occur in pure water (almost an insulator). Adding NaCl to water makes it a good conductor but still it is mostly water, and if the electrodes are close enough, electrical breakdown can occur. Instead of ions carrying the current as it should happen in an aqueous conducting solution, the current becomes electronic even in the presence of water. Apparently, the local heating between the electrodes is so high, that a gaseous plasma is formed between the electrodes and plasma are electrically conducting.
As suggested in the comment, always exercise cause caution and all experiments should be done under proper supervision by a trained person/teacher.


Is the function $f(a_1 \dotsm a_n) = a_1(a_1a_2)(a_1a_2a_3)\ \dotsm\ (a_1 \dotsm a_n)$ regularity-preserving?

Question: A function $f: A^* \to A^*$ is regularity-preserving if, for each regular language $L$ of $A^*$, the language $f^{-1}(L)$ is regular. I think I have a proof, as a consequence of more general results, that the function defined by
$$
f(a_1 \dotsm a_n) = a_1(a_1a_2)(a_1a_2a_3)\ \dotsm\ (a_1 \dotsm a_n)
$$
is regularity-preserving. If this result is correct, could someone provide an elementary proof?
Answer: Here is a proposition for an elementary proof:
Let $\mathcal A=(A,Q,q_0,F,\delta)$ be a DFA for $L$, we want to build a DFA  $\mathcal A'=(A,Q',q_0',F',\delta')$ for $f^{-1}(L)$. Intuitively, when reading a word $u$, $\mathcal A'$ will remember the state reached in $\mathcal A$ by $f(u)$, together with the action of $u$ on all states of $\mathcal A$. More formally, we take:

$Q'=Q\times Q^Q$
$q_0'=(q_0,\mathit{id})$
$F'=F\times Q^Q$
$\delta_a'(p,g)=(\delta_a(g(p)),\delta_a\circ g)$

Where $\delta_a:Q\to Q$ is the transition function associated with a letter $a$.
This ensures that after reading a word $u$, the first component of the state of $\mathcal A'$ gives the state reached by $\mathcal A$ on $f(u)$.
Comment: @Hermann: $g$ is the second component of the current state: from any state $(p,g)$, reading letter $a$, we go to the state $(\delta_a(g(p)),\delta_a\circ g)$.
Comment: @Denis how is the function g defined?
Comment: I'd add that there is a simple and systematic way to show that a copyful streaming string transducer Σ* → Γ* is regularity-preserving, which takes a monoid morphism with codomain $M$ recognizing a language over Γ and yields a DFA with states $M^k$ recognizing a language over Σ ($k$ is the number of registers). The function considered here can be computed by a copyful SST with 2 registers, so if we compose this systematic construction with taking the transition monoid of a DFA, we get the set of states $(Q^Q)^2$ which is very close to Denis's solution!


How good is the LP relaxation?

Question: Consider the optimization problem
\begin{align}
\max_{x\in\mathbb{R}^n}~c^Tx~, \text{ s.t. } Ax=b,~x_i\in\{0,1\}~\forall i
\end{align}where $c,b\in\mathbb{R}_{+}^n$ and $A\in\mathbb{R}_{+}^{n\times n}$. Thus $x$ is a boolean vector (entries can be $0$ or $1$). It is not hard to prove that this is a NP-hard problem. A typical approach to this problem is to relax the only non-linear constraint $x\in\{0,1\}$ and make it continuous so that $0\leq x_i \leq 1$. Is there any study on how good this approximation is?
Comment: These types of problems are sometimes known as 'psuedo-boolean' optimization problems in that the function of interest is not boolean but the input is.
Comment: I guess the question is aimed at cases where [total dual integrality](https://en.wikipedia.org/wiki/Total_dual_integrality) and the likes do not apply, so the LP-relaxation solution is supposed to be different from the integer one, right?
Answer: Yes. In chapter two, section three and four of Nemhauser and Wolsey's Integer and Combinatorial Optimization there are conditions detailed for various relaxations of the first problem to have solutions which are within $\epsilon$ of the original problem's solution.
For the problem you address specifically, Theorem 2.6 (on pg 17 in linked pdf) in Li and Sun's Nonlinear Integer Programming (although somewhat weak) gives the type of result it seems you are interested in (stated below). This result initially appeared in W. Cook, A. M. H. Gerards, A. Schrijver, and É. Tardos' paper Sensitivity theorems in integer
linear programming published in 1986.
Consider problems,
$$\hspace{15 mm} \min c^{T}x \\ (P)\hspace{15 mm} s.t.\ Ax\leq b \\ \hspace{15 mm} x\in \mathbb{Z}^{n}$$
and
$$\hspace{15 mm} \min c^{T}x \\ (P')\hspace{15 mm} s.t.\ Ax\leq b \\ \hspace{15 mm} x\in \mathbb{R}^{n}$$
where $A$ is an integer matrix, and $c$ and $b$ are real. Let $\Delta(A)$ be the maximum among the absolute values of all subdeterminants of $A$.
Theorem: Assume that the optimal solutions to ($P$) and ($P'$) both exist. Then for each optimal solution $\overline{x}$ to ($P'$), there exists an optimal solution $z^{*}$ to ($P$) such that $$ \|\overline{x}-z^{*}\|_\infty \leq n \Delta(A).$$
Edit: The condition that $A$ is integer valued above should be noted. In the case $A$ is given as real valued then the problem can be scaled and rounded, but this will lead to much worse bounds.

How good is the LP relaxation?


Time synchronization on cisco switches

Question: I have LAN that must not be on Internet. I have a lot of switches. How to make core switch 4500 series to be some kind of NTP server, and all other switches to adjust their time with this core? Goal would be to set manual time only on core, and all other switches to adjust time with the core.
Does anyone know syntax for core and access switches?
Comment: Did any answer help you? If so, you should accept the answer so that the question doesn't keep popping up forever, looking for an answer. Alternatively, you can provide your own answer and accept it.
Answer: The following is an example of how to configure your devices to point to your 4500 for NTP.
There are a few things that you have to ensure you have on hand:

Know what time-zone the devices are operating in.
Know the local time (or whatever time your equipment is set to according to policy).
A refreshing beverage (in a non-spillable container of course.)

Configs:

4500# config t
  4500(config)#ntp master
  4500(config)#ntp authenticate
  4500(config)#ntp authentication-keys 1 md5 password
  4500(config)#int lo0
  4500(config-int)#ip address 10.0.0.1 255.255.255.255
  4500(config-int)#no shut
  4500(config-int)#description Loopback_for_NTP
  4500(config-int)#end
  4500#clock set hh:mm:ss day name of month year
  4500#clock timezone number of hours you are offset from UTC
  4500# copy run start
Client#clock set hh:mm:ss day name of month year
  Client#clock timezone number of hours you are offset from UTC
  Client#config t
  Client(config)#ntp authenticate
  Client(config)#ntp authentication-key 1 md5 password
  Client(config)#ntp server 10.0.0.1 key 1
  Client(config)#end
  Client#copy run start

If I missed anything or someone sees and issue with my configuration, please let me know.
Comment: Q: why did you set the clock on the client, too? It isn't enough just to set the ntp server IP? Last one: Is clock timezone mandatory? The ntp is local, so doesn't mind about timezone.
Comment: 1)  some NTP clients complain when the drift between clocks is too high.  it often doesn't matter but there's always that one time so it doesn't hurt to build the habit.  2)  NTP never minds about the timezone. the setting of the timezone only changes how the time is displayed in the logs, etc.  It's a convenience feature since internally it's stored in universal coordinated time (or epochal depending on device ).   If you prefer viewing UTC you can leave that part out of the config.
Comment: Thanks Stuart.  You covered everything I was going to.  Technically you don't need to set the clock on the clients, but NTP has a tendency to get wonky if the client drifts too far from the master.  It doesn't happen often, but it can be annoying to troubleshoot (especially in a virtualized environment.)

Time synchronization on cisco switches


How to calculate median via interpolation

Question: I am reading a text on data mining. I came across this formula, but I do not understand how to apply it. There aren't any examples following the forumla and my research online has produced very few results. Can someone explain how to apply this formula?
Answer: Let's suppose we have three groups
0-20000       20
20000-39999   60
40000-        20

where the second column is frequency, and also percent. The median must be within the second group as $20\%$ are less and $20\%$ are more.
Then the recipe gives
$20000 + [(50 - 20) / 60] \times 20000$
which is $20000 + 0.5 \times 20000 = 30000.$
which is halfway through the median interval, as it should be: I deliberately made the example really simple (and symmetric). If we had instead
0-20000       25
20000-39999   60
40000-        15

so that the recipe yields
$20000 + [(50 - 25) / 60] \times 20000 \approx 31667$
it should be clear that the median should be nearer the lower end of its interval than the top, because the cumulative probability at the bottom ($25\%$) is nearer $50\%$ than is the cumulative probability at the top ($85\%$).
It may help to draw cumulative bar charts with simple numerical examples and consider interpolation geometrically.
Let's spell it out: the assumption here is that within each bin, the distribution is uniform. If there are lots of bins, that assumption may work well. Otherwise it is not necessarily the only alternative. For example if all upper bin limits are positive, and the distribution is right or positively skewed, then interpolation on the logarithms of upper bin limits may work better.
Answer: You have binned data, $k$-th bin contains $freq_k$ points, and has some width $width_k = U_k - L_k$ where $L_k$ is the lower bound for the interval, and $U_k$ is the upper bound (e.g. "\$10-20,000").

Median is located at the $N/2$ point (median is a middle value of a sorted list of values).
$\sum(freq)$ is the number of points in the bins before the middle bin. In such a case, median would be located at $\sum(freq) + \delta = N/2$ position of a sorted list of points, so $\delta = N/2 - \sum(freq)$ is how many points we are missing till hitting the median.
$\phi = \delta \big/ freq_{median}$ translates the number of points $\delta$ into the fraction $\phi$ of the median interval. It's the number of points before median divided by the number of points in the interval.
$L_1 + \phi \,\times\, width$ says that median is located in the $\phi \,\times width$ location of the interval, and you need to move that many units from the lower bound $L_1$ to get there. Here we're moving from counts, to the actual units (e.g. dollars, as in the example).

Try drawing this.


Keyframe being ignored?

Question: I'm probably missing something obvious, but it seems whenever I try to move the root bone of my character after frame 35, and add a keyframe, it's being ignored. I'll scrub along the timeline to the new keyframe, but the character doesn't move to the new position that I set.
Answer: You have an Action strip in the NLA Editor which is overriding/controlling the animation of the object.
Here I have added a keyframe on frame 54, but because the end of the Action Strip is at 35 (green timeline marker), the keyframe is ignored:

To solve this you can extend the End Frame property of the Action Strip in the Properties shelf on the right of the NLA Editor (N) to be as long as your animation:

Or, if you don't need to use the NLA Editor, you can delete the strip by selecting the Action Strip called 'Jump' (it will be yellow/orange when selected, as shown above), press Space, type "Delete Tracks" and press Enter.
Comment: Surely all that will do is extend/draw my current animation out and slow it down...? I would have thought the amount of the Action Strip's frames would keep increasing as I add more keyframes...? I don't recall setting it to 35 at the start...
Comment: I've just increased the end frame to 60, but any frames I add after 35 don't register either.
Comment: It doesn't slow the animation down it sets the range of where to look for keyframes within the original action. The exact steps I take with your file is to change to NLA, select 'Jump' strip, extend range, add new keyframe and it works.
Comment: Note that the panel in the screenshot is 'Active Clip' not 'Active Strip'. There are two panels that look quite similar and both have frame range options.
Comment: Ahaa... That's why I couldn't get it to work; I was adjusting the Active Strip. That worked. Thanks. :)

Keyframe being ignored?


OS X - Signing installer/application

Question: I would like to sign my OS X installer using company certificate. I have .cer and .p12 files. I wonder if there is some way to do that without creating keychain. E.g. in 'productsign' tool flag --cert looks promising, but I can't find too much info about how to use it.
Answer: Apple's signing tools require a keychain containing your organisation's signing identity.
The cert flag on productsign is used to embed an intermediate certificate. It is not used to specify the signing certificate.
It is possible to create a keychain containing your organisation's signing identity. This can then be used to sign your installer using the keychain flag. The separate keychain file can be managed with source code control or other file management tools; it remains separate from the user's login keychain.
Comment: I was expecting this, but still wanted to make sure. So if pkg creation is last step of my build procedure, every developer will have to deploy certificate on his machine, right?
Comment: Yes, if you want the developer to be able to sign, they must have the keychain on their Mac. You can sign the package as a separate pre-launch step. You could create an internal certificate for testing, see http://security.stackexchange.com/questions/17909

OS X - Signing installer/application


Enrichment of mutations in particular region of the gene

Question: I have a gene say "X" of 3000 base pairs. 300 of those 3000 bp belong to ring domain. Rest 2700 do not belong to ring domain. In a particular tumor, the ring region has 4 alterations and the rest of the region has 4 alterations too. Clearly the frequency in ring region is higher, but is there a statistical test that will give me a p value that tells the probability of having a mutation in ring region is higher or not?
Comment: Does yours **ring domain** mean Really Interesting New Gene finger domain or it refer to some kind of loop? Maybe you should strip the question of domain specific knowledge and edit it? Moreover, you should clearly state what model of mutation do you assume, something like Junkes & Cantor's, Kimura's or something else?
Comment: In Junkes & Cantor's each nucleotide could alternate to any other with the same probability. In Kimura's model the transitions (purine to purine or pyrimidine to pyrimidine) are more likeli than transversions (between purines and pyrimidines). Or maybe you should even use something more general. Have a look on those models and specify the question further https://en.wikipedia.org/wiki/Models_of_DNA_evolution
Comment: This question about RING is because in much more elaborated model we could make use of the very specific structure of RING finger domain: $Cys_3 His Cys_4$. Because we know their codons we probably could make some assuptions and put some bonds on nucleotide percentage content.
Comment: When i say ring domain i mean Really Interesting New Gene. I want to know if the occurrence of mutation in this region of the gene is significantly higher than the mutations occurring in the non RING part of the gene.
Answer: As I wrote in comments, I don't know how complicated your question is. Maybe I'm exaggerating a bit with those models or you don't know anything else about the situation.
If that is question should be very simple (homework or something like that) you could have a look on simplest Welch's T test.
With this test you could check wheter two non-overlapping populations have the same means.
Let's say, you have two populations $\mathfrak{F}$ (RING - foreground) and $\mathfrak{B}$ (the rest - background) represented by two arrays of lengths $L_F = 300$ and $L_B = 2700$, respectively. In the picture below, with blue balls are marked positions of bases which were altered.

For array $\mathfrak{F}$ we have independent binary random variables $F_1, \dots, F_{L_F}$, where $F_i = 1$ denotes at this position $i$ an alternation took place. I assume that any position in $\mathfrak{F}$ the probablity of alternation is the same(, but unknown) $p_f$ and each variable $F_i$ denotes single Bernoulli trial, so $F_i \sim Bernoulli(p_f)$.
For array $\mathfrak{B}$ we have the same situation, but corresponding variables $B_1, \dots, B_{L_B}$ are distributed with maybe different probablity $p_b$, so $B_i \sim Bernoulli(p_b)$.
According to the Central Limit Theorem (we have more than 30 random variables with each array, so CLT may be used) the mean of $F_i$s and mean of $B_i$s have Normal distribution:
$$\text{(mean of $F_{i}$)} ~~~~~~ \mu_F =\frac{\sum\limits_{i} F_i}{L_F} \sim Normal(p_f, \frac{p_f \cdot (1 - p_f)}{L_F} )$$
$$\text{(mean of $B_{i}$)} ~~~~~~ \mu_B = \frac{\sum\limits_{i} B_i}{L_B} \sim
Normal(p_b, \frac{p_b \cdot (1 - p_b)}{L_B})$$
Because you don't know anything about variations, thus use Welch's T test https://en.wikipedia.org/wiki/Welch's_t_test (rather than Student's T test).
In this test you may compare the corresponding means with hypotheses:
$$H_0 : \mu_F = \mu_B ~~ \text{against} ~~ H_A: \mu_F > \mu_B$$
In R you use method t.test{stats}:
t.test(arr_f, arr_b, alternative = "greater", paired = FALSE, var.equal = FALSE)
arr_f and arr_b are simply an 0-1 arrays where 1 points to alternated bases and 0 elsewhere.
The two trailing parameters are by default false, but I put them to make you aware of them. The last var.equal = FALSE indicates the Welch's T test instead of Student's T test with TRUE.
Comment: That should explain how Welch's T test could work in your case. Remember only the assumption that the probabilities of alternation $p_f$ and $p_b$ are the same all over arrays. This simplest approach above would work, but maybe in your model you should give different probabilities for transversions and transitions.


What are the differences between 'incident', 'issue' and 'affair'?

Question: What are the difference between incident, issue, and affair? How should one use them?
Comment: These words are, to my mind, completely unrelated. What's the difference between *taxi*, *green*, and *kitchen*?
Answer: An incident is a single distinct event - one occurrence of something that can happen more than once. It is often unpleasant and/or unexpected.
Issue has lots of meanings. Given the other words you're asking about, the meanings you might be thinking of are (1) a problem, something that needs to be discussed/fixed; or (2) a topic of interest.
The first meaning that springs to mind for affair is the extra-marital kind, but it can also mean a social event (of the dress-up kind), or a plain old (read: not sex related) scandal.
(I've linked each word to the definition with the most examples of usage that I could find.)

After that incident with the neighbor's dog,
  he avoided chihuahuas like the plague.

vs.

After that affair with the neighbor's dog, he
  avoided chihuahuas like the plague.

The incident probably took less time than the affair - for the former, I'd imagine the dog scared the man, while the latter might have involved an actual bite and subsequent lawyers and suits and animosity.

After that issue with the neighbor's dog, he
  avoided chihuahuas like the plague.

Here the implication is that there was a problem which had (or should have had) a solution. I'd imagine the dog peed somewhere inappropriate, or something similar.
Comment: An affair could have issue: that is, give rise to offspring. This is, admittedly, a somewhat archaic usage.


How does one align a laser using two adjustable mirrors?

Question: Suppose we would like to get a laser beam to pass through a particular point in space in a particular direction.
At our disposal we have a laser, two adjustable mirrors (can rotate up/down and left/right) and a card which we can hold in the laser beam to see where it is.
What is the procedure we should follow for adjusting the positions and orientations of the mirrors to achieve the goal?
How, mathematically, can we see that this procedure converges (i.e. gets the laser aligned within a reasonable number of steps)?
Comment: Is this the thing you are looking for? -  http://laser.physics.sunysb.edu/~simone/mini-project/
Comment: @DanielSank Roughly speaking, if you put in the basic equations and maybe a picture or two (copying from source, with attribution, is fine), and then say "for more details, go to foobar.com" you're good to go.
Comment: @sa101 for the benefit of future readers, you should post that link in an answer along with some explanatory text :-)
Comment: @sa101: Yes, that's it exactly.
Comment: @CarlWitthoft: I was wondering about that. What is the standard procedure if a question can be answered really well with an external resource? While it would be odd to re-type the resource here, it would also prevent the answer from being subjected to link rot.
Answer: I would start by taking a pen and a piece of paper and drawing the relative positions of the source point and the target. Then draw the direction of the laser beam as a long and a straight line starting at the source point, lets call this Line1. Try to draw a line parallel to the laser beam that goes through the target point (Line2). Now, draw a new line (Line3) that is perpendicular to both Line1 and Line2. This Line3 should intersect with Line1 and Line2. You will place the mirrors on these intersections points of Line1 and Line3 or Line2 and Line3 respectively with approximately 45 degrees to the incident and reflected beams. Planning part is over.
Now for the actual aligning part: generally, the laser and the mirrors are placed on an optical bench, that has equally spaced holes on it. You can use those holes to see if you beam is going straight. To do that, use the card you have. Hold the card so that you can see the beam, try to look at the dot on the card straight from the top and see if it coincides with our imaginary line created by the holes.
Place the mirrors approximately at the positions you planned with ~45 degrees with respect to the incident beam (actually as long as both of the incident angles of the mirrors are a total of 90 degrees it is fine). I would set the height of the mirrors so that the centre of the mirror is approximately at the same height as the laser aperture and the centre of the second mirror with the target point. We want to stay away from the edges of the mirrors. This ensures that in the end, we will have a beam that goes straight into the target without any tilts.
Now, with the card, make sure that the beam is centred on the first mirror, if not, change the position of the mirror slightly to make it so by moving the post holder that holds the post on which the mirror1 resides. After it is centred on mirror1 and you fixed the post holder of mirror1, you can change the lateral angle of the mirror1 so that the beam is incident on the same vertical line as the center of mirror2 by rotating the post of mirror1 while its post holder stays fixed. We did not use the knobs yet, mind you. Now try to find the knob that will move the beam to ~center of mirror2 in the vertical direction. After that is done too, fix the post holder of mirror 2.
Now turn the post of the mirror2 in lateral direction inside the fixed post holder so that the beam is on the same vertical line as the target point. Then turn the knob so that the beam moves in the vertical line and is on top of the target. You have aligned the laser to the target.
Now lets say you went out for a quick bite and when you return you see that the beam is not aligned anymore (it happens). Now do not move the post holders of mirror 1 and mirror 2 that you fixed before. You can simply use the knobs as the misalignment cannot be too bad afterall. mirror1 is far away from the target with respect to mirror2, so rotating the knobs on mirror1 will move the beam much farther than the knobs of mirror2.
This may seem like a very long procedure, but it really is not. When you practice it 3 or 4 times, you can do this under two minutes.
Also note that this is the procedure for aligning the laser to a single target point. The procedure to align the laser to the optical rail is not the same although not entirely different.
Answer: Set two points, one as far away as you can get, and one close to the 2nd mirror.
Use mirror 1 to align for the close point and mirror 2 to align for the far point. Keep iterating over this (M1 -> M2 -> M1 -> M2) until the beam goes through both points at the same time.


Unfortunately, Software Update has stopped OTA (LG G2 Rooted)

Question: Whenever I click it, I get the "Unfortunately, Software Update has stopped" message and the app closes. Picture is not of my phone, I found it from another post that was not answered.

My phone was trying to update automatically but would fail during the process. I read a forum saying to restore some hotspot files that I had changed to get the free hotspot. I must have done something wrong in trying to find the stock hotspot files and now my phone wont even start to try and update.
Any help would be great!
Answer: Just open your setting>apps>software update>clear data. You are done...!!!


ext2 filesystem

Question: I have a question about ext2 of file system. I need to know really well about this. And I think I sort of understand everything on it. But there is a thing bothering me. As you can see from the first picture, this file system makes the volume be divided to some "block group". Each of which has a Inode Table Section mutually. what I want to know is if it is same between the Inode Table of Block Group 0 and that of Block Group 1(2, 3 .. whatever except 0).
Are they same or not? If they are same, how to find which Inode_table corresponds to a i_node. If they are not, in this case it kind of seems like there are over 1 number of same i_node. If you know the answer exactly, let me know the basis of your thoughts like websites or books that you can prove you're right.

Answer: If you are asking if the inode table is always at the same offset relative to the beginning of a block group, this would mean everything before it must be of fixed size. The block and inode bitmaps are always one block. The block group descriptor table is not fixed. This is what the documentation says:

Depending on how many block groups are defined, this table can require
  multiple blocks of storage. Always refer to the superblock in case of
  doubt.

Assuming you want to find the inode table for a given inode you need to know which blockgroup an inode belongs to. If you know the blockgroup number, the block size (s_log_block_size) and the amount of blocks per blockgroup (s_blocks_per_group), you can find the start of a blockgroup, where the block group descriptor table sits. It contains the block id of the first block of the inode table of this block group (bg_inode_table).
Ext filesystem internal layout documentation: http://www.nongnu.org/ext2-doc/ext2.html
Comment: thank you for your answer. Actually I know how to find the inode-table of a block group when I have inode number from this formula,  block group = (inode – 1) / INODES_PER_GROUP . For me, it seems like each inode table of each block group is in charge of some range of number of inode number. For example , inode table of first block group is in charge of 1~ 100 and that of second block group is in charge of 101~200  because that formula above calculates which block group a inode number belongs to by the operator '/' .
Answer: (after posting, I then realize I'm a couple years late, anyways I'll leave this answer here)
If I understand your question right, there's confusion over what's in the group descriptor tables vs what the bitmaps refer too.
Each block group contains a superblock, a set of group descriptors, block and inode bitmaps and an inode table. The set of group descriptors is for all the block groups (the super block and group descriptors are backup copies), but the bitmaps and inode table are just for that block group.
So, for example, if you're interested in the 4th block group, you'd read in the 4th entry from a group descriptor table (either the main one towards the beginning of the disk or a backup copy), and from it, you can read the block number for where the block and inode bitmaps are located.
One note: What I wrote above isn't quite correct as the sparse option is normally set by default and not all block groups have a super block (to save space). It's easy enough to read in a block as of it were a superblock, test the superblock's s_magic field to see if it's equal to EXT2_SUPER_MAGIC, it if's not correct, then that block group starts with the bitmaps instead.
The link Hoov posted is a good one and here's another helpful link too http://cs.smith.edu/~nhowe/Teaching/csc262/oldlabs/ext2.html
There's a couple confusing aspects to it, but used in conjunction with Hoov's link should get you up and running. https://wiki.osdev.org/Ext2 is also good.

ext2 filesystem


Select() system call in threads?

Question: I am reading data from multiple serial ports. At present I am using a custom signal handler (by setting sa_handler) to compare and wake threads based on file descriptor information. I was searching for a way out to have individual threads with unique signal handlers, in this regard I found that select system call is to be used.
Now I have following questions:

If I am using a thread (Qt) then where do I put the select system call to monitor the serial port?
Is the select system call thread safe?
Is it CPU intensive because there are many things happening in my app including GUI update?

Please do not mind, if you find these questions ridiculous. I have never used such a mechanism for serial communication.
Answer: The POSIX specification (select) is the place to look for the select definition. I personally recommend poll - it has a better interface and can handle any number of descriptors, rather than a system-defined limit.
If I understand correctly you're waking threads based on the state of certain descriptors. A better way would be to have each thread have its own descriptor and call select itself. You see, select does not modify the system state, and as long as you use thread-local variables it'll be safe. However, you will definitely want to ensure you do not close a descriptor that a thread depends on.
Using select/poll with a timeout leaves the "waiting" up to the kernel side, which means the thread is usually put to sleep. While the thread is sleeping it is not using any CPU time. A while/for loop on a select call without a timeout on the other hand will give you a higher CPU usage as you're constantly spinning in the loop.
Hope this helps.
EDIT: Also, select/poll can have unpredictable results when working with the same descriptor in multiple threads. The simple reason for this is that the first thread might be woken up because the descriptor is ready for reading, but the second thread has to wait for the next "available for reading" wakeup.
As long as you're not selecting on the same descriptor in multiple threads you should not have a problem.
Comment: Gud info!! One question.. How does the thread know that it needs to wake up if the socket fd is ready to do read/write operation. Does kernel give some interupt to the thread?
Comment: @SumitTrehan The kernel wakes up the thread as in it puts the thread into runnable state i.e. the thread will run as soon as it gets CPU time.
Answer: It is a system call -- it should be thread safe, I think.
I did not do this before, but I would be rather surprised, if it where not. How CPU intensive select() is, depends in my opinion largely on the number of file handles you are waiting for. select() is mostly used, to wait for a number (>1) of file handles to become ready.
It should also be mentioned that select() should not be used to poll the file handles -- for performance reason. Normal usage is: You have your work done and some time can elapse till the next thing is going on. Now you suspend your process with select and let another process run. select() normally does suspend the active process. How this works together with threads, I am not sure! I would think, that the whole process (and all threads) are suspended. But this might be documented. It also could depend (on Linux) whether you use system-threads or User-Threads. The kernel will not know User-Threads and hence suspend the whole process.
Comment: This is really not a good answer. Lots of guess work... What is a "User-Thread" anyway?!

Select() system call in threads?


NTP client authenticate server using Autokey protocol without server key

Question: I am trying to create a NTP client-server setup using Autokey authentication for server validations. I have followed the instruction on link http://support.ntp.org/bin/view/Support/ConfiguringAutokey to setup client and server on NTP 4.2.6 . The setup I had created is working in some unexpected manner.
I had created server and client certificates using ntp-keygen as mentioned in the above link. I have edited the client's ntp.conf to use autokey to authenticate server. As mentioned in the above link, I have to copy the server key to client for authentication to work, but while testing I have found that client is able to verify the server even if I do not copy the server certificate on the client. The result for "ntpq -c as" show auth field "ok" for the server and ntpq -c "rv 0 certs" shows the server certificate bindings.
Can someone explain me why NTP is able to verify server without copying the server certificate on client ?
If this is not the expected behavior, what are the changes I have to make in the configuration to get it working correctly.
Answer: See
CVE-2014-9295
Just don't do it


Basics on anabelian geometry and Grothendieck's section conjecture

Question: Even I can find similar questions and some answers on that questions, most of them are not quite unsatisfactory to me. Maybe this is a very stupid question, but there is no other place that I can ask this. I want to undersatnd Grothendieck's section conjecture and its recent results and also I want to study anabelian geometry. I just finished to read Hartshorne's algebraic geometry book. Is there any good start point for those things which contains some basics? If my background is not enough, please let me konw a kind of 'road-map' for anabelian geometry and section conjecture.
Comment: seems very redundant with
http://mathoverflow.net/questions/108860/anabelian-geometry-study-materials?rq=1
to me.
Answer: if you just read the Hartshorne, your background is not enough for anabelian geometry. You need
A) To learn about etale morphismes: Hartshorne just mentions that notion in exercises.
B) to learn about the étale fundamental group Grothendieck,
before C) learning anabelian geometry proper.
Let me begin by B), because for this I think there is one best reference, which is the original one: SGA I. It is certainly a non-trivial read, but not nearly as difficult as it is often imagined by beginners. After all, it is the first SGA, made for an audience who consisted only of beginners. And it is a good initiation to the grothendieck's style of thought, of which you will need plenty if you are to learn anabelian geometry.
Before learning the étale fundamental groups, you have to learn étale morphisms, as I said in A). Here you have several choices. You can stick with SGA I,
whose first chapters contain everything you need on the subject. But those chapters may be a little terse for someone who just knows the Hartshorne. Alternatively, you can find a good introduction to étale morphisms in the texts about étale cohomology, such as Milne's or Freitag-Kiehl's. And of course, you can also read the relevant chapters in EGA, which will probably lead you to read other chapters first, but if you want to work in algebraic geometry, that's no wasted time.
For C), there is much to read and I am not an expert, but for an introduction you can begin with "The Grothendieck Conjecture on the Fundamental Groups of Algebraic Curves" by Hiroaki Nakamura, Akio Tamagawa, Shinichi Mochizuki.
Answer: For the section conjecture you might look at Jakob Stix's great book
Evidence for the section conjecture in the theory of arithmetic fundamental groups Habilitationsschrift, School of Mathematics and Computer Science at the Ruprecht-Karls-Universität Heidelberg, January 2011, x+190 pages, to appear as
Rational Points and Arithmetic of Fundamental Groups. Evidence for the Section Conjecture
Springer Lecture Notes in Mathematics 2054, xx+pp.249, Springer, 2013.
"The first exposition of foundational material on the arithmetic of fundamental groups with respect to the Section Conjecture of anabelian Geometry: from the history of the subject to the state of the art of the conjecture. Numerous approaches to the Section Conjecture are discussed with open questions to stimulate future research.
Assuming the basics, the more advanced chapters are self contained and can be read independently."


Does Mac OS X have a better installation story than Windows?

Question: I'm a Windows developer... I know nothing about Apple Mac OS X.
In Windows one uses Windows Installer to install packages.. For historical reasons, installation is not an easy thing in Windows.
I was wondering what is the OS X story? Just curious.
Answer: This is a really thoughtful blog on that topic from John Gruber (daringfireball.net)
http://daringfireball.net/2009/09/how_should_mac_apps_be_distributed
The story is weird -- many installers just give you a .app file that the user is expected to copy to their Applications directory.  It's simple, but do novice users understand? And there are actual installers as well.
Answer: The "proper" method for OSX application installation is drag and drop the application to the /Applications folder.  No installer, no "type your password", no changes to the system.
Answer: It's not too bad, most people use something called packagemaker which has a nice GUI but also has an XML configuration syntax.  The GUI is very nice to use and on my last project I used that initially to create a simple installer.  Then I figured out that I could automate the creation of the XML files and generate my installer automatically.  It's quite a nice solution.  Better than MSI/Nullsoft which I've used on windows.
Comment: Mind you, the linux deb format is still my favorite for simplicity and power!
Comment: PackageMaker is painfully buggy to create packages for anything other than just a straight file copy installation.
Answer: on the mac, to install, you normally just copy or delete a file which is actually a directory which contains the whole package. some also come with installers to install daemons. the problem is that there is no real list of installed apps so that you can uninstall the daemons again.
Real-life example: KB article for the uninstall of the Kaspersky Antivirus on the Mac. So what they are saying is that you need the install medium to uninstall. Which you might have just downloaded and then deleted. I would prefer if the OS would keep the uninstall somewhere.
Answer: Most Apple installs (I have worked with) are similar to DOS/.Net installs where you can just copy the program into any directory and run it.  But this comes at the price of not sharing libraries and litters the machine with different versions of toolkits.
But like Windows installs when you copy files all over the place to update different libraries you can still installs files that you will never see again.  (Linux/Unix is the same.)  The more you reuse code the more complex the install and maintenance story.
Answer: I'm no developer, but I think you can also use similar packages similar to Unix (FreeBSD,of which OS X is partially based on, along with Darwin), and Linux.


How to remove pigments from white clothes that have been accidentally laundered with strong colors clothes?

Question: Accidentally I've laundered white socks with a red t-shirt. Now I have pink socks. So my question is: How to remove pigments from white clothes that have been accidentally laundered with strong colors clothes?
Comment: This is not an answer to your question, but a tip. If you bought new coloured clothes, wash them once on their own, just add one piece of white fabric ( Old T-Shirt for example, make slice out of it so you have multible pieces of fabric for further tests). This has two effects. 1. Removes possible harmful chemicals like bleach, 2. Shows you how much of colour the garment releases. Sure this lowers with time, but it's an nice indicator.
Answer: If the clothes can tolerate chlorine bleach, that should be effective, since they were white to start.
Scrubbing small spots with dish-washing detergent and toothbrush works if the color is only a small area.
Answer: The solution to this is to put everything white back through the wash immediately, before the items are dry, preferably on the hottest wash they can take. Having made my partner's cricket whites pale pink in a similar situation, running them back through straight away cleared it, but I have since adopted the use of those Colour Catcher things... I think they also make a colour run corrective for these situations. As its only socks, you might not want to wash those on their own... I'd try soaking in Vanish Oxyaction for 6 hours.
Comment: Yes, its brilliant stuff - even gets red wine stains off a linen tablecloth!
Comment: That Vanish stuff (I use another make) is magic. I can even get the collar of my son's band uniform white again. There are different ways to use it; add to the washing powder, soak in a bucket before washing, or mix to a paste and leave for a while before washing. Read the instructions.


using custom setting inside apex

Question: I have a custom setting object holiday__c and added one field into it i.e, date__c. I have entered all the values into it. Now my requirement is how to match the incoming date with the holiday dates field date__c. I've to call this field into apex and match with the incoming dates.
Answer: Custom settings methods are all instance methods, that is, they are called by and operate on a particular instance of a custom setting. There are two types of custom settings: hierarchy and list. From your description it seems like it is List type custom setting, in that case you can directly fetch value instead of looping all records described in Ratan's answer.
if(holiday__c.getvalues('NAME VALUE')!=null)
   system.debug(holiday__c.getvalues('NAME VALUE').date__c);
else
  system.debug('Not Found');

You can read more about custom settings in Apex

using custom setting inside apex


How to measure daily number of metrics which is written to the single MongoDB instance?

Question: Please suggest a commands to measure daily number of metrics which is written to the single MongoDB instance?
Answer: "Daily number of metrics" is very broad, but the db.serverStatus() command in the mongo shell (or the serverStatus command if you want to invoke this via a driver) is a great starting point for hundreds of metrics about your deployment.
The serverStatus output will vary depending on your version of MongoDB, O/S, and deployment configuration. Common metrics include opcounters (database operations by type since the mongod instance started), connections, and memory usage.
For more general informational and diagnostic commands, the list of Database Commands used by the Cloud Manager Monitoring Agent is also a useful reference.


rebuild itunes library after crash

Question: I had a hard drive crash and lost the system files, but recovered all my iTunes folders and files e.g. Books, Downloads, iTunes U, Mobile Applications, etc.  The iTunes library file "iTunes Library.itl" went down with the crash.  What's the best way to rebuild my iTunes library now that I have a new HDD?
Answer: You have two options:

restore the library from a backup copy (previous libraries folder in the iTunes folder, Time Machine, other backups)
re-import the songs by dragging the media into the library section and allowing it to add the tracks back to the library - optionally you can import any playlists or library xml documents that saved the playlists, ratings and data relating to the tracks and not embedded into the media files on the drive

If you have enabled iTunes Match, you will also be safe from most data loss since all playlists are stored in the cloud unless it contains exclusively tracks that were not matched to the cloud like podcasts and other oddities like voice memos and low bit-rate recordings.
Answer: If you still have the 'iTunes library.xml' file, start iTunes and get it to generate a new .itl library file.  Once that's there, close iTunes, and open the .itl file with your preferred text editor.  You'll just see a bunch of unreadable gibberish that makes up the library file iTunes reads.  Delete everything in the document and save it.
Now when you restart iTunes, it will say it's trying to import your library.  When you tell  it to stop trying (because it won't get anywhere), it will say it's corrupted and rebuild a new one from the information in the .xml file.

rebuild itunes library after crash


Teacher Assistant verbal job offer

Question: I received a verbal job offer today and accepted, cancelling 2 interviews. There is no letter of the job offer. I start tomorrow. Is a verbal job offer acceptable or should there be a letter?
Comment: If you found out _today_ and start _tomorrow_, they probably didn't have time for a letter. You should simply show up tomorrow as discussed, and it's likely everything will be sorted then.
Answer: As has been indicated in comments, there's simply not enough time between acceptance and the job starting for you to receive a formal job offer in the mail and return it before you start.
Simply follow the instructions regarding starting work and go through the paperwork on arrival.
If you don't like what you hear when you're there, then head right out of the door again (in a polite fashion, of course).
Answer: I am not a lawyer, but verbal offer =/= signed contract. Unless you have one signed by both yourself and your employer, it can be rescinded.
At the end of the day, if you trust your employer, then it isn't an issue.

Teacher Assistant verbal job offer


GPGPU/FPGA programming for Combinatorial Analysis

Question: Recently, I have taken an interest in performing combinatorial analysis for the game of 21 (blackjack) and attempted to use my AMD APU to try and thread the program via the 4 cores on the chip. Generating the proper strategy and expectations has proven to be a success, as well as taking very few seconds (around 12) to compute the optimal strategy for any given rule(s) and deck composition. However, when it comes to computing other deck compositions, it would take 12.63 years to compute all deck states...for a single deck. So, another approach would be to simulate a select limit of random deck subsets via a Monte-Carlo method. This will work! However, the 12 seconds per analysis is a huge bottleneck! Randomly selecting just 10E6 subsets would take around 139 days. Not feasible with my current CPU, even with threading.
A primer on how I am analysing the strategy chart(s):
1.) I first start by computing what the overall expectation for standing is by taking a set of n_cards for the player and enumerating all possible dealer hand sets. I compare the outcome of each specific dealer total against the current hand total of the player hand.
2.) I then compute the hitting expectation by taking a player hand set {23} and finding matching hand sets for x:2->A, so that we can compute the weighed expectation of hitting to {232}, {233}, {234}, ...,{23A}. We do this by computing all hard 21's first, then hard 20's...down to all hard 12's; then do the same by computing hitting all soft 21's to soft 13's; then compute all hard 11's to hard 5; and finally, we compute hitting all pair cards ({22}, {33}, ..., {TT}, {AA}.)
3.) Doubling is the same as hitting, except we only draw one card and stand for any 2_card player hand. We return the expectation of drawing to a specific 3_card hand and multiply the expectation by 2 times the probability of that drawn card.
4.) For splitting, we will take steps 1.) to 3.), we will repeat 1->3 up to 11 times. Why? We are computing the expectation of splitting to a new hand by removing the rank for which we are splitting. (For example: We want to split {22}. We will compute standing, hitting, doubling for a given deck subset, minus one of the ranks we are splitting. If we originally split {22} for a deck subset of {4 4 4 4 4 4 4 4 16 4: 2-A} or {3 1 4 3 4 4 3 1 14 3: 2-A}, our new subsets would be {3 4 4 4 4 4 4 4 16 4: 2-A} or {2 1 4 3 4 4 3 1 14 3: 2-A}.)
5.) After all of this, we should get back out optimal strategy with respect to the computed expectation(s) for each possible decision for each player hand.
Now, I have been looking into seeing if there is a quicker way of analysing the strategy using either GPGPU or FPGA/ASIC. I first looked at GPU programming as a possible route, however, I am not sure if it is feasible as there are 3072 unique player hand states, meaning there will be 3072 unique data structures to compute for standing, hitting, doubling, and splitting.
With all this said, I was hoping there was a way to perform some form of simultaneous processing, where the state of each expectation changes dependent on the change in the rules and/or the deck state. That is, rather than recompute each expectation for every change in rules/deck_state, there would be some dependence on the output for each data point. For example: We have three data points named A, B, and C. We also have state data {1 2 3}. For each data point, there is a state equation that we possess:
A = data[0]
B = A + data[1]
C = B +data[2]
Under serial processing, we would evaluate A first for 1, B for 2 plus A, and C for 3 plus B. If we change data to be {2 2 3}, then A would be 2, B would be 4, and C would be 7. Under serial processing, this would take several cycles per data point, for each data point. Is there a method under FPGA where the change in state is instantaneous? That is if we change any point of data, that A, B, and C will change after data changes, simultaneously?
If not, what benefits does FPGA/GPGPU processing offer to a programmer who wants to accurately and quickly compute large volumes of floating point data in a near instant? Basically, is there a way to rapidly compute the optimal strategy of a blackjack game that is faster than multi-threaded CPU processing that is not 12 seconds long?
Answer: I am writing a general answer about porting a program running on a CPU to a GPU or FPGA.
Both GPU programs (using say CUDA) and CPU programs are written in high level languages like C, C++. Therefore it is much easier to port a CPU program to its equivalent on a GPGPU. The algorithm that you have presented seems suitable for porting to GPU. It is compute intensive, repetitive. Some effort, and you will be able to achieve good amount of speedup.
Framework like OpenCL, OneAPI (Intel) primary objective is to automate the process of porting a CPU program to accelerators like  GPU or FPGA. But they still have not achieved wide acceptance. Automation is still not good enough across problem domains.  In my personal experience it is much easier to write a GPU program from scratch. For somebody who can program in C it is not very difficult.
FPGA is a different game altogether. Like for the logic that you mention in your example using three data points, can be easily implemented in an FPGA using two Adders. The resultant circuit is a combinational circuit, hence using appropriate adder (like carry look-ahead) the computation can be performed within a nano-second on modern FPGA.
But that would require learning a HDL language like verilog or VHDL. It will require a lot of effort.
Alternative is to just wait for some of the framework like OneAPI or OpenCL to get refined enough that they are able to generate an equivalent FPGA HDL code from a high level language(like in C) program.
Personally, I believe, it is not going to be anytime soon.