post-stratification of ACS survey

Question: I have a survey methodology question. I am preparing a report that contains some demographic information. My supervisor instructed that I use the NCHS bridged-race population estimates when reporting the state population. However, he has also instructed that I use the ACS IPUMS to calculate rates on various indicators such as poverty and language isolation. Then, I am to apply that rate to the NCHS population estimate; the product of the ACS IPUMS rate and the NCHS population estimate is the "adjusted true estimate" according to my supervisor. Since then, I have found that what he is instructing me to do is called post-stratification. I am, however, curious as to whether this is sensible practice given the methodology used to calculate NCHS bridged-race population estimates (http://www.census.gov/popest/methodology/2013-natstcopr-meth.pdf). Is my supervisor's proposed post-stratification method correct or poor form of survey analysis methodology?
Answer: Post-stratifying ACS sounds very funny to me as a survey statistician. It's like "rectifying Google search". Generally, ACS sample sizes are at least an order of magnitude larger than sample of any other survey (more often, two or three orders of magnitude larger). So ACS should generally be used as the target population to calibrate / post-stratify to. However, if there is a standardized medical (quasi-)population that is only available through NCHS, designed to make trending or comparisons apple-to-apple, then I see the point of this exercise of calibrating towards NCHS.
Please check that you are not confused about terminology, see clarifications in http://www.surveypractice.org/index.php/SurveyPractice/article/view/315.
Also, I think that what you are effectively after are some sort of indirect synthetic ratio estimation, in terms of the traditional small area estimation methodology.

post-stratification of ACS survey


How do I generate a uniform random integer partition?

Question: A Google search reveals plenty about generating all possible partitions of an integer n into m parts, but I haven't found anything about sampling a uniformly distributed random partition of n into m parts.
Comment: @Beta It's not entirely clear to me what algorithm you are suggesting. Could you be more specific? Also, of the possible interpretations I can think of for your suggestion, some of them seem like they might plausibly result in uniform distribution, but others do not.
Comment: @Moron Generally, when working with partitions, it is accepted that order does not matter and zeros are not allowed.
Comment: Maybe I'm missing something. Why not just do m uniformly distributed cuts (over the remaining possible cut-points)? You might be able to optimize a little, but probably not a lot.
Comment: There is some ambiguity in the question. For instance, does the order matter? Are zeroes allowed?
Comment: opencover: To clarify, you mean an algorithm that's equivalent to (a) generate all possible partitions; (b) choose one at random.  But hopefully much faster.  Right?
Comment: @Beta: say n=9 and m=3.  Then choosing random cut-points, there are several ways to get the partition {1,1,7}, but only one way to get the partition {3,3,3}, so it will not be uniform.
Comment: The answer of Beta is only valid if the order matters.
Comment: Well, when n is large and n/m = k where k is a small integer, you can use the same trick that I just posted here -- http://stackoverflow.com/a/29849947/134852 Or you can check section 7 of this paper -- http://arxiv.org/pdf/1504.06238v1.pdf
Comment: Related: https://stats.stackexchange.com/q/497858/2921, https://cs.stackexchange.com/q/154784/755
Answer: The title of this post is a bit misleading.  A random integer partition is by default unrestricted, meaning it can have as many parts of any size.  The specific question asked is about partitions of n into m parts, which is a type of restricted integer partition.
For generating unrestricted integer partitions, a very fast and simple algorithm is due to Fristedt, in a paper called The Structure of Random Partitions of Large Integer (1993).  The algorithm is as follows:

Set x = exp(-pi/sqrt(6n) ).
Generate independent random variables Z(1), Z(2), ..., Z(n), where Z(i) is geometrically distributed with parameter 1-x^i.
IF sum i*Z(i) = n, where the sum is taken over all i=1,2,...,n, then STOP.
ELSE, repeat 2.

Once the algorithm stops, then Z(1) is the number of 1s, Z(2) is the number of 2s,  etc., in a partition chosen uniformly at random.  The probability of accepting a randomly chosen set of Z's is asymptotically 1/(94n^3)^(1/4), which means one would expect to run this algorithm O(n^(3/4)) times before accepting a single sample.
The reason I took the time to explain this algorithm is because it applies directly to the problem of generating a partition of n into exactly m parts.  First, observe that
The number of partitions of n into exactly m parts is equal to the number of partitions of n with largest part equal to m.
Then we may apply Fristedt's algorithm directly, but instead of generating Z(1), Z(2), ..., Z(n), we can generate Z(1), Z(2), ..., Z(m-1), Z(m)+1 (the +1 here ensures that the largest part is exactly m, and 1+Z(m) is equal in distribution to Z(m) conditional on Z(m)>=1) and set all other Z(m+1), Z(m+2), ... equal to 0.  Then once we obtain the target sum in step 3 we are also guaranteed to have an unbiased sample.  To obtain a partition of n into exactly m parts simply take the conjugate of the partition generated.
The advantage this has over the recursive method of Nijenhuis and Wilf is that there is no memory requirements other than to store the random variables Z(1), Z(2), etc.  Also, the value of x can be anything between 0 and 1 and this algorithm is still unbiased!  Choosing a good value of x, however, can make the algorithm much faster, though the choice in Step 1 is nearly optimal for unrestricted integer partitions.
If n is really huge and Fristedt's algorithm takes too long (and table methods are out of the question), then there are other options, but they are a little more complicated; see my thesis https://sites.google.com/site/stephendesalvo/home/papers for more info on probabilistic divide-and-conquer and its applications.
Comment: Set partitions are an example of an assembly: https://arxiv.org/pdf/1308.3279.pdf
One uses Poisson(\lambda_i) in place of Geometric, where \lambda_i = x^i/i!, for any x >0, with x satisfying: x*e^x = n being optimal.
An extremely fast algorithm using PDC deterministic second half appears in: https://arxiv.org/pdf/1411.6698.pdf  Section 8.7
Comment: @stephen-desalvo do you know, from the top of your head, a nice algorithm to generate _set_ partitions? I need to generate plenty of random set partitions, where the set size is a) 64, b) 128.
Answer: Here is some code that does it. This is O(n2) the first time you call it, but it builds a cache so that subsequent calls are O(n).
import random

cache = {}

def count_partitions(n, limit):
    if n == 0:
        return 1
    if (n, limit) in cache:
        return cache[n, limit]
    x = cache[n, limit] = sum(count_partitions(n-k, k) for k in range(1, min(limit, n) + 1))
    return x

def random_partition(n):
    a = []
    limit = n
    total = count_partitions(n, limit)
    which = random.randrange(total)
    while n:
        for k in range(1, min(limit, n) + 1):
            count = count_partitions(n-k, k)
            if which < count:
                break
            which -= count
        a.append(k)
        limit = k
        n -= k
    return a

How this works: We can calculate how many partitions of an integer n there are in O(n2) time. As a side effect, this produces a table of size O(n2) which we can then use to generate the kth partition of n, for any integer k, in O(n) time.
So let total = the number of partitions. Pick a random number k from 0 to total - 1. Generate the kth partition.
Comment: So count_partitions(n, limit) counts the number of partitions of n into parts less than or equal to limit. Okay, I see how you're counting that. And then, given a bijection between the integers 1,...,count_partitions(n,n) and the partitions of n, random_partition chooses one of those integers and constructs the corresponding partition. Of course, this solution doesn't quite address the question, which asked for a random partition of n *into exactly m parts*. I suppose I should have made that clear in the title. However, I can definitely come up with what I need based on this.
Comment: Oh, I'm sorry. I misread the question! Anyway, all I did was take some code I already had for generating all partitions, make two copies, and turn one copy into the counting function and the other copy into the kth-partition-constructing function. The exact same approach should work for your problem.
Comment: Oops! Never got around to marking this as answered. Sorry about that.
Comment: This algorithm is found in this paper: [Uniform random integer partition](http://pfigshare-u-files.s3.amazonaws.com/484635/Partitioning_paper.pdf)
Answer: Another algorithm from Combinatorial Algorithms page 52, "Random Generation of n into k parts"

Choose a1, a2, .. , ak-1 a random k-1 subset of {1,2,..,n+k-1} (see below 1., 2.)
Set r1 = a1-1; rj = aj - aj-1-1 (j=2..k-1); rk = n+k-1- ak-1
The rj (j=1..k) constitute the random partition of n into k parts

This algorithm for random compositions is based on the
  "balls-in-cells" model.
Briefly we choose the posiitons of the cell
  boundaries at random, then by differencing we find out how many balls
  are in each cell.

For efficiently generating a random subset of a set, see a 1. related answer here and 2. here
update
Another approach using a single random number in [0,1] to uniformly generate a random partition (also called composition) is given in IVAN STOJMENOVIC, "ON RANDOM AND ADAPTIVE PARALLEL GENERATION OF COMBINATORIAL OBJECTS" (section 5, section 10)
Answer: Just one more version in c#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication6
{
    class Program
    {
        static Random random = new Random();

        static void Main(string[] args)
        {
            PrintPartition(GetUniformPartition(24, 5));
            PrintPartition(GetUniformPartition(24, 5));
            PrintPartition(GetUniformPartition(24, 5));
            PrintPartition(GetUniformPartition(24, 5));
            PrintPartition(GetUniformPartition(24, 5));
            Console.ReadKey();
        }

        static int[] GetUniformPartition(int input, int parts)
        {
            if(input<= 0 || parts <= 0)
                throw new ArgumentException("invalid input or parts");
            if (input < MinUniformPartition(parts))
                throw new ArgumentException("input is to small");

            int[] partition = new int[parts];
            int sum = 0;
            for (int i = 0; i < parts-1; i++)
            {
                int max = input - MinUniformPartition(parts - i - 1) - sum;
                partition[i] = random.Next(parts - i, max);
                sum += partition[i];
            }
            partition[parts - 1] = input - sum; // last
            return partition;
        }

        // sum of 1,2,3,4,..,n
        static int MinUniformPartition(int n)
        {
            return n * n - 1;
        }

        static void PrintPartition(int[] p)
        {
            for (int i = 0; i < p.Length; i++)
            {
                Console.Write("{0},", p[i]);
            }
            Console.WriteLine();
        }
    }
}

This code will produce next output:
5,8,7,2,2,
6,6,7,2,3,
5,7,6,2,4,
6,4,3,2,9,
7,8,4,4,1,

Answer: I have an evenly distributed partition generator.
Where n := the integer to be partitioned, r:= the number of slices:
The algorithm is a patched version of the naive method of simply inserting partings at random. The problem with this method, as it appeared to me when I looked at its output, was that scenarios where partings are placed in the same spot are less likely to occur. There is only one way to get {1,1,1}, while there are 3! ways of getting {2,4,9}, any of {4,2,9},{2,4,9},{9,4,2}... will lead to the same partition placement when sorted. This has been amended by providing additional explicit opportunities for repeats. For each parting insertion, there's a chance that the position of the parting wont be random, but will be selected as a repeat of a formerly selected value. This balances the uneven probability distribution of the naive method right out.
I have proved by exhaustion that each partitioning is perfectly equally likely for r = 3, n = 2. I cbf proving it for higher values but healfhearted ventures to do so found only promising signs. I also tested it on random input, finding that it is at least roughly even for every values I tried[but probably perfectly even].
here it is in C++11: [the output format is different to what you're expecting, it's the positions of the partings rather than the size of the space between them. The conversion is easy, though]
#include <vector>
#include <algorithm>
#include <random>
#include <cassert>
template <typename Parting, typename Seed>
vector<Parting> partitionGen(unsigned nparts, unsigned bandw, Seed seed){//nparts is the number of parts, that is, one greater than the number of dividers listed in the output vector. Bandw is the integer being partitioned.
    assert(nparts > 0);
    vector<Parting> out(nparts-1);
    srand(seed);
    unsigned genRange = bandw;
    for(auto i=out.begin(); i<out.end(); ++i, ++genRange){
        unsigned gen = rand()%genRange;
        *i = ((gen<bandw)?
            gen:
            *(i-(gen-bandw+1)));
    }
    sort(out.begin(), out.end(), less<Parting>());
    return out;
}

I don't like the fact that I have to sort it though. If Vlody's version has an even distribution, it appears that it'd be better.
Answer: After some googling I found an algorithm for this in the "Handbook of Applied Algorithms," which Google Books has indexed. The algorithm is given in section 1.12.2, on page 31.
Comment: Yeah, I came across that, too. It doesn't generate partitions with exactly m parts, and it assumes that RP(n,m) (equivalent to Jason's count_partitions(n, limit), with limit = m) has already been computed. I'm thinking less work needs to be done to compute the number of partitions of n into m parts.
Answer: I have implemented the above solution and found that it works very well if one wants to calculate integer partitions for n but not with respect to m. If working with large n, recursion limits and call stacks may need to be increased a lot.
However, you don't need the first function because count_partitions(n, limit) will actually equal the number of partitions of 'n+limit' with 'limit' number of parts. Some mathematical software have very fast functions for finding the number of partition of n into m parts.
I have recently derived a definitely unbiased, very simple, and very fast method (using memoization) to solve your exact question: An algorithm for randomly generating integer partitions of a particular length, in Python?
It's based on knowing something about lexically ordered partitions of n having m parts and uses a similar approach to well-accepted algorithms (e.g. Nijenhuis and Wilf 1978) that find random partitions of n, and is conceptually similar to the above.
In short, if there are x partitions of n with m parts, then we choose a random number between 1 and x. That random number will code for one and only one partition satisfying n and m. I hope this helps.


Photos and iCloud cannot see photos on iCloud safe to delete?

Question: I want to delete photos from my Mac to free up space. I've never gone to iCloud before to check on my back ups and just assumed they occurred. However when i go to iCloud it shows nothing but find phone. Is there a way to see photos? The only question i see that actually addresses this is negatively voted on, and the only answer did not address the Question but was geared toward organizing library and space on cloud. I just want to know my stuff is there. How? if I cannot see it??
Comment: never come to this site, so sorry if i sound stupid. all research indicates iCloud should look similar to my dock, but it doesn't.
Answer: If you enable iCloud Photo Library on your Mac, and your photos are on the Photos app, you can set it up to save originals on the cloud and automatically save space by keeping a lower resolution copy on your Mac.
To do this, go to Preferences > iCloud, then select "Optimize".
This will also allow you to view your entire collection on iCloud.com if you wish.
Note that you have no saying on when the app starts "saving space" on your behalf, and that if you delete a photo on your Mac it will be deleted on iCloud too; it is more a synchronization service than a storage on the cloud service, with the advantage of the space optimization.
Also, there is no Mac iCloud backup service to my knowledge; you can only backup to Time Machine —or some other backup service of your preference, of course. You may have some of your documents synchronized to iCloud but if you delete them locally they will also be deleted there.
Time Machine erases old backups when it runs out of space, so it won't work as a long term storage solution either, unless you have lots of space available —so it does not need to delete your old backups in order to make space for the new ones.
Comment: @gracey209 It was reset and works fine now! I called the store and the genius bar techpeople said it was a bug that affected a certain number of users who got iCloud so now its fine. thanks u
Answer: My understanding is that iCloud is for storage of photos, and not just for synchronization; otherwise, why would you have the option to purchase more space (which I have done). That being said, @Jaime Santa Cruz is correct in that you cannot back up Time Machine to iCloud, but you should be able to indefinitely store photos, docs, notes, etc., so long as you keep within the storage limit or purchase (and continue to pay) for additional storage.
I had the same problem and actually wrote a question about it just the other day and received a number or comments and an answer. Deleting Photos, what iCloud saves and how to access things from iCloud and device storage issues It seemed clear from what others were saying that I should be able to see icons in iCloud, such as photos, and when you click on/open these tabs you should be able to see your photos/docs. I could not.
It was suggested I contact Apple support if there was nothing there aside from Find My Phone (which there was not - sounds like this is what you are saying). I did contact Apple and sure enough, there was a problem on iCloud/Apple's end and they need to remotely reset my iCloud account(this is the word they used, from a  technical perspective I have no clue what was wrong or what they did to fix it), but after about 15 minutes with them iCloud appeared as it should and never had before. There was an orange background with most of the app icons that appear on the dock, and I could now view my photographs and documents, etc.
If iCloud is turned on, your devices are synced and you are going to iCloud.com and getting a black background with just a FMP, you probably need to do what I did.
Comment: i noticed this question and it seemed you were asking the same...i was even afraid to ask because i saw you got a negative for asking...but this is my problem. I read the answer you got but that was about storage on iCloud so i thought either that person did not understand what you were saying or i ws reading it wrong. but now i know you may be right. i will call apple and LUK
Comment: Good luck. I looked like an idiot and did get a down vote, but at least I realized that iCloud was not acting as it should. Let us know if this works. Don't be surprised if a more senior user ends up saying your question is too similar to another. You should edit for grammar. This site is quite picky about using caps when appropriate, not using text lingo, and using proper punctuation. Otherwise, someone else probably will :~) .


Is Bluefish text editor compatible for Xfce(GKT2)?

Question: I like Bluefish text editor but want to make sure it doesn't have a huge set of libraries that will swamp my small computer. I'm using Xubuntu 13.10.
Comment: ...I guess your question is mainly if Bluefish it is too heavy, rather than if it is compatible with XFce?
Comment: Yes, you're right, Jacob.
Answer: If you want to know what bluefish depends on and what it will install, search the application in synaptic and right click on it's name. In Properties you will see all dependencies and the size of the application.


Repair/Check for empty geometry in ArcSDE?

Question: I understand that the standard validation/repair tools are not for use with ArcSDE and that ESRI needs to fix this, but are there work-arounds for at least checking where there might be empty geometry in a feature using ArcObjects or a script? Anything really. I'm attempting to export features from layers in an ArcSDE instance but some of those layers in the database give the "Attempted an operation on empty geometry" error when attempting to extract. I'm running ArcMap 10.3
Comment: I suspect you are misidentifying the problem in this situation.  Please **edit** the question to describe the environment and behavior more completely (which version of ArcGIS, what type of geometry storage, the coordinate system and coordinate reference values for the input and output layers, what exact command is being used to perform the export), so that the *actual* problem can be identified and a solution offered.
Comment: I think Vince may be correct. As are you, in that geometry repair cannot be run on sde data. However I think the empty geometry is more of a selection problem. If you are exporting from a csv, I have fixed this problem by selecting all of the rows (that have values) and then exporting.
Answer: Here is my solution...

open in arcmap the suspect layer.
zoom to the entire dataset.
make it the only selectable layer (if there is more than one)
start editing
make a selection box around all of the features
switch the selection
you now have all the <NULL> geometry rows in the sde table.
delete
Comment: This is a great suggestion, but I tried it and there were no other features selected after I switched the selection. The table has only five features and all 5 features were returned in the selection. Once the selection was switched, no other features were selected.
Comment: see my comment above. I do not think your problem is related to the null geometry. rather no geometry. Mark this as answered and start a new question with more info (as requested by Vince) referring to the empty geometry, export format, software ver, origin data format.
Answer: ArcGIS does not include tools to detect corrupt geometries because it is not possible to create them (short of hacking the SDE metadata tables).  Native SQL types can create corrupt geometries, if ArcGIS is not used in the pipeline, but then there are native tools to detect and repair or delete those same corrupt geometries, so no Esri tools are needed.
A definition or selection query of SHAPE IS NULL or SHAPE IS NOT NULL is the simple solution for identifying NULL or not-NULL features (this will work for all storage types).  This is not an error condition, just a natural database state, for which repair tools are not necessary.
Detecting NIL shapes (not-NULL shapes with zero vertices) is a different problem, easily detected with SQL queries by storage type (e.g., WHERE sde.ST_NumPoints(shape) = 0).  NIL shapes are also not invalid, since they can only be populated if the database layer permits them (the "n" in "npc", "npc+", "nslc+", and "nac+" entity flags layer properties).  Any supported mechanism to remove NILs from a layer would also first delete the NILs in the layer.
The most common way to generate invalid geometries is by using inappropriate on-the-fly projection parameters, which result in horizon clipping or vertex sequences beyond the coordinate reference precision.  These objects are not technically in the data table, and therefore do not need detection/removal tools either.
It is far more likely that there is an error in your procedure that is producing corrupt output than that filesystem corruption has occurred only to the degree to cause subtle errors in a few disparate byte sequences which will still pass internal validation checks (and if this has occurred, you should immediately buy a lottery ticket, since normal rules of causality do not apply).
Comment: It is possible to create null geometry in sde. start an edit session. Open attribute table. Go to the bottom of the table and click on the next available record. Type anything in one field. Hit enter. Stop editing.  Another thing that happens is I see my editors using copy paste multiple times quickly. If you get out of step it automatically jumps to the bottom. paste and hit enter and now you have a null geometry.
Answer: Assuming that you are running ArcSDE with ST_GEOMETRY as your storage type, you can use the ST_IsEmpty function to check for empty geometries. You can do this within a definition query applied to your layer like this :
objectid IN
(SELECT objectid
FROM your_table
WHERE sde.st_isempty(shape) = 1)

Adjust accordingly as per your unique id column, table name and database backend (the example above applies to Oracle). Also be careful if you are running the query on a versioned table. You should run the query against a (multi)versioned view if that is the case.


Since when is a Feruchemist able to only have one power?

Question: Based on the first Mistborn trilogy, it seems that unlike Allomancy, if you were a Feruchemist, you were able to use a Metalmind made of any metal. However, in the Wax Wayne trilogy, it is clear that most (if not all) Feruchemists can only tap into one Metalmind.
Was Feruchemy always like this - that it was possible to only have one power? Or did Sazed/Harmony change the rules when he recreated the world?
Answer: There are a few major factors at play here.
The first is the weakening of the allomantic bloodlines over time.  By the time the Catacendre happens, it's implied that Spook is the only remaining Mistborn; and he is a standard weaker Mistborn, unlike Elend who was a full Mistborn due to the Lerasium bead.  Source
The other major factor is the mixing of bloodlines.  Before the Catacendre, Terris seem to be regulated pretty highly in terms of their breeding and mixing with the general population.  This made it highly unlikely that the Terris would have bred with someone who had a strong enough allomantic bloodline to produce a ferring/misting combination.
Brandon Sanderson has said that you cannot be born both a full feruchemist and a full allomancer; there is too much interference between the powers. Ferrings were not possible before the final empire either.source
It's not really clear where all the feurochemists went at the time of the Catacendre, but we have not seen evidence of them in Era 2.  I've seen speculation, and personally subscribe to the theory that in the Terris community, they still have full feurochemists somewhere.  Just like during The Lord Rulers reign though, they are able to keep it a secret.
From the story, I don't see anything that definitely suggests that Harmony intervened to cause this situation.  It makes sense that it occurs naturally, but I could also understand Harmony doing this on purpose, especially with the Ruin aspect of his powers.
Comment: I'm had thought Sanderson went on record that Harmony tinkered to keep things calmer and not have so many god-like humans running around.  Can't find it now though.
Comment: @Radhil I thought that at first too; but everything I can find on 17th Shard suggests he just let it run it's course.  The lack of Mistborn makes decent sense with the narrative.  The lack of full Feurochemists is a bit suspicious;  but I think there's still a small chance some are hiding.  The Terris seemed to be really good at breeding them in secret.
Comment: where did you get the idea that spook was a weaker mistborn? lerasium is a piece of preservations essence so if preservation (or harmony) made someone a mistborn they should be full power
Comment: @Stormblessed No, the Lord Ruler was a mistborn and full feruchemist.  He was only born a full feruchemist though.  He was able to give himself full mistborn powers (possibly more than just a single Lerasium bead even, his allomancy was very strong) when he took the power of the well.
Comment: @Antheloth If Preservation (or Harmony) made someone a Mistborn without Lerasium they would have control over how much power they can provide.  In this case, we have at least one (but I believe multiple) "Words of Brandon" saying he was not full power.  https://wob.coppermind.net/events/243-hero-of-ages-qa-time-wasters-guide/#e5265
Comment: So the Lord Ruler was just a mistborn and a ferring?
Comment: @JMac Oh, I forgot that thanks
Answer: The reason for the diluting of the genes for feruchemy is because the remaining steel inquisitors went to the Terris Dominance and killed all the Keepers they could find. It's commonly held that, by the time of the Catacendre, Sazed was the only full feruchemist left alive.
However, the Terris people still had the genes for feruchemy, just in a more diluted form, and after the Catacendre, they started interbreeding with outsiders, leading to a further dilution of the genes, resulting in ferrings.
You can read all about it on coppermind.net/wiki/Feruchemy. There's a history section that details all of this.
Comment: Could you [edit] in some relevant information (quotes) from the link? Or better yet go to the source material (books) and get some supporting quotes from them to edit in.


What restrictions are there on paid applications?

Question: If I pay for a program can I install it on the three computers I use on a daily basis?
How is licensing decided or are there any restrictions on licenses used?
Where are these kinds of questions documented?
Answer: This really depends on the publisher of the application.
There is a page with information on how licenses work for paid applications in the Ubuntu Software Center:

Once you've enabled licence keys, Ubuntu Software Centre will fetch a licence key when it completes a purchase, and copy that into the right file for your app to check. It is up to you, the developer, to provide keys that are hard to guess, check if the key is there when your application starts and behave accordingly.
You will receive a notification by email when the number of available licence keys goes below a certain configurable threshold, and you will see notices when you visit the website telling you about this also. If we run out of license keys we will necessarily stop selling copies of your app.
Comment: I need more information on this licensing. How it works, how I can implement it, where will it be located, how can I provide the license range (assuming it is a running number, noob here sorry) to Ubuntu etc.
Answer: All paid applications in the Software Center are user based. The Software Center will allow you to install on all three of your computers. If the application is licensed via a license key, this same license will be used on all three - note that you may be violating the terms of use of the application, however it is not enforced by the Software Center.
The new website has a FAQ page at http://developer.ubuntu.com/publish/commercial-software-faqs/ that answers these questions.
Answer: Currently there's no DRM-like application security system. Developers have to rely on the good will of the users to appreciate the fact that there's no DRM and show that they're responsible enough to not need any DRM.
If you want to install your previous purchages after reinstalling Ubuntu, just click on the File -> Reinstall Previous Purchases menu item in Software Center. You'll be prompted for your login details when you click it. And from here it all depends on what happens then: I expect you can download and install the app (not tested ;) ) but technically the website you download from could block you and make you pay again. Save the .deb if you want to be sure.
Partly taken from: Do I need to re-purchase software in the Ubuntu Software Centre if I reinstall?
Answer: I would imagine this would depend on the program. I would first check the publisher's website for the program in question to see what licensing restrictions they have.
If you specified the program name, we might be able to help you out more.
Comment: I guess I should have noticed the software-center tag, sorry.
Comment: Thanks but I'm fishing for an authoritative answer or documentation if it exists. As paid apps begin to play a bigger part in in Linux, does Ubuntu have stated policy for inclusion, in the software center and especially for these particular questions because I'd like to start supporting some in this way.


ec2 spot complete price history

Question: I am using API to get ec2 spot price history, but I cannot get anything except for last 90 or so days, and cannot specify frequency of observations. Is there a way to get a complete history of spot prices, preferable at minute or hourly frequency?
Comment: Could you post a request example?
Answer: While not explicitly documented for the DescribeSpotPriceHistory API action, this restriction is at least mentioned for the AWS Management Console (which uses that API in turn), see Viewing Spot Price History:

You can view the Spot Price history over a period from one to 90 days based on the instance type, the operating system you want the instance to run on, the time period, and the Availability Zone in which it will be launched.

Since anybody could have retrieved and logged the entire spot price history ever since this API is available (and without a doubt quite some users and researchers have done just that; even the AWS blog listed some dedicated Third-Party AWS Tracking Sites, but these are all defunct at first sight), this restriction admittedly seems a bit arbitrary, but is certainly pragmatic from a strictly operational point of view, i.e. you have all the information you need to base future bids upon (esp. given AWS has only ever reduced prices so far, and regularly does so in fact much to the delight of its customers).

Likewise there's no option to change the frequency, so you'd need to resort to client side code for the hourly aggregation.
Comment: Every site listed in the "Third-Party AWS Tracking Sites" post is now dead. :-(
Answer: This website has re-sampled EC2 spot price histories for some regions, you may access them via a simple API directly from your Python script:
http://ec2-spot-prices.ai-mmo-games.de/
I hope this helps.
Comment: Looks like this site has disappeared.
Answer: AWS only provides 90 days of history.  And the data is raw, i.e., not normalized by hour or even minute.  so there are holes in the data sometimes.
One approach would be to suck in the data into an ipython notebook and use pandas excellent time series tools to resample by minute or 5-min etc.  here's a short tutorial:
https://medium.com/cloud-uprising/the-data-science-of-aws-spot-pricing-8bed655caed2
here are more details on using pandas for time-series resampling:
http://pandas.pydata.org/pandas-docs/stable/timeseries.html
hope that helps...
Comment: Please summarize the details from the links.

ec2 spot complete price history


How far is Brahmaloka from our Earth?

Question: I mean where does Brahmaloka lie? Is there any scripture that tells it's exact location and time difference between different lokas?
Comment: The different spheres, lokas, are at different levels of vibration. The spiritual realms are not within the sensual universe. The Puranas describe them in material dimensional space as all cannot grasp the concepts of spiritual realms, but can easily understand a vast spatial distance as most think of themselves as material beings
Comment: The different spheres, lokas, are at different levels of vibration. The spiritual realms are not within the sensual universe. The Puranas describe them in material dimensional space as all cannot grasp the concepts of spiritual realms, but can easily understand a vast spatial distance as most think of themselves as material beings
Comment: "The spiritual realms are not within the sensual universe." Proving its existence is impossible then. Such a statement must then be refuted.
Comment: I had seen an image from some book, which shows all 14 Lokas and their distance in yojanas, but I can't find it now
Answer: A partial answer ...
Skanda Purana says that the distance is 8 crore yojanas.
Quoting from the book "Essence of Skanda Purana":

there was no Place like Bharat which happened to be the 'Karmabhumi'
or the Place where Noble Deeds were rewarded and there was no Tirtha
like Kasi and no Bhagavan like Viswanath Linga in the Universe.'
Having visited Satya Loka, Siva Sharma asked the Vishnu Prashads as to
how far he would have to travel farther and the latter replied that
from Prithvi to Surya Loka the distance was away by a lakh Yojanas
(one Yojana is 13-16 km approx); from Prithvi to Maha Loka is one
Crore Yojanas; from Prithvi to Jana Loka is two crore yojanas, four
crore yojanas from Prithvi to Tapa Loka and eight crore yojanas to Satya Loka;
sixteen crore yojanas to Vishnu Loka and sixteen times higher from
Vaikuntha to Kailasa Dham; in other words, the distance from Bhu Loka
to Kailas is a staggering figure of two arab and fifty six crore
yojanas! From Satya Loka Siva Sharma was blessed to travel further to
reside at Vaikuntha.

Note that Brahmaloka is another name for the Satyaloka. And, for understanding the unit of measurement, Yojana, see the wiki article.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/91283/discussion-on-answer-by-rickross-how-far-is-brahmaloka-from-our-earth).
Answer: The answer lies in the Vishnu Purana:

Parasara said: The sphere of the earth (or Bhúr-loka), comprehending its oceans, mountains, and rivers, extends as far as it is illuminated by the rays of the sun and moon; and to the same extent, both in diameter and circumference, the sphere of the sky (Bhuvar-loka) spreads above it (as far upwards as to the planetary sphere, or Swar-loka). The solar orb is situated a hundred thousand yojanas from the earth; and that of the moon an equal distance from the sun. At the same interval above the moon occurs the orbit of all the lunar constellations. The planet Budha (Mercury) is two hundred thousand yojanas above the lunar mansions. Śukra (Venus) is at the same distance from Mercury. Angáraka (Mars) is as far above Venus; and the priest of the gods (Vrihaspati, or Jupiter) as far from Mars: whilst Saturn (Sani) is two hundred and fifty thousand yojanas beyond Jupiter. The sphere of the seven Rishis (Ursa Major) is a hundred thousand yojanas above Saturn; and at a similar height above the seven Rishis is Dhruva (the pole-star), the pivot or axis of the whole planetary circle. Such, Maitreya, is the elevation of the three spheres (Bhúr, Bhuvar, Swar) which form the region of the consequences of works. The region of works is here (or in the land of Bhárata). Above Dhruva, at the distance of ton million yojanas, lies the sphere of saints, or Mahar-loka, the inhabitants of which dwell in it throughout a Kalpa, or day of Brahmá. At twice that distance is situated Janaloka, where Sanandana and other pure-minded sons of Brahmá, reside. At four times the distance, between the two last, lies the Tapo-loka (the sphere of penance), inhabited by the deities called Vaibhrájas, who are unconsumable by fire. At six times the distance (a hundred and twenty millions of yojanas) is situated Satya-loka (Brahma-loka), the sphere of truth, the inhabitants of which never again know death. (Vishnu Purana, Book II, Chapter VII)
Comment: Why did you delete the answer?
Comment: So the answer is 120 million yojanas, right?
Comment: @Wikash_hindu Idk. Not sure if that calculation is correct.
Comment: A yojana is about 12-15 km. Thusly the distance is 1440 million km - 1800 million km.
Answer:

The extent to which the rays of the sun and the moon shine and illuminate is the size of the earth. It is called Bhūloka.

2-3. The sun's sphere is situated a hundred thousand Yojanas from the
earth. The moon is situated thousands of Yojanas from this earth and a
hundred thousand Yojanas from the sun.

The spheres of the planets are entirely situated above the moon along with the stars about ten thousand Yojanas one above the other.

Budha (Mercury); above that is Kāvya (Venus): above that is the sphere of Bhauma (Mars). Bṛhaspati (Jupiter) is above that and
Śanaiścara (Saturn) is above that.

The sphere of the seven sages (The Ursa Major) is situated a hundred thousand Yojanas above it. The Pole Star (Dhruva) is situated
a hundred thousand Yojanas above the sages.

The Pole star is the prop of the circle of luminary bodies.1 The Bhuvarloka and Svarloka are above the earth but beneath the Pole star.

A crore Yojanas above the Pole star is the Maharloka where the seven sons of Brahmā are stationed. They live even during the time of
Kalpa.

The seven sons are—Sanaka, Sananda, Sanātana, Kapila, Āsuri, Voḍhu and Pañcaśikha.

Above that is stationed Śukra (Venus) at a distance of two hundred thousand Yojanas. Two hundred thousand Yojanas below it is stationed
Budha (Mercury) the son of the moon.

O sage, Bhauma (Mars) is stationed two hundred thousand Yojanas above it. Bṛhaspati (Jupiter) is stationed two hundred thousand
Yojanas above it.

Two hundred thousand Yojanas above Jupiter, Saturn is stationed. These are the seven planets that stay in their respective zodiacs.

The seven sages (Ursa Major) are stationed eleven hundred thousand Yojanas above the planet Saturn. The Dhruva star is said to be
stationed fourteen hundred thousand Yojanas above the great star.

Sixty-three hundred thousand Yojanas from Janaloka is stationed the Tapoloka  the gods called Vairājas stay. They are free from
burning sensation.

15-16. Eighty four thousand Yojanas from Tapoloka is stationed the
Satyaloka. It is known as Brahmaloka where the pure-minded, perfectly
wise Brahmacārins engaged in truthful virtue stay. Men who go there
from the earth also stay there.

Shiva Purana

How far is Brahmaloka from our Earth?


Bluetooth receiver (H-163) makes noise

Question: I just bought a Bluetooth receiver and whenever I connect it to the radio it started to make some weird noises like beep constantly. I then decided to take a look to this problem on the internet and the solution that I found was to connect it to a 6V supply(https://www.youtube.com/watch?v=_JupcaTRKYk), but if I connect it to 6V it randomly turns off, which didn't happen on the normal connector (5V). What can I do to solve it? I'm new in electronics so maybe you can give me a hand on this.
Here is a diagram of the Bluetooth receiver and some specifications:

And my power supply is a modified cellphone charger which I change the Zener diode for a 6.2V one:
input:100-240Vac; 50/60Hz; 0.35A
|||output: 6.2V---2A
Comment: Questions on the usage of products are generally off topic.  Your modification of a phone charger sounds quite suspect, too.
Comment: Agustin, it is difficult to answer your question, because you didn't tell us what is your BT receiver. That's because probably this problem only shows up in some kind of device. By the way, in electronics, we don't say "6V current": Volts are a measure of electric potential, not current. You didn't said where you found this solution to connect the module to 6V, but, the better option would be to follow the instructions of the maker of the device: which are the specs of the device? 5V or 6V? It would help if you add a schematic showing how you connected it, and which power source you are using.
Answer: Your problem is power supply noise that is causing the buzz sound to come.
This happened to one of my tutors and it used the power supply isolation to remove the noise using any 5V to 5V isolation circuit.
You can also buy a new good power supply from some reputed company, 6V is not needed at all. 5V will work fine.
Comment: Answers on this site must stand on their own, they may not rely on external links for the key technical content.  That's true for all links, but doubly so for video links, as video is a horribly inefficient way to present technical information.  It would strongly appear that the question itself does not belong on this site.

Bluetooth receiver (H-163) makes noise


What is the difference between the words concede, admit and accept?

Question: In which situations is the word concede used, in which situations is the word admit used, and in which situations is the word accept used?
Comment: What have you found by looking in dictionaries?
Answer: Concede implies reluctance or a change of mind. "I concede your point" means that I reluctantly accept it, or I go back on my previous opinion and now agree with you. Accept is more neutral; "I accept your point" would be valid if I originally agreed with it, and if I didn't.
Admit (in the context of "I admit your point is true") means to concede something as true, again it implies reluctance. Just in my opinion, it doesn't imply as much of a change of heart as concede does. Admit also has the meaning to confess, as in "I admit I ate all the blancmange, but it was a crime of passion".
Answer: Concede: To acknowledge, often reluctantly, as being true e.g.

He finally conceded that she was right.

Admit: To grant to be real, valid, or true; acknowledge e.g.

admit the truth.

Accept: To agree to take (a duty or responsibility), to answer affirmatively e.g.

accept an invitation.


How do you set requirements (such as minimum length) on passwords?

Question: Is there any way to set up minimum passcode requirements, such as a minimum length, requirement of mixed case alphanumerics and at least 1 symbol in the passcode, and enforce that at passcode changes?
Answer: Password complexity in Ubuntu is controlled by PAM. Unfortunately, PAM is "typically Unix" like in its approach. Meaning that it spreads its configuration through a large number of very confusing files.
The file that controls password complexity is:
/etc/pam.d/common-password

There is a line:
password [success=1 default=ignore] pam_unix.so obscure sha512

Which defines the basic rules for password complexity. You can add a minimum length override by changing it to:
password [success=1 default=ignore] pam_unix.so obscure sha512 minlen=12

or whatever minimum you want. As you can see, the default already defines some basic obscurity rules. These basic rules can be seen in:
man pam_unix

Search for "obscure".
There are a large number of pam modules that can be installed.
apt-cache search libpam-

Should show you them.
You will need to hunt down the documenation for them I'm afraid. But the "cracklib" is a common addition.
UPDATE: I should have pointed out that the default "obscure" parameter includes tests for complexity based on previous passwords and simplicity (length, number of different types of character). The example in the manpage shows cracklib in action. Install libpam_cracklib to get that working.
Also, once you have worked out what to change, the changes are the same in other files so that you can enforce the same (or different) password checks for SSH and other applications.
Comment: According to `man pam_unix`, the default password minlength is 6 chars if you search `minlen`.
Comment: this doesnt work for ubuntu 18.04 - even with this setting I can put any password I want (short, palindrome,.. ) - I just need to repeat such password 4x :(
Comment: When you say "doesn't work", it isn't clear what you mean. Do you mean that it **does** work but that repeating the short password 4 times is some kind of "bypass" - if so, respectfully, you are wrong, that is still a strong passcode. Otherwise, could you please clarify?
Answer: Pre-installed PAM modules allow you to set up basic requirements within the light of complexity. There is a nice module which is a successor of pam_cracklib module - pam_pwquality. In order to install it type the following
apt-get install libpam-pwquality

then get familiar with this one
man pam_pwquality

especially with the "Options" section.
Now you can edit the common-password in /etc/pam.d/
vi /etc/pam.d/common-password

find the line which contains the following "password        requisite                       pam_pwquality.so" statement and after pam_pwquality.so attach your options like this
password        requisite         pam_pwquality.so minlen=16 ucredit=-4 retry=3

which stands for "the minimum size of password is 16 characters, where minimum 4 of them a uppercase. Prompt user for password 3 times.
pam_pwquality allows you make much more complex password requirements in combination with other modules like pam_pwhistory. Good luck
Answer: Password values are controlled in the file
/etc/pam.d/common-password

For more information on how to modify the file see pam_unix manpage


How to solve recursion T(n)=T(n/2)+T(n/3)+n?

Question: How to solve recursion $T(n)=T(n/2)+T(n/3)+n$? I do not really know how to approach this kind of recurrence.
Comment: Use the Akra-Bazzi theorem.
Comment: I know the theorem but i do not know how to use it.
Answer: This is a straightforward application of the Akra-Bazzi theorem.
You can also show that $T(n) = \Theta(n)$ by induction. First, clearly $T(n) \geq n$. In the other direction, if we have shown that $T(m) \leq 6m$ for $m < n$, then
$$
T(n) \leq 6(n/2 + n/3) + n = 6n.
$$
Therefore as long as the base case holds, and if we ignore the fact that $n/2,n/3$ are not necessarily integers, we can prove inductively that $T(n) \leq 6n$.
Comment: Thank you! If i do not bother you, can you please detail steps for proving it by induction? I applied the Akra-Bazzi after some research, but i need to prove it by induction too. Have a nice day!
Comment: I'm not going to do the exercise for you.


Is the case of a big state space, should we use a softmax exploration policy rather than $\epsilon$-greedy for Q-Learning?

Question: In Reinforcement Learning, epsilon-greedy policies are the most used exploration policies, but in case there is a big state space with impossible actions, wouldn't it be better to use soft-max policies instead?
Answer: In single-step Q learning, you can use almost any exploration policy that you like, provided it covers all choices eventually. Usually you want to focus around the target policy, because that is the most likely to visit parts of the trajectory (state, action, reward sequences) that you want to explore for improvements.
The main problem with using a softmax policy in Q learning* is that you have no independent set of preferences, just value estimates. So the agent's exploration performance would become dependent on the scaling of the reward signals. A simple method to adjust for that is to use a temperature hyperparameter $T$, that divides the action value estimates used in the softmax. A high temperature results in near random behaviour, and a low one will almost always select actions with the highest action value. You can start with a high temperature and slowly decay it, similar to decaying $\epsilon$ for $\epsilon$-greedy.
Will this help for you case? Maybe . . . although using an approach which filtered out the impossible actions would be cleaner and definitely faster (in terms of number of samples required).
There are other approaches you could use, such as Thompson sampling, Gibbs sampling, upper confidence bound (UCB). Some of these don't translate easily to deep RL, so you don't see them mentioned as often, but they can work nicely in tabular approaches.

* Outside of Q-learning, in policy gradient and actor-critic methods a softmax policy can be used more directly, and might be a good choice when action space is large.


Capture text between curly braces in C preprocessed file

Question: I'm working with a preprocessed C source file. I want to extract one function for additional processing. I can find the start of the particular function with:
gcc -DNDEBUG -march=native -E source.c > source.pre

BEGIN=$(grep -n 'static inline int some_function' source.pre | cut -f 1 -d ':')

After the above executes, I have a line number where the function begins. In this case, its 7812.
I am having trouble devising a way to capture the text between the C function's curly braces ({ and }). Based on Extract middle section of lines of a text file, I think this is reducing to a problem of finding the immediate closing brace (}).
How do find the immediate closing brace? Or how do I capture the text between curly braces in C preprocessed file?
Answer: Assuming nothing wacky in the source that might place a stray } on a line by itself, try sed.
sed -n '/^static inline int some_function(/,/^}$/p' source.pre

Comment: Oh, thanks. That's much easier than the path I was going down.


JAXB unmarshal callbacks not called with the Binder implementation of EclipseLink Moxy

Question: I have a problem with the javax.xml.bind.Binder implementation of EclipseLink Moxy: the unmarshal callback methods (afterUnmarshal in my case) annotated in my binding classes are never called when I unmarshal my objects from a DOM document instance.
The problem seems to be in the org.eclipse.persistence.oxm.XMLUnmarshaller instance used by the Binder : the unmarshalListener, which is responsible for calling the callback methods, is always null. This code demonstrates the problem :
<code>//Instantiate a JAXBContext
JAXBContext context = JAXBContext.newInstance(MyObject.class);

//Create a "standard" unmarshaller
JAXBUnmarshaller standardUnmarshaller = (JAXBUnmarshaller) context.createUnmarshaller();

//assertion is ok
assert standardUnmarshaller.getXMLUnmarshaller().getUnmarshalListener() != null;

//Create a Binder
XMLBinder xmlBinder = ((JAXBBinder) context.createBinder()).getXMLBinder();

//Use reflection tricks to get the unmarshaller (fest-reflect is used for conciseness)
XMLUnmarshaller binderUnmarshaller = Reflection.field("unmarshaller").ofType(XMLUnmarshaller.class).in(xmlBinder).get();

//assertion error here
assert binderUnmarshaller.getUnmarshalListener() != null;
</code>
This can't be easily fixed, because org.eclipse.persistence.jaxb.JAXBUnmarshalListener can't be instantiated without a javax.xml.bind.Unmarshaller instance, which does not exist in the Binder context. There is no other XMLUnmarshalListener implementation available in Moxy to replace the JAXBUnmarshalListener.
I came up with this workaround, which consists in reusing the JAXBUnmarshalListener instance from a "standard" JAXB unmarshaller. :
<code>//Instantiate a JAXBContext
JAXBContext context = JAXBContext.newInstance(MyObject.class);

//Create a Binder
JAXBBinder binder = (JAXBBinder) context.createBinder();

//Create an standard unmarshaller to reuse its unmarshalListener
JAXBUnmarshaller standardUnmarshaller = (JAXBUnmarshaller) context.createUnmarshaller();

//Use reflection for setting the binder's unmarshallerListener (fest-reflect again)
XMLUnmarshaller unmarshaller = Reflection.field("unmarshaller").ofType(XMLUnmarshaller.class).in(binder.getXMLBinder()).get();
unmarshaller.setUnmarshalListener(standardUnmarshaller.getXMLUnmarshaller().getUnmarshalListener());

//my unmarshal callbacks are called now
MyObject myObject = binder.unmarshal(domDocument);
</code>
I guess the problem would be the same with the marshaling methods, but I did not investigate this case, as I don't use marshal callbacks.
I tested the JAXB RI implementation of javax.xml.bind.Binder, and the callback methods are called correctly. Though, it is not an option for me to use the RI, because it does not preserve the comment nodes in the original DOM document.
Did I miss something in the configuration of Moxy, or is this a bug in the implementation ? If a bug, is there a simpler workaround than the one I used ?
Answer: I have been able to confirm the issue that you are seeing.  You can use the following link to track our progress on this issue:

http://bugs.eclipse.org/420753


Approval Process Entry Criteria

Question: We are using the trigger to kick off an approval process, the trigger fires when the opportunity is updated, can you please let me know how we can configure the entry criteria to "Is opportunity updated". Thanks for any help on this.
Comment: I agree with @crmprogdev a before/after trigger context may do what you need, but without more information its hard to provide a more accurate solution.
Comment: do you want the approval process to unconditionally start every time the Opportunity is updated? what about if it is already approved or in the middle of an approval process?
Answer: There's a "Before Update" and an "After Update". Normally, one would set up something like what you're describing with the following syntax.
<code> // Before Update:
 if(trigger.isBefore == true && trigger.isUpdate == true){

    // do something here

 } // end Before Update code section

 // After Update:
 if(trigger.isAfter == true && trigger.isUpdate == true){

    // do something here

 } // end After Update code section
</code>
I'm guessing from your description that you'd want to set up your trigger as an "AfterUpdate", but you've not provided enough information to really say. A BeforeUpdate trigger fires any time you're preparing to make an update to the record. This occurs before its been saved to the database and does not trigger workflow. An AfterUpdate trigger would cause your approval process code to execute every time an update to an existing record is saved to the database, regardless of whether any changes were made to your opportunity.
Answer: I'm not sure if you really need the trigger here. The platform already has these built in. You can create a criteria based workflow that will get kicked off and create the process for you:
http://www.salesforce.com/_app/video/workflow/help/create_workflow_rule.jsp
Comment: Agree with Brent, seem very little reason not to use Approval rules and possibly Process Builder to guide the entry into the process.

Approval Process Entry Criteria


how to convert content in the pages and post in wordpress to word format

Question: How to convert content in the pages and post in wordpress to word document(docx)? Used aspose doc exporter plugin but it is "untested with your version of wordpress"! is there any solution for this problem??
Answer: It works fine and I am sure it will be helpful for you
https://wordpress.org/plugins/woocommerce-pdf-print/
Answer: Use this plugin, "Aspose Importer & Exporter" plugin, it works fine.It convert content in the page and post to doc format or pdf format as per the requirement


Can the conceptual metaphor be approached syntactically?

Question: I am really interested in studying how syntax is connected to cognition. I would like to see if the conceptual nature of metaphor can also be approached syntactically. But I don't know where to start. Could you maybe name some resources (academic papers), or provide any type of guidance?
Comment: Probably syntax is not the appropriate model; syntax is for representing linear temporal events like speech. Metaphor is a matter of framing and lexical selection in appropriate pragmatic contexts. For instance, [the _`Time` Is `Money`_ metaphor theme](http://www.umich.edu/~jlawler/TIM.pdf).
Answer: Lakoff and Johnson discuss possible relationships between metaphor and syntax in their 1980 book Metaphors We Live By. Their focus is mostly on understanding syntax through the framework of metaphor, rather than the other way around, and some of their examples have been disproven rather thoroughly (like the claim that WITH-accompaniment and WITH-instrument are always the same in every language), but it's still a decent starting point.
Comment: Thank you for your answer. Do you think the association of syntax with the conceptual metaphor would be a good research paper topic?
Comment: Sure. Look at the metaphors in Relational (aka Arc Pair) Grammar, in contrast to the ones in MITis theories. One uses economic terms (promote, demote, _en chômage_) and the other uses social ones (daughter, sister, head, parent, command, dominate). For instance.


Thawing haggis safely

Question: I have a large frozen haggis that I'd like to use for dinner Saturday night.  when do i start to thaw it, and whats the safest method of thawing to prevent both food borne illness and to preserve quality of the product?  I already read the question about cooking haggis from frozen, and decided I don't want to do that.
Comment: As Elendil says, it doesn't matter that it's haggis. There is no need to repeat the same instructions for every possible frozen food. Also see http://cooking.stackexchange.com/tags/food-safety/info for a roundup on foood safety.
Answer: Defrosting haggis is no different to defrosting any other perishable food. It shouldn't be at room temperature for more than 2 hours. That means:

Defrosting in the fridge for 24 hours
Defrosting by running it under cold water for no more than 2 hours, then cooking it straight away.

There really is no problem with cooking haggis from frozen (or after partially defrosting), so long as you ensure it's piping hot throughout when you take it out of the oven. Use a probe thermometer if possible to ensure a safe temperature (75°C is a safe bet).

Thawing haggis safely


Find only relevant points in MATLAB

Question: I have a MATLAB function that finds charateristic points in a sample. Unfortunatley it only works about 90% of the time. But when I know at which places in the sample I am supposed to look I can increase this to almost 100%. So I would like to know if there is a function in MATLAB that would allow me to find the range where most of my results are, so I can then recalculate my characteristic points. I have a vector which stores all the results and the right results should lie inside a range of 3% between -24.000 to 24.000. Wheras wrong results are always lower than the correct range. Unfortunatley my background in statistics is very rusty so I am not sure how this would be called.
Can somebody give me a hint what I would be looking for? Is there a function build into MATLAB that would give me the smallest possible range where e.g. 90% of the results lie.
EDIT: I am sorry if I didn't make my question clear. Everything in my vector can only range between -24.000 and 24.000. About 90% of my results will be in a range which spans approximately 1.44 ([24-(-24)]*3% = 1.44). These are very likely to be the correct results. The remaining 10% are outside of that range and always lower (why I am not sure taking then mean value is a good idea). These 10% are false and result from blips in my input data. To find the remaining 10% I want to repeat my calculations, but now I only want to check the small range.
So, my goal is to identify where my correct range lies. Delete the values I have found outside of that range. And then recalculate my values, not on a range between -24.000 and 24.000, but rather on a the small range where I already found 90% of my values.
Comment: I'm not sure I understand... are you saying that you specifically want to find points in your vector that are between -24 and 24, ignoring anything outside that range? Or are you looking for a general approach that picks a range that captures 90% of the points?
Answer: The relevant points you're looking for are the percentiles:
% generate sample data
data = [randn(900,1) ; randn(50,1)*3 + 5; ; randn(50,1)*3 - 5];
subplot(121), hist(data)
subplot(122), boxplot(data)

% find 5th, 95th percentiles (range that contains 90% of the data)
limits = prctile(data, [5 95])

% find data in that range
reducedData = data(limits(1) < data & data < limits(2));

Other approachs exist to detect outliers, such as the IQR outlier test and the three standard deviation rule, among many others:
%% three standard deviation rule
z = 3;
bounds = z * std(data)
reducedData = data( abs(data-mean(data)) < bounds );

and
%% IQR outlier test
Q = prctile(data, [25 75]);
IQ = Q(2)-Q(1);
%a = 1.5;   % mild outlier
a = 3.0;    % extreme outlier
bounds = [Q(1)-a*IQ , Q(2)+a*IQ]
reducedData = data(bounds(1) < data & data < bounds(2));

BTW if you want to get the z value (|X|<z) that corresponds to 90% area under the curve, use:
area = 0.9;                 % two-tailed probability
z = norminv(1-(1-area)/2)

Answer: Maybe you should try mean value (in matlab: mean) and standard deviation (in matlab: std)?
What is the statistic distribution of your data?
See also this wiki page, section "Interpretation and application".
In general for almost every distribution, very useful Chebyshev's inequalities take place.
In most of the cases this should work:
meanval = mean(data)
stDev = std(data)

and probably the most (75%) of your values will be placed in range:
<meanVal - 2*stDev, meanVal + 2*stDev>

Comment: Typo, that should be 95% of the values should be in the + or - 2*stDev range, assuming it's normally distributed data...
Comment: Yes, you are right. But I'm not assuming it is normally distributed. Chebyshev's equalities take place in general case, and there is 75% for 2*stDev
Comment: Thanks for your answer. I added a little bit to my post to make it clearer. Maybe your approach is sufficient. Unfortunately I won't have time to work on this today anymore.
Comment: And after the edit, what I wrote still takes place. Play with it, I'm sure it would work for you
Answer: it seems like maybe you want to find the number x in [-24,24] that maximizes the number of sample points in [x,x+1.44]; probably the fastest way to do this involves a sort of the sample points, which is ultimately nlog(n) time; a cheesy approximation would be as follows:
brkpoints = linspace(-24,24-1.44,n_brkpoints); %choose n_brkpoints big, but < # of sample points?
n_count = histc(data,[brkpoints,inf]); %count # data points between breakpoints;
accbins = 1.44 / (brkpoints(2) - brkpoints(1); %# of bins to accumulate;
cscount = cumsum(n_count); %half of the boxcar sum computation;
boxsum  = cscount - [zeros(accbins,1);cscount(1:end-accbins)]; %2nd half;
[dum,maxi] = max(boxsum); %which interval has the maximal # counts?
lorange = brkpoints(maxi);   %the lower range;
hirange = lorange + 1.44

this solution does fudge some of the corner case stuff about the bottom and top bin, etc.
note that if you're going to go by the Chebyshev inequality route, Petunin's Inequality is probably applicable, and will give a slight boost.

Find only relevant points in MATLAB


How do I simulate a low bandwidth, high latency environment?

Question: I need to simulate a low bandwidth, high latency connection to a server in order to emulate the conditions of a VPN at a remote site. The bandwidth and latency should be tweakable so I can discover the best combination in order to run our software package.
Comment: Great question! I'd love to hear some answers related to ASP .NET web development.
Comment: Related/dupe: [Network tools that simulate slow network connection](http://stackoverflow.com/q/1094760) & [Simulate delayed and dropped packets on Linux](http://stackoverflow.com/q/614795)
Answer: For macOS, there is the Network Link Conditioner that simulates configurable bandwidth, latency, and packet loss. It is contained in the Additional Tools for Xcode package.
Comment: The "Network Link Conditioner" preference pane is part of the Hardware IO Tools for XCode, which you can download from https://developer.apple.com/downloads/
Comment: Download link for newer XCode versions: https://developer.apple.com/download/more/?q=Additional%20Tools
Comment: doesn't seem to work with Genymotion. (Black Screen)
Comment: @jstorm31 Thank you. I've updated the answer with the current name of the package and current link.
Answer: There's an excellent writeup of setting up a FreeBSD machine to do just this - take your standard old desktop, toss in an additional NIC, and build.
The writeup is available at http://www.freebsd.org/doc/en/articles/filtering-bridges/article.html.
In step 5 of the above instructions, you're enabling a firewall. For just simulating a different IP connection, you could (for example) do the following:
Create a file /etc/rc.firewall.56k which contains the following:
ipfw add pipe 1 ip from any to any out
ipfw add pipe 2 ip from any to any in
ipfw pipe 1 config bw 56Kbit/s
ipfw pipe 2 config bw 56Kbit/s

And change /etc/rc.conf... replace the line
firewall_type="open"

with
firewall_type="/etc/rc.firewall.56k"

reboot, and you've got yourself a 56K bridge!
If you happen to be working from a Macintosh, that OS has ipfw built into it by default. I've done the same thing by routing network traffic over the Airport and through the ethernet, setting it up so that anything coming over the airport has the same characteristics as whatever I'm trying to emulate. You can invoke the ipfw commands directly from the terminal and get the same effects.
Answer: In the past, I have used a bridge using the Linux Netem (Network Emulation) functionality.  It is highly configurable -- allowing the introduction of delays (the first example is for a WAN), packet loss, corruption, etc.
I'm noting that Netem worked very well for my applications, but I also ended up using WANem several times. The provided bootable ISO (and virtual appliance images) made it quite handy.
Comment: Note: MasterShaper now points to some unrelated landing page
Comment: Perfect for my needs, and available out of the box on my Ubuntu 14.04 server!
Answer: I found this little neat program for Windows called clumsy. It's in kind of alpha status, but it seem to work fine for me, and it's open source.
Edit: Others have noticed that you can't limit bandwidth with clumsy, and that's true. You can only add Latency and a couple of other network related errors.
This will disqualify this answer as a valid answer to the question, however since I had good use for it when I wanted to simulate a bad network so I'll leave it here as long as it has > 0 votes or similar.
Comment: Excellent program. Just what I needed. I Recommend it. Works like a charm and its super easy.
Comment: When most people say "limit bandwidth" they are probably more than happy with simply adding massive amounts of latency and packet loss, as these effectively do limit bandwidth. Also this program is amazingly simple to use, beats everything else I tried on windows.
Comment: How do you control bandwidth with clumsy?
Comment: Clumsy 0.3 supports explicit bandwidth restriction.
Answer: Charles
I came across Charles the web debugging proxy application and had great success in emulating network latency. It works on Windows, Mac, and Linux.

Bandwidth throttle / Bandwidth simulator
Charles can be used to adjust the bandwidth and latency of your Internet connection. This enables you to simulate modem conditions using your high-speed connection.
The bandwidth may be throttled to any arbitrary bytes per second. This enables any connection speed to be simulated.
The latency may also be set to any arbitrary number of milliseconds. The latency delay simulates the latency experienced on slower connections, that is the delay between making a request and the request being received at the other end.

DummyNet
You could also use vmware to run BSD or Linux and try this article (DummyNet) or this one.
Comment: Hi Brad. Can you mention what kind of problems did you have?
Comment: Charles is an HTTP proxy, and therefore only suitable for testing HTTP applications.  To each their own, but in my opinion it's probably some of the worst software I've ever used.  I only used it for a short time while I had to work on a Mac.  For Windows users, I'd recommend Fiddler if you need an HTTP debugging proxy.  Unfortunately, I didn't find anything other than Charles for OSX.
Answer: Try WANem

WANem is a Wide Area Network Emulator, meant to provide a real experience of a Wide Area Network/Internet, during application development / testing over a LAN environment.
Comment: I've tried this and cannot seem to get it to work.  It won't get an IP address from our network for some reason while any other computer has no issues with it.
Answer: For Windows you can use this application: http://www.softperfect.com/products/connectionemulator/
WAN Connection Emulator for Windows 2000, XP, 2003, Vista, Seven and 2008.
Perhaps the only one available for Windows.
Answer: I would try using netem on linux.  With it you can simulate additional delay, corruption, packet loss and duplication.  It even works on the loopback device.
Comment: Hey do you have some equivalent command for windows as netem?
Answer: Another client-side program (Windows only), is NetLimiter - http://www.netlimiter.com
Comment: Even the current beta (NetLimiter 4) does not let you change the latency.
Comment: Netlimiter is good, but I think it only does low bandwidth - it can't change the latency?
Comment: The beta plans for v3 listed latency simulation as a planned feature. It  was recently released and I haven't used it yet to see if that feature made it in.
Comment: That feature did not make it in to beta version 9. Ugh.
Answer: I use NetBalancer on my Windows machine.
http://seriousbit.com/netbalancer/
Updates on 2017-10-07:  The last free version of NetBalancer is 9.2.7.  The program has a hard-coded expiration date.  Before you start the NetBalancer service, you need to turn back the system clock before 2016-10-18.  See this article for details.
Comment: Thank you!! NetBalancer is the only tool listed on this page that I was able to get to work and that can control latency.
Answer: Found this one for Windows using Fiddler (free solution)
http://www.logic-worx.com/index.php/tools-and-apps/fiddler-connection-simulator/
Comment: Fiddler itself has an option: `Rules -> Performance -> Simulate Modem Speeds`, if you don't want to use a separate plugin.
Answer: I guess tc could do the job on UNIX based platform.
tc is used to configure Traffic Control in the  Linux  kernel
http://lartc.org/manpages/tc.txt
Answer: To simulate a low bandwidth connection for testing web sites use Google Chrome, you can go to the Network Tab in F12 Tools and select a bandwidth level to simulate or create custom bandwidth to simulate.
Comment: Thanks! If you can't find it, it's in the Chrome console, Network tab, at the right side of "Disable cache" button. It's default value is "No throttling".
Answer: If you're on linux, I find the Traffic Control program to be a great help for this sort of thing.
Answer: There is a product from http://www.shunra.com called VE Desktop which can be used to simulate varying network conditions. It allows you to tweak latencies, bandwidth and packetloss with a simple UI. Only caveat is, its not free. Hope this helps.
Answer: I've been looking for an easy to use tool for this type of testing for a while now.  I just came across this the other day:  Network Delay Simulator
If you're running Windows, you should check it out.  It was super easy to set up and get going, and seems to work really well.  It allows you to define bandwidth, latency, and packet loss in each direction.  The other really nice thing is that you can define "Flow Match Conditions" so that it only affects the traffic you want it to.  Oh yeah, and it's free.
Comment: Link does not work.
Answer: i think i found what i need. maybe you can use charles proxy or slowy. hope it helps.
Answer: Take a look at the NE-ONE Network Emulator which allows you to configure bandwidth, latency, packet loss, packet reordering, packet duplication, packet fragmentation, network congestion and many more impairments so that you can create real-world network conditions in the lab.  Different impairments can be configured for the up and downlink so you could have a really good uplink but a really bad downlink experience, great for seeing how the app handles TCP queuing because the acks don't come back in a timely manner and the overall latency therefore increases!
There's an overview video here http://www.youtube.com/watch?v=DwtqlE7LcrQ specifically aimed at game developers, but it shows what it's about.  NE-ONE is configured using a web browser so it's really easy to get installed and configured - you don't need to be a network guru :-)
There's a hardware version - http://www.itrinegy.com/index.php/products/network-emulators/ne-one - or you can download a Virtual Appliance (software) version that runs under VMware ESXi Server.  The Virtual Appliance can be download from VMware's Solution Exchange - solutionexchange.vmware.com/store/products/ne-one-flex-network-emulator
Answer: LANforge ICE is a network emulator  with an emphasis on virtual routing, jitter, corruption and delay. Projects have used it to emulate satellite link, cable and modem connections, and high-speed (10Gbit) wan emulation. You can use a Java GUI to build your virtual networks and generate very detailed reports of the traffic flow. The LANforge products also provide traffic generation features: frame, ethernet, layer-3 and stateful traffic (NFS, http). Recent editions for LANforge have sophisticated WiFi testing features as well.
Answer: You can try this: CovenantSQL/GNTE
just write YAML like this:
group:
  -
    name: china
    nodes:
      -
        ip: 10.250.1.2
        cmd: "cd /scripts && ./YourBin args"
      -
        ip: 10.250.1.3
        cmd: "cd /scripts && ./YourBin args"
    delay: "100ms 10ms 30%"
    loss: "1% 10%"
  -
    name: us
    nodes:
      -
        ip: 10.250.2.2
        cmd: "cd /scripts && ./YourBin args"
      -
        ip: 10.250.2.3
        cmd: "cd /scripts && ./YourBin args"
    delay: "1000ms 10ms 30%"
    loss: "1% 10%"

network:
  -
    groups:
      - china
      - us
    delay: "200ms 10ms 1%"
    corrupt: "0.2%"
    rate: "10mbit"

run ./generate scripts/your.yaml


Sharepoint 2013 BCS Connectivity

Question: I have created a BCS Service but as I am clicking on it, this is giving me error..
please tell me what is the problem and how to trace it.
Comment: Can you please add the error message as plain text, it is hard to tell what it says from your image
Answer: Please make sure the service is started:

Go to Central Administration -->  Application Management --> Under Service Applications
  Click Manage services on server. Start Business Data Connectivity service.

Source
Comment: Thanks Robert :) but in "Application Management -> Manage Service Application" it was already "Start". Then what was that "Start" for. as it is in my given Image on thread.
Comment: Most services in SharePoint are constructed of two parts (the service application is one part, and a web service is the other).The service can be started but at the same time the web service can be stopped. But the service application do need the web service to function, so you have to start the web service as well

Sharepoint 2013 BCS Connectivity


Book with solved examples and exercise problems for SUSY

Question: I am learning supersymmetry right now. I am mostly following Bailin and Love. I try to connect all the steps from the book and complete the derivations in order to get comfortable with the calculations but I feel the lack of a problem book with a lot of solved and unsolved problems, something like the Schaum's series which I can use together with Bailin and Love. Do you happen to know any such book that you think would be helpful for me?
Comment: Hi, thanks for the response. I browsed through the paper that you suggested. Although it is very interesting, what I am looking for is slightly different. I am searching for something which has solved and unsolved problems on supersymmetric gauge field theories, spontaneous supersymmetry breaking, supergravity and so on. Thanks again.
Comment: Probably not what you're referring to (also I'm not familiar with the texts you mention), but if you're looking for exercises in the supersymmetric method in quantum mechanics (see section 2 of http://arxiv.org/abs/hep-th/9405029) some classic examples are finding the super-partner potentials to the infinite square well and hydrogen, and use the formalism of the supersymmetric method to solve for their spectra and associated eigenstates.
Comment: Ah I see. That's way beyond me at the moment. I'm a second year undergraduate and I just wrote a research paper for a quantum class I'm taking about the supersymmetric method described in section 2 of that paper. Good luck with your study of field theory!
Comment: Saved comment from @[AnarchistBirdsWorshipFungus](http://physics.stackexchange.com/users/27384/anarchist-birds-worship-fungus): Course on [SUSY with exercises and solutions](http://bolvan.ph.utexas.edu/~vadim/Classes/2009f/396T.html) posted online. God tier material.
Answer: Supergravity by Daniel Z Freedman and Antoine Van Proeyen is quite excellent for illustrating Clifford algebra techniques and calculations in the classical SUSY/SUGRA in general(in the component formalism). The book has several calculations illustrated and plenty of exercises.
Answer: Not a problem book, but Supersymmetry: an Introduction with Conceptual and Calculational Details by M\"uller-Kirsten and Wiedemann may be helpful. From the preface:

"The text was compiled with the belief that the
  majority of potential readers is more interested in actually using or applying supersymrnetry in some model theory
  than in painstakingly rediscovering the results of others
  for themselves, It seemed plausible, therefore, to revise
  various relevant concepts and in particular, to include
  the proof or verification of almost every formula. In this
  way the reader can select the problems he wants to tackle
  himself, compare his solutions with the calculations given
  here, and thus gain the confidence in his own calculations
  which he needs for his discussions of supersymmetry in
  other contexts."

Citation information here: https://inspirehep.net/record/18778?ln=en
Answer: A valuable book on line from Jürgen Reuter with exercises on subjects as diverse as :

SUSY Field Theory
Symmetry and Algebra
Superfields and Superspace
Supersymmetric Lagrangians
SUSY Gauge Theories
SUSY breaking
The Minimal Supersymmetric SM (MSSM)
Gauge Coupling Unification
The MSSM Higgs sector
The Sfermions
Charginos, Neutralinos, Gluino
Models for SUSY-breaking communication
SUSY Phenomenology
MSSM Higgs searches
SUSY at colliders – Sparticle searches
SUSY Simulations
Electroweak precision observables
Muon anomalous magnetic moment
MSSM Dark matter
Answer: Course on SUSY with exercises and solutions posted online. God tier material.
Comment: This is a link-only answer, which is generally frowned on [>:( ] <-- See? It's frowned on. Consider adding a summary to accompany the link in case it gets dead and renders your answer useless
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/142705)
Comment: @heather jim  I do understand that for a question which has an answer that is found in a link, posting the link is not correct since the whole point of the site is to provide answers here, not to give links with the answers. However, OP does not post a question, he wants a reference. You say "include the essential parts" am I supposed to copy all solved exercises and solutions on the link which are dozens of pages?
Comment: @AnarchistBirdsWorshipFungus, see the answer to [this meta question](http://meta.physics.stackexchange.com/questions/4697/are-resource-recommendations-allowed) for information about this. Provide details about your resource, etc. The banner right below this question details this as well: "Please write substantial answers that detail the style, content, and prerequisites of the book, paper or other resource. Explain the nature of the resource so that readers can decide which one is best suited for them rather than relying on the opinions of others."


How can my audio input always be the webcam microphone?

Question: Each time I want to use Skype, I have to go in the sound preferences. And there, turn the audio-in to "webcam" and uncheck the "mute" button. It's quite annoying. Is there a way to always keep the same configuration ?
Comment: I have this problem as well with a logitech quickacam.  After every reboot I have to go through the preferences and reset it as the default input in order for it to work.  I think it has something to do with the fact that usb devices are loaded after sound preferences are set so pulse or alsa don't "see" the usb mic.  Unfortunately because the "problem" isn't really a problem just an inconvenience it's not so important that I want to roll up the shirt sleeves and start digging and editing through config files.
Answer: Changing default settings for PulseAudio
When running pulseaudio all settings can be defined by putting custom configuration files in the hidden .pulse directory in your HOME. If these file do not yet exist there you can use the standard files from /etc/pulse/ as a template. Most entries have verbous explanations in these files.

~/.pulse/default.pa to load modules and define defaults
~/.pulse/client.conf to configure a client for the sound server
~/.pulse/daemon.conf to define sample rates and buffers

To make your webcam the default source we need to know this source's name and number by looking through the list produced by the following command in a terminal:
pacmd list-sources

We then edit the following line in ~/.pulse/default.pa:
set-default-source [name]

and replace [name] by the name or the source number for the desired source. We then need to make sure that the source is unmuted by adding this line:
set-source-mute [name]|[#n]> 0

Give the name or the index of your source. You can add a variety of other settings that are referenced in the PulseAudio Wiki (now on man page: man pulse-cli-syntax).
It is recommended to first test all commands through the command line interface before changing the configuration files. This can be opened with pacmd in a terminal
Comment: @ToDo the default settings are in `/etc/pulse/default.pa`. Use this file or copy it to `~/.pulse` before editing.
Comment: There's no default.pa in my .pulse folder. Should I create a new file with one line: set-default-source x ?
Comment: For the sake of completeness: one have to write as an input device name the thing that is written inside of angle braces of output of `pacmd list-sources`. I.e. with for my device it was `set-default-source alsa_input.usb-0d8c_USB_PnP_Sound_Device-00-Device.analog-mon`.
Comment: @Hi-Angel: thank you for that - the answer came from a much older version of pulseaudio. We can now use the proper name of a sink.
Answer: I agree that the problem is that Pulseaudio does not set a USB device as default because it is not present when pulse starts.
Soo my solution to this is to hook into the system that does notice when a USB device is connected... UDEV!
BTW, these instructions are slightly funky, and I am assuming that you are comfortable doing stuff at the command line, and becoming the root user to update udev files, and making scripts executable.
First, find out stuff
USB Id
First step is to plug in your webcam and find the magic vendor and product numbers by typing
lsusb

I'm using a Microsoft Lifecam, and it show as
Bus 001 Device 013: ID 045e:072d Microsoft Corp.

the important part is 045e:072d
Pulseaudio device
Next, while the webcam is connected, find out the pulseaudio device name. Type
pacmd list-sources

Again, I'm looking for the line that starts name: then has something about a Microsoft Lifecam... here it is
name: <alsa_input.usb-Microsoft_Microsoft___LifeCam_VX-5500-02-VX5500.analog-mono>

so my pulseaudio device name will be alsa_input.usb-Microsoft_Microsoft___LifeCam_VX-5500-02-VX5500.analog-mono
UDEV rules
Then I made a new udev rule which is fired when a USB device with vendor=045e and product=072d is inserted. To make a rule, create a new file called /etc/udev/rules.d/SOMETHING.rules (I called my file /etc/udev/rules.d/95-webcam-mic.rules).
Put this line into the file
SUBSYSTEMS=="usb", ATTR{idVendor}=="045e", ATTR{idProduct}=="072d", ACTION=="add", GROUP="audio", RUN+="/usr/local/bin/webcam-mic"

Remember to replace the ATTR{idVendor} and ATTR{idProduct} with the values for your webcam.
What this rule does is run a script to set the usb device for input, that is the RUN+="/usr/local/bin/webcam-mic" part.
Finally, set the webcam for input
Quick overview time. Each time I connect my webcam I want to run the command
pacmd set-default-source alsa_input.usb-Microsoft_Microsoft___LifeCam_VX-5500-02-VX5500.analog-mono

But the command needs to run as me (the user running the desktop), but udev runs as the root user - so when udev runs my command I need it to change to my user then run the command.
So we have 2 options.

Quick and dirty. Make the udev rule run su james -c pacmd set-default-source...
this is sooo wrong I can't even finish typing the command. What if you change webcams? What if you install this for another user?
Slightly cleaner. Run a script that reads a defaults file which has the pulseaudio device name, and your username in it. If you want the files they are on GitHub. First the script  /usr/local/bin/webcam-mic. The defaults file /etc/default/webcam-mic just needs to define the 2 shell variables, as per the comment in the gist.
Put the script into /usr/local/bin/ and make it executable. Then put the defaults file into /etc/defaults/ and edit it to use your username and the pulseaudio device from earlier.

Good luck!
Comment: Any chance you could upload those scripts again; they appear to have disappeared from pastebin?
Comment: I have put the script into a gist on GitHub, and updated the answer.
Answer: The solution by Takkat was not working for me, here is my solution for anyone still having a problem with this.
There were two issues for me with the solution by Takkat. First, I realised that there needs to be a delay after startup before the switch to the microphone can take place (I use the command 'sleep' in my solution below). Also, the command 'set-default-source' was working to switch the USB microphone on, but somehow Skype was not recognising this and continued to use the internal microphone.
For this to work, first it is useful to install pavucontrol. In pavucontrol, open the 'Configuration' tab, and observe what happens with the commands below to check things are working as intended.
Then, from a terminal enter:
pacmd

From there, enter:
list-cards

In the output, find the index number of the USB audio you want (in my case, this was '1'). Then have a look at the lines listed under 'profiles' for both the default card and USB card. These should be the same as the ones listed in pavucontrol, and can be something like 'ouput:input+output', 'off', or 'input:analog-mono' etc. Still in the pacmd command line, the command set-card-profile <index number> <profile name> should change the settings in pavucontrol. What we want to do here is to switch the internal audio from duplex to output only, and the USB to input.
Once found the appropriate profiles, we want to create a startup command to change a few settings just after startup. To create a startup command, open the dash and search for 'startup applications', then click 'add', then enter a name of your choice and the appropriate command below.
After trial and error, my start up command ended up looking like this:
bash -c "sleep 30 && pacmd set-card-profile 0 output:analog-stereo && pacmd set-card-profile 1 off && pacmd set-card-profile 1 input:analog-mono"

Explanation: I found that the command 'sleep' was necessary, this means that the command is executed after a pause,  that I set to 30 seconds (I think this can be less, play around with this). The next command (after the '&&') is to get the default (internal) card profile to switch from input+output (duplex, which is the default) to output only. The next command is for the USB sound card (in my case, the number is '1') to switch off. The last command is for this same card to switch back on in the mode 'input:analog-mono'
You might have to play around with these settings, to find the one that works.
Now when I startup, my USB microphone is ready to use after 30 seconds, and Skype uses the correct microphone.
Answer: try this, click on the speaker icon on your top panel, the click preferences. there you can select a default input option for you microphone and probably change some hardware config to make it work ok.
Comment: Thank you for your help, but that's what I'm doing right now. However, I don't see any ways to make this a default setting. Every now and then, I'll have to do it again because the setting would have changed.


How to turn webpages into pdf?

Question: I mean saving them as a pdf and keep them as a backup for future reference or for future reading
Answer: You could install CutePDF printer driver, and print the pages you want to PDF files.
Alternatively, there exist quite some tools to download and store full websites.
Comment: similar method: print to file using a PostScript printer driver, then convert the resulting file with `ps2pdf`.  this was handy way-back-when when PDF printer drivers only came from Adobe but Microsoft provided a great postscript driver for Apple Laserwriters for free.  :)
Answer: From sourceforge:

http://sourceforge.net/projects/pdfcreator/

In case you are using firefox browser, this addin is a good one:

https://addons.mozilla.org/en-US/firefox/addon/5971?src=api
Answer: There are online converters such as:
web2pdf.co.uk
Comment: This website has been removed.
Answer: This is my favourite - converts everything (documents, websites, emails etc)
http://www.freepdfconvert.com/
Answer: I have used wkhtmltopdf to convert a webpage to PDF in the past.
Answer: If you'd like to save web pages for future reference or future reading I find best to use the Scrapbook Addon in Firefox or save the webpage as .mht file (native in IE, possible in Firefox using UnMHT Addon).
These methods will save your page with more accuracy than printing them to pdf.
I hope it helps.
Answer: HTML-to-PDF is a free utility for batch converting webpages to PDF documents from the command line or via a GUI...
See: http://sourceforge.net/projects/html-to-pdf/
It produces HTML and CSS rendering pretty much identical to that of Internet Explorer. Handles pages containing JavaScript, embeds fonts, and allows you to insert live links and live forms into a PDF document.

How to turn webpages into pdf?


How did the nano bots stopped creating electricity?

Question: After the nano bots were released, then it leads end of the electricity age, how did that happened, scientifically ?
Comment: It did not happen scientifically at all, revolution was decent but really required the MST3K mantra.
Answer: While there's a good deal of hand waving, the general idea was that they simply used the electricity themselves.  That is to say, the nanobots consumed electricity, and they replicated enough that the population of nanobots was able to constantly absorb and use all the electricity being produced.
I realize this opens a lot of questions around how the nanobots kept themselves going once all the power was gone,but that's how the show explained it. I'll look for a transcript later.