Lost my Home CSM home page

Question: I have a Sahara theme installed and wanted to change the browser tab name to my site name. It was called as per theme "Sahara Home Page".
I changed the title but I thought it was OK to change the URL key as well. Wrong!
Now I don't see my feature products and other modules which are part of the theme. It now says "No Home CMS page configured or found".
Now I don't recall the set url key and I have no idea where to find it.
The fields in the picture are what I believe it was as default however I don't see it restored. Even when I change the title it now stays with my shop name even after re-index, cache re-flush etc. I'm such a Rookie! but hope you can help me. ;-) screen shot of CMS page
Answer: Make sure you have selected the homepage in the System > Configuration > Web tab as well. The name and URL shouldn't make a difference to call the homepage from the base url

Lost my Home CSM home page


Does the Japanese word "akasuki" means "bright improvement" in English?

Question: We are an outgoing college students, we've decided to choose a Japanese name for our class. We want it to be meaningful, it should represent our ambitions to grow and further improve ourselves. We also want it to be applicable in business, our seniors chose the word "Kaizen" as their class name, we want to have something as meaningful as well. However, when I searched online, 'akasuki' means 'I like red' which is different from what we initially thought.
Answer: Akasuki is not a Japanese word. It might be analyzed as a sentence, Aka, suki ("Red, (I) like"), but of course it's not suitable as a name.
There is a word akatsuki (あかつき in hiragana, 暁 in kanji), meaning "dawn". This may be the word you are looking for, and it's a nice word suitable for names. But it's not a word that means something complicated like "bright improvement".
By the way, kaizen is a prosaic word that simply means "improvement" in Japanese. Japanese Wikipedia does not have an article for it because it's just a word with no significant meaning worth notable in an encyclopedia. If it has a special meaning in English, it may be called an 英製和語.


Error while trying to uninstall Adobe Photoshop CS6

Question: I am trying to uninstall Adobe Photoshop CS6 on my laptop (Windows 7 home premium) but it comes up with an error saying: "DW039: Failed to load deployment file". I have CS6 cd and tried to install it but it says you need to uninstall previously installed version before you can continue. Can anybody please suggest how should I go about this.
Answer: Download the Adobe Creative Suite Cleaner Tool, extract, right-click and Run as Administrator.


Is there any reason I shouldn't use SHA1 of salt + website name + master password for my password in websites?

Question: I considered writing a program to do the above for websites I only intend to use for short-term use.
Comment: Crazy steve again.
Comment: Yeah, don't do this. Not only a waste of time, its not going to help when you don't have access to the program.
Comment: Well, the point was that I would be able to remember that and implement it easily if I lost the program.
Answer: Yes, there's a very good reason, it's called KeePass. It's a free and open source password management application. It can automatically generate a rock-solid password for you, pair it to certain website, and store it in a securely encrypted database for which you have the key in a form of a master password.
Other than for learning purposes, don't play a crypto pro and write your own security-related programs.
Comment: @user29349 Oh no, I'm perfectly aware of the reason. If you write it yourself for actual usage, you **will** do something wrong. It's insecure and a waste of time. Honestly, others have given better answers when it comes to deeper explanations. I'm more interested in giving you and future visitors of this question a better solution next to a quick explanation.
Comment: I think "I don't know, but use someone else's program" is kind of a non-answer.
Answer: If the webmaster of any site you visit knows the algorithm above, it becomes possible for them to mount a brute force attack on your master password from the generated password. So for this to be a viable scheme the master password would probably have to be a long string of randomness (which would probably defeat the purpose of the scheme), or the device generating the passwords would have to have a long random key that was unlocked by the master password.
It is unclear how the "salt" fits in this - if it is random, how do you know what salt to use for a particular site? If it isn't (ie it is a fixed secret), how does it differ from the master password in nature?
If you have random salt and you are storing it on the generating device, you might as well be generating the whole password randomly and storing it protected on the device (like Keepass et al). As a practical matter this has an advantage that you have a record of all the site names you have keys for. Without that, it becomes difficult to remember what the canonical name for a site is. For example are you going to refer to this site as "IT Security Stack Exchange", "Security StackExchange", "Security", "security.stackexchange.com", "www.security.stackexchange.com", or "user29349.openidprovider.com"...?
Comment: It is true that the slat has no difference in nature to the master password. On the canonical name I intend to use the first level above the TLD + extension. I think the likelihood a web-master realises I am using this is low enough to make this viable.
Comment: Either way, I wanted to use this on websites that have "no special characters" restrictions.
Answer: There are several good reasons not to do that:

A single SHA-1 instance is too fast; when deriving things from passwords you want to apply proper password hashing. The salt is a good thing, but it is only part of the equation.
Cryptographic algorithms should not be improvised; there are many ways to botch it. Reuse an existing password hashing algorithm which has been published and analysed and which resisted attacks for some years.
If you want to change your master password you lose all your site passwords. If you want to change one site password you have to change your master password. This is inadequate. For that, you need an indirection layer; say, the master password is used to encrypt a local database of stored per-site passwords (and these per-site passwords can then be completely random, or chosen by the site, or whatever). This is more crypto, so again don't do this at home.
Comment: Are you suggesting the webmaster, looking at my hashed password in his database, would reverse the hash, and then reverse my hash? Is that possible in reasonable time? I'd prefer explanations rather than this flood of 'avoid crypto if at all possible', which attempts to unask the question.
Comment: @user29349 Please note that nobody is telling you to avoid crypto, we're telling you to avoid improvising crypto yourself. We're not being condescending at all, I'm sure that not even Tom Leek (Thomas Pornin, Google him) who is our #1 expert here on crypto matters would write his own crypto and user it in a production environment. As you can see, he has given you very good reasons not to do this, from security point of view and usability point of view.
Comment: I don't consider "websites I only intend to use for short-term " to be a production environment. I asked this question from personal interest and as much and more I care about why than whether.
Comment: @user29349 - I'm not absolutely sure that i understood your question correctly, but keep in mind that today (2013) one can calculate about [3 Giga SHA1 hashes per second](http://hashcat.net/oclhashcat-lite/#performance) with common hardware. That leaves a lot of room for brute-forcing.
Comment: I am entering in the "password" field of a given website a string generated from my existing password + the name of the website.
Comment: Apologies for not reading all of your "how to securely hash passwords" article before, I thought it was shorter than it was, I really appreciate the information.


Is everything between me and my lawyer confidential?

Question: From the law point of view can I tell my lawyer EVERYTHING knowing that he is NOT allowed to disclose anything I tell him including crimes I did in the past or crimes I am planning to commit in the future?
Comment: Short answer: no.  You might want to search for exceptions to the attorney-client privilege.  In the U.S., things like future crimes generally aren't privileged.  If you sue your lawyer for malpractice, confidentiality also gets suspended (so the attorney can make a defense).  The idea behind the privilege is to make sure you feel free to discuss all the details pertinent to the issue at hand (rather than an issue that's not at hand...).
Comment: I know that in the UK if you tell your barrister that you actually committed the crime, the barrister becomes limited in the defense he or she may pursue.
Answer: Firstly, legal professional privilege applies only when information is disclosed for the purpose of obtaining legal advice. Talking about a bad haircut you got last week is probably not protected by legal professional privilege.
Secondly, all privileged communications and documents are confidential and protected. However, there are certain exceptions to legal professional privilege - such information is not privileged, not confidential and may be disclosed.
Finally, there is an exception to legal professional privilege. This is where documents form part of a criminal or fraudulent act, or communications that take place with the intention of carrying out an offence - from the Law Society Chapter on legal professional privilege, 6.4.5. It goes on to enumerate a number of exceptions to legal professional privilege:

Intention of furthering a criminal purpose
If a client (or a third party) intends that the communication is made to further a criminal purpose, it is not privileged.
Knowing a transaction constitutes an offence
If the transaction is an offence, the lawyer also commits an offence - these communications are also not privileged.

In answer to your question - information about past crimes is privileged, however, information provided in order to obtain advice on committing future crimes is not.
Answer: tl;dr: Definitely not.
The UK's concept of legal privilege includes the: a) legal advice privilege, and b) litigation privilege.
This UK vs. US comparison on privilege is a good read.  I'd initially hesitated to include it since it's tailored towards corporate law, however, it might be helpful to two audiences:

Those reading this question from a business/non-profit perspective
Individuals with more complicated circumstances
Those who'd like to see a few good examples that differentiate the UK's legal advice privilege from the litigation privilege

Of course, there are differences, but a rough translation into US terms would equate the legal advice privilege with attorney-client privilege and the litigation privilege with attorney work-product doctrine.  US procedure stems from the Federal Rules of Civil Procedure, Rule 26.
In most cases this latter doctrine shields work prepared by or for an attorney (e.g. an attorney's personal reflections, thoughts on strategy, a consultant's assessment).  It's helpful to have this in mind while reading the comparison.
united-kingdomunited-states


Why doesn't the polar side of the plasma membrane block nonpolar diffusion?

Question: It is often stated that small molecules or nonpolar molecules can diffuse through the plasma membrane because they can pass through the middle nonpolar bit, but why don't the polar sides block these nonpolar molecules. Estrogen is nonpolar and can diffuse across the membrane right? Why don't the polar heads of the phospholipids block it? Or look at H+. H+ can't diffuse across the membrane because it's charged (it's not like nonpolar molecule have a repulsive force against it, neutral objects don't repel charged ones as far as I am aware, I don't get why we say polar and nonpolar repel each other, as I understand they just stick to themselves better than each other). Regardless, H+ a small charged molecule would be able to get past the hydrophilic heads right? Estrogen wouldn't be. Where am I going wrong here?
Thanks!
Comment: You might get the answers you're looking for on the chemistry stackexchange
Answer: Polar and nonpolar molecules don't actually "repel", it's that polar molecules attract each other much more than nonpolar molecules attract anything. Therefore, to take a polar molecule from the (polar) water on one side of the membrane and bury it in the nonpolar region in the middle of the membrane is difficult because it means breaking its relatively strong interactions with the polar water molecules without forming new strong interactions to compensate.
In the case of a nonpolar molecule passing through the membrane, it is already in water when it approaches the membrane, and transferring it past the polar head groups isn't much "worse" (there's likely a slight effect of the often charged head groups attracting ions that bridge them to one another, but this would be small). The large effect of it being nonpolar, however, is to make it less unfavorable to move it into the middle layer of the membrane where there aren't polar groups for it to interact with.


Make inserting image via css after cross browser

Question: I'm currently trying to insert some separator image between li elements of menu via css :after property:
nav ul li:after
{
    content: url('../Content/Images/BorderSeparator.png');
    display: block;
    height: 30px;
    padding:10px 0px 10px 0px;
    overflow: hidden;
}

And this solution works for all latest versions of Chrome, Opera, Safari, except from Firefox.
 How can I fix it for Firefox also?
Update 1:
This is how it supposed to look like

Problem is somehow relate to overflow:hidden, when I remove this attribute FF displays separator, but not in the right place.
Answer: In firefox the overflow and the padding are not compatible try to uncomment padding to verify. try to use instead  left top.


Where's my I Voted hat?

Question: I upvoted an answer on SO Meta today, and according to the description of the I Voted hat, you should get it if you upvote any question or answer (emphasis mine). There's no mention that meta sites are exempt from this. In fact, the short description says upvote anywhere (emphasis mine again). However, I have yet to see that hat.
Comment: Voting should be done on the main site. I voted yesterday and got the hat today
Comment: Well, I just upvoted this and did not get a hat, maybe the description needs updating...
Comment: Meta.SE is not a meta site, it's a main site. Meta sites don't have rep changes, can't have bounties on questions etc.
Comment: I received this hat on Meta Stack Exchange as well, so believe meta sites are counted, too
Comment: Also I noticed a couple of hours passed after actual voting and receiving a hat
Comment: @RafaelTavares OK, didn't know that. Then probably hat description should be updated
Answer: Meta sites are not counted for the purposes of the "I Voted" hat. Your vote needs to be cast on the main site—in this case, Stack Overflow.
What can be somewhat confusing is that Meta Stack Exchange does count, but that's because it's actually a main site, in the sense that it doesn't have a child Meta site associated with it. The hats you earn for actions taken on Meta Stack Exchange are actually awarded and displayed on Meta Stack Exchange.
It's also worth noting a couple of other things here, with regards to this hat:

The vote must be on a post (i.e., question or answer), not a comment. (This is now clarified in the description.)

Yaakov changed the trigger for the hat after the initial deployment so that either an upvote or a downvote on a post is sufficient to earn the hat. (Previously, an upvote was required, which was poorly thought out.)
Comment: In future winter bashes, could the descriptions of those hats that don't count on meta sites be made clear enough that we don't have to keep asking about it? (Maybe add "Cannot be earned on a meta site other than Meta Stack Exchange," or something to that effect to the description?)

Where's my I Voted hat?


Small white spots on rose leaves

Question: My rose leaves have small white spots on a few of the leaves. Since there were more today than the last time I looked, I want to nip this problem in the bud if possible. Any idea what this is? I couldn't see any insects anywhere.
Comment: @Daanil This looks like regrowth from where bugs were eating your rose plant leaves. It would seem the roses have recovered nicely.
Comment: Rob, there are more small white spots every day, and they are spreading to more leaves. But it doesn't look like anything is eating the leaves, as there are no holes but just places where the green is gone. I saw some aphids and sprayed the area with detergent water. I guess I'll keep monitoring and see what happens.
Comment: I suppose it's possible that this is scale, try some Malathion.
Comment: Rob, I looked for signs of scale or other insects and couldn't find any. But the damage is spreading rapidly so for safety's sake I'll get some Malathion tomorrow and try it.
Answer: I have the same thing and it ultimately developed to a point where all the leaves were eaten away.  This may be a problem with rose slugs (sawfly larvae).  One thing I've been trying is heavy doses of Neem Oil spray all over the leaves.  To the point where they are dripping from the oil.

Small white spots on rose leaves


Actions - What are objects and context

Question: Can somebody explain to me what the difference is between an object and context within the advanced action setup please.
I understand what an object is but am failing to understand what context is.
Thanks.
Comment: What is "the advanced action setup"?
Answer: If you are talking about the $context variable (and I think you do), then the official description is: an associative array containing extra information about what triggered the action call, with $context['hook'] giving the name of the hook that resulted in this call to actions_do() (from here:  http://api.drupal.org/api/drupal/includes!actions.inc/function/actions_do/7)
But if you want to understand it better, this page is very useful: http://www.sysarchitects.com/node/47
Answer: The context is used to identify how the action is being triggered so that, if necessary, it can handle the object differently — e.g. an action that has to do different things depending on whether a node is being inserted for the first time or updated.
Answer: Drupal supports a trigger/action system. So you can easily give drupal some object id(s) and say I want these Actions to occur to this object, at some time or context.
Here is a small example from some code I run via drush in a php-eval:
$q = new EntityFieldQuery();
$types_to_publish = array('page');
$q->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', $types_to_publish, 'IN');
$results = $q->execute();
foreach ($results['node'] as $node) {
  $current_node = node_load($node->nid);
  $migrator_user = user_load_by_name('d7migrator_user');
  $current_node->uid = $migrator_user->uid;
  $actions = array('node_publish_action', 'node_save_action');
  $context['node'] = $current_node;
  actions_do($actions, $current_node, $context, NULL, NULL);
}
drupal_set_message('Done publishing content.');

I do this because I'm migrating some node via node_export and then apply the Workbench module and currently need to re-save nodes to that Workbench can properly set the publish state for the given NIDs. We dont need to supply a $context here beyond the node because I'm not hooking into the lifecycle of a page request or form POST processing.

Actions - What are objects and context


Logistic regression on 2 concentric circles

Question: If we have 2 concentric circles of different radius and points on the same circle corresponds to the same data class then can model this problem to be solved by logistic regression. I don't think we can since the data points are not linearly separable.
Answer: In practice, yes, it can.
Let's say the circles are of radius $\frac{1}{\sqrt{2}}$ and $\sqrt{\frac{3}{2}}$, just to make things easier to follow (*).
Then the following functional form works when thresholded to classify the points:
$$ P(y | x_1, x_2) = \frac{1}{1 + \text{exp}(x_1^2 + x_2^2 - 1)} $$
On the circle of radius one half:
$$ P(y | x_1, x_2) = \frac{1}{1 + \text{exp}(x_1^2 + x_2^2 - 1)} = \frac{1}{1 + \text{exp}(-0.5)} > 0.5$$
On the circle of radius three halves
$$ P(y | x_1, x_2) = \frac{1}{1 + \text{exp}(x_1^2 + x_2^2 - 1)} = \frac{1}{1 + \text{exp}(0.5)} < 0.5$$
So if you threshold the probabilistic predictions at $0.5$, you'll classify correctly.
Note that you do need to add some derived features, in this case the squares of the coordinates.   This is very common in practice to deal with these kinds of situations.
(*) Note that this isn't really a restriction, you can always scale your coordinates in a way to map any two concentric circles to this specific situation.
Comment: I think the underlying question is *how would you discover* such a functional form when presented with noisy data generated from the given model?


How do I know if I can replace the 27 inch wheels with 700c wheels on my bike?

Question: I recently purchased an 80's Japanese bike off craigslist called "Jupiter King." It has 27 inch tires but I want to switch to 700c for greater wheel/tire selection. I specifically want some nice yellow wheels with yellow rim. Help? I am quite a noob with bikes. Thanks for any help/advice.
Comment: Yeah, you'd have to get new wheels.  That's $80-150, if you don't get anything fancy.  And then you hope that the brakes will still work.
Answer: You may or may not be able to make that conversion with your existing brake/frame combination. Your brakes will have to reach farther because a 700c wheel is a smidge smaller than a 27 inch wheel. Depending on your setup, that may be possible. I'd recommend borrowing a 700c wheelset from someone to see if you can line it all up. If it all lines up, great. Purchase whatever 700c wheelset strikes your fancy. If not, you may be able to purchase brakes with a longer reach. Some older frames still won't work with 700c wheels even with the longest brakes available. If that's the case for your frame, you're stuck with 27's.
Personally, if it were me and I couldn't get it to work with the existing brakes, I'd stick with 27 inch wheels. If you start having to swap brakes out, it starts to get iffy and frankly, I think it's more hassle than it's worth. It's a lot easier (and maybe cheaper) to just start hunting for a frame that already has 700s on it.
Comment: A possibility that should always be considered, even in a "classic" bike, is to reposition the rear brake "bridge" on the frame via removal and re-brazing/re-welding, or to use some clever (!) adapter. THAT would be extra work... ;o)
Comment: Believe it or not, that was something I considered with a past rebuild. But you can't reposition where the front brake attaches and I was hesitant to jimi-rig an adapter for something crucial like the brakes.
Answer: You will probably need to drop your brake calipers.
I did this on my 1981 Raleigh.  Despite fitting long-reach Tektro R559 calipers, the back wheel looked like this:

There might have been another millimetre by fiddling, but not the difference I needed.
Please ignore the dodgy-looking cracked tyre sidewalls... they where only for testing.
Here's the drop-plate I made from 6mm of scrap aluminium bar.

Fitting that with lots of copper grease and some solid bolts gives this:

Curiously, the same brake on the front reached the wheel rim perfectly without any crafting.
I should have lowered it even more, but this way there's clearance for a mudguard someday.
Answer: The difference between 700C and 27" is pretty small. The rims are 622mm and 630mm so the actual change in brake shoe position is 4mm (less than 1/4"). Look at your brakes and decide whether they will suit. You may be able to change the brakes to ones with longer arms (assuming caliper types).
Another issue may be the rear hub as these have got wider over the years. If it's only a couple of mm you can probably spring the rear forks enough to fit. If it's more than that I would advise you to find a frame builder who can reset the forks.
Answer: I am working on a similar project.  Take a look at this on YouTube:
Comment: In case the link disappears, its often good to note down the main points in writing.
Answer: I would be switching to 700c with disc brakes so obviously would not need to be concerned with O/D. And my Motobecane has plenty of clearance to make the switch.
Comment: Welcome to the site - this sounds like trading one problem for another because OP's bike won't have disk brake mounts, and adding them to a frame is complex engineering.
Comment: Hi, welcome to bicycles.  This doesn't seem to help OP much with whether it's possible to change the wheels of a "Jupiter King" to 700c.
Answer: The outside diameter of a 700 wheel is obviously (?) 700 mm which equates to 27.5 inches. A 27 inch wheel has an O/D of 27 inches. If things are a bit tight you cannot replace a 27 inch with a 700C especially if using larger sized tyres i.e. 38-700 or even 35-700, I know as I have recently tried it. You could probably get away with a small tyre such as 25- or 28-700 but may have to use longer brake arms. Better going the other way but not a lot of point, really.
Comment: The *rim* diameter of a 700c wheel is actually slightly smaller than that of a '27inch'. 700c bead diameter is 622mm whereas 27" bead diameter is 630mm.
Comment: Obvious... but wrong, sorry. 700mm is the nominal diameter of the tyre, not the wheel. These days, you only tend to find 700C but 700A, 700B and 700C all had different rim diameters so that different-sized tyres would take the total diameter to 700mm.
Answer: Don't listen to anyone that claims it's not possible to convert because of rim brake compatibility. If you don't have enough reach with the current brakes installed… all you have to do is source new brakes!
I can't say that about all bicycles though, some conversions will require some mechanical know-how and tinkering capabilities, or the drive to learn which is something I wish more people were open to try. It's sad to hear that people will give up on the first set back like "my brake arms don't reach." Have they not noticed that bike parts/components are 99% non-proprietary to the frame?
Comment: Welcome to the site - as a new poster it is recommended to browse the [tour] and learn how the Stackexchange Q&A format works.  Instead of duplicating info in existing answers just upvote the answers you found useful, and downvote anything that is wrong.   "purchase brakes with a longer reach" was already mentioned in the oldest answer.   It may be easier to try answering a newer question.  I've also edited this to clear the "rude or abusive" flags.


Building a class that contains built classes

Question: I have some classes I've created that are immutable and follow the builder pattern. I'm now creating a composite class that will include those classes as fields. Should the builder for that composite class call through to the sub-builders and then build them in the outer builder's build() method, or should the composite builder have methods that accept already constructed instances of the contained classes, or should I allow both options?
Answer: I'm going to assume your classes are called Composite, Foo, Bar and Baz.
The simplest option is to let CompositeBuilder take pre-built Foos/Bars/Bazs, so you get new CompositeBuilder().setFoo(...).setBar(...).setBaz(...).build(). The big advantage here is that the API to your Composite class is dead simple, both for you and your users. KISS and YAGNI apply here. Plus, you still get the option of subclassing Foo/Bar/Baz, and this might make it easier to change Foo/Bar/Baz themselves since Composite doesn't have to know much about them.
The alternative of having CompositeBuilder provide it's own interface has other potential advantages, assuming that you provide a much smaller, narrower interface than the one you get "for free" from the three subbuilders. That can potentially make Composite much easier to work with, and opens the possibility of someday changing Composite to use Oof/Rab/Zab instead of Foo/Bar/Baz without affecting client code, in case subclassing isn't enough.
I would avoid providing both, unless you're very sure you have a lot of users that want a simplified interface and a lot of other users who need the full power of a raw FooBuilder. Trying to do too many things at once always runs the risk of doing none of them well (and making it hard for anyone to figure out how they're supposed to use Composite).
Which one you should pick depends on a lot of factors you haven't described. How complicated are the three subbuilders? How much customization does a Composite need? Will users of CompositeBuilder already be familiar with the Foo/Bar/BazBuilders? Do they despise the current Foo/Bar/BazBuilder interfaces? Are there separate "consumers" and "producers" of these objects, or are they usually used in the same place where they're built? Would it ever make sense to change the classes that Composite is implemented with? And so on and so forth.
Comment: You gave me some very good points to chew on, which led me to my ultimate conclusion: I realized that while I was not likely to replace Foo with Oof, I am likely to subclass Foo or directly extend Foo with additional fields. If I take pre-built Foos, then my Composite class doesn't need to know about the change, which is preferable. I don't want this point to get lost in the comments. If you add it to your answer I will accept it.
Comment: @TBridges42 Very good point. Added it.
Answer: I tend to prefer a builder for each object that accepts fully built sub-objects.
The primary reason is this path provides simplicity of implementation, without loss of flexibility of expression. Also, I find it more readable.
Compare two completely facetious examples:
CompositeClass.builder()
              .withArgument(some_arg)

              .withSubclass1Argument1(some_arg)
              .withSubclass1Argument2(some_arg)

              .withSubclass2Argument1(some_arg)
              .withSubclass2Argument2(some_arg)
              .build();

vs
CompositeClass.builder()
              .withArgument(some_arg)
              .withSubclass1(Subclass1.builder()
                                      .withArgument1(some_arg)
                                      .withArgument2(some_arg)
                                      .build())
              .withSubclass2(Subclass2.builder()
                                      .withArgument1(some_arg)
                                      .withArgument2(some_arg)
                                      .build())
              .build()

It comes down to personal preference, but I find the second easier to read and work with.


Relationship between absolute magnitude of a star and its luminosity?

Question:
Why does this relationship involves the absolute magnitude of the sun and its luminosity?
How to derive an expression relating the absolute magnitude of a star to its luminosity?

So according to the magnitude equation, $$m - M = 2.5\log\left(\frac{d^2}{d_0^2}\right)$$
$$\Rightarrow M = m - 2.5\log\left(\frac{d^2}{d_0^2}\right)\ \ (eq1)$$
and Luminosity is $$L = 4\pi(d^2) \times f$$
 $$\Rightarrow d^2 = \frac{L}{4\pi \times f}\ \ (eq2)$$
Plugging eq2 to eq1 would have seem reasonable, but how is absolute magnitude of the sun and its luminosity used?
Comment: This site has TeX enabled. You can format your equations using TeX
Comment: It's only used because we compare other star's luminosity to the Sun. In theory, you could measure luminosity in watts (https://en.wikipedia.org/wiki/Luminosity tells us the Sun's total brightness is 3.846×10^26 watts), but it's the same reason we use light years and astronomical units: to avoid numbers from getting too large.
Answer: You are specifically talking about absolute visual magnitude; how bright an object would appear to our eyes if the object were 10 parsecs away from us. However, you must remember that stars emit a wide spectrum of light — much of it isn't visible to the naked eye.
Luminosity is a measure of the total amount of energy given off by a star (usually as light) in a certain amount of time. Thus, luminosity includes both visible light and invisible light emitted by a star. So there isn't a precise conversion between luminosity and absolute visual magnitude, although there is an approximation we can do.
Absolute bolometric magnitude is an analogous magnitude system considering all the energy emitted by the star. The formula relating absolute bolometric magnitude with luminosity is as follows:
$$L_\text{star} = L_0 10^{-0.4 M_\text{Bol}}$$
where $L_\text{star}$ is the star's luminosity, $M_{\text{Bol}}$ is the bolometric magnitude of the star, and $L_{0}$ is the zero-point luminosity (the luminosity of a star with $M_{\text{Bol}} = 0$) arbitrarily defined as $L_{0}=3.0128×10^{28}$ watts by the IAU. We can approximately convert between the two magnitudes via a bolometric correction:
$$M_{\text{bol}}\approx M_V + BC$$
The bolometric correction term $BC$ is empirically determined for the spectral class and evolutionary stage (although it can be modeled; see Torres (2010)). A table of values is given on the Wikipedia page.
The idea is that stars of the same spectral class and evolutionary stage have a similar distribution of wavelengths, so the discrepancy between all emitted wavelengths ($M_{\text{bol}}$) and visible wavelengths ($M_V$) should be similar.
Thus, the conversion between luminosity and absolute visual magnitude is approximately
$$L_\text{star} \approx L_0 10^{-0.4 (M_V + BC)}$$
Of course, this is only an approximation, but it can give us a pretty decent idea of what to expect. Trying it on 9 Pegasi, I predicted it would be around $1000 L_\odot$, which is still in the ballpark of the actual value $1950 L_\odot$. Mind you, the approximation would be better suited for less extreme stars than 9 Pegasi.


Are U.S government bonds completely liquid?

Question: In the event of a market downturn like 2008, could I liquidate them whenever I wanted to at good price on a retail stock broker?
Comment: Note that selling during a downturn is a Bad Idea.
Comment: @RonJohn what if the selling of bonds is to free up capital take advantage of even lower equity prices?
Answer:
Are U.S government bonds completely liquid?

A liquid asset is anything that can be sold quickly.  US Government Bonds are very liquid.

In the event of a market downturn like 2008, could I liquidate them whenever I wanted to

Yes.

at good price

Probably not Maybe.  After all, price is a function of supply
and demand.
During the 2008 meltdown, "everyone" was selling stocks, so there was a large supply, and low demand.  Thus, prices fell.
The bond market was affected because some traders needed cash quickly to satisfy loans, and so had to sell their bonds to raise that cash.  That increased supply meant... lower prices.
Thus, the answer to "at good price?" is not really maybe.

on a retail stock broker?

Yes, as long as they are the custodians.
Comment: "In the event of a market downturn like 2008", T-Bond prices were "really good", like 15-25% capital gains.
Comment: @RonJohn Look at a TLT chart. There was no unusual downward volatility in Treasury bonds during 2008. There was, however, unusual upward volatility in Nov and Dec.
Comment: @base64 was that *during* the collapse, or *afterward*?  (I know the Fed dropped interest rates *afterwards* to stimulate liquidity.)
Comment: Interesting.  This makes sense but this makes most publicly traded stocks liquid as well.  I hadn't thought of it that way.
Comment: @base64 I would like to know this as well.


Sound from cupping hands over ears

Question: Sit in a silent place and then bring your hands close to your ears and cover your ears, you will start hearing some sound but if you remove your hands you don't hear it anymore. Can anyone explain physics of this?
Comment: @WetSavannaAnimalakaRodVance It's the same reason you hear the _sea_ in a seashell. http://en.wikipedia.org/wiki/Seashell_resonance
Comment: My guess is that your cupped hands are working like resonant cavities with a definite frequency response. Therefore, the spectrum of background noise around you is changed and you mind suddenly notices it because its spectral content is markedly different from what is wonted to your mind, having been quite radically altered by the hand-cavities.
Comment: here is a full explanation http://en.wikipedia.org/wiki/Seashell_resonance
Comment: Would you get the sound if you cupped your hands around a microphone or put a seashell on it?
Answer: The most likely explanation for the hissing noise you hear is ambient noise from around you , That is increased in amplitude according to the dimensions of the resonant cavity (your cupped hands ) so theoretically if you are in a real soundproof room this will not work , if you change the cavity size and distance of your cupped hands from your ears  you can hear a slightly different pitched hiss . does that rings a bell ??
Try this take an empty preferably a thin walled metal mug (though a cold drink bottle will also work fine ) and some water ,  sit in a silent place  keep the mug on a table now you must be able to hear the same hiss when you bring your ears close to the mug now pour in some water and try to hear again the pitch of the hiss(noise) must change for different levels of water in the mug   ,The level/pitch of the sound will also vary depending on the angle and distance the cup is from your ear  if it does it can prove that resonant cavity is the reason for this hiss sound.
Similar explanation goes for sea shells also seashells captures this ambient noise, which resonates inside the shell . The size and shape of the shell therefore has some effect on the sound you hear. Different shells sound different because different shells accentuate different frequencies.

Sound from cupping hands over ears


Quantum mechanics and Group theory

Question: Vectors are representations transform under $SO(3)$ Group, 4-vectors are representations transform under $SO(1,3)$ Group,
Like wave function in discrete but infinite  basis (hilbert space) are some representations which transform under what? what about continuous basis? what are the Groups which form quantum mechanics?
Comment: Vectors are not representations. Vectors are one example of things  that transform under representations. You can think of a representation as a collection of matrices, one corresponding to each group element. For example, for each SO(3) rotation, there is a 3x3 rotation matrix which rotates 3-vectors.
Comment: You might profitably consult [WP](https://en.wikipedia.org/wiki/Stone–von_Neumann_theorem).
Comment: So can u define in general a tensor in 3 dimensions with a SO(3) group ,  what we call things that transform under representations ? @ –  G. Smith
Answer: The book you might consult on the subject is a classic one,  by H Weyl, The Theory of Groups and Quantum Mechanics, Dover Publications, 1950, ISBN 978-1-163-18343-4.
A continuous (Lie) group SO(3) ~ SU(2) is generated by three generators, and its group elements are exponentials of all linear combinations of said generators. An n-dim representation of the group thus consists of $n\times n$ matrix exponentials acting on n-vectors; n-1 is twice the spin; you mention n =3, but it could be n =2, for a simplest spin 1/2 system. The operators and observables of such a simple spin system are in the space of functions of the generators, so, not just the exponentials: this space is called "the universal enveloping algebra" of the so(3) Lie algebra, and is not a Lie algebra, so it is not closed under commutation. So, in this simplest model, your Hilbert space is two dimensional.
(Again, SO(1,3) has six generators with representations which are not just 4×4 dimensional matrices, but quite varied, as you may read up on elementary group theory books or WP.)
The conventional QM Hilbert space you may well have in mind consists of infinite-dimensional vectors acted upon by infinite-dimensional square matrices in the universal enveloping algebra of the Heisenberg Lie algebra (generated by $\hat X, \hat P$ and the center thereof, the identity matrix in the infinite-dim  representation of the continuous Heisenberg group ).
Thus, your operators are functions of the above generators, acting on, e.g., eigenvectors of $\hat X$, an infinite-dimensional vector space, now. There are further technical restrictions such as square integrability, but they apparently outrange the scope of your question.
The Heisenberg group provides suitable changes of basis of such a Hilbert space, and, again, Hamiltonians  generate upon exponentiation continuous "rotations" of such Hilbert space states, even though they themselves do not close into the Heisenberg algebra. Instead, the Heisenberg algebra specifies the (unitary) quantum canonical transformations (motion) they (the Hamiltonians) generate, the group Weyl calls that of quantum kinematics.
You may usefully train your intuition as Weyl did in his book, by taking the infinite-dimension limit of finite Hilbert spaces acted upon by Sylvester's (1882) clock and shift matrices.
Answer: First, we need  to distinguish between a mathematician's representation and a physicist's. Formally, a representation of a Lie group $G$ on a vector space $V$ is a homomorphism $\rho : G \to \mathrm{Aut}(V)$ such that,
$$\rho(g_1g_2) = \rho(g_1)\rho(g_2).$$
$\rho$ is the representation, but physicists will often call $V$ the representation (space) or elements $v\in V$ as the representation. For example, Euclidean spinors transform under $\mathrm{Spin}(n)$.
Note that $\rho(g)$ need not be a matrix, and the only constraint is that it act linearly  on the space, so there are many non-trivial actions one can define.
The Hilbert space in quantum mechanics is a space which - as said in Comas' answer - is acted upon by the Heisenberg group.
However, the wave function is slightly more complicated than say, a vector. Formally, the wave function is a section of an associated bundle to a principal bundle constructed from a symplectic form. The advantage of this is to formulate the dynamics in a coordinate independent way, as for example self-adjointness fails in quantum mechanics for certain choices of coordinates.

Quantum mechanics and Group theory


Is it possible to swap the Alt keys of a MacBook keyboard?

Question: I dual-boot elementary OS on my MacBook and it annoys me that the two alt keys do different things, but in particular that all characters for which I use the left alt key in OSX now require the right one (e.g. \ or @) which make for some very taxing finger exercise especially on the command line. So my question is, can I interchange the roles of the two alt keys?
Answer: You can use xmodmap for that. First find out the keycode(s) of the alt keys using "xev". If not installed, you should install the x11-utils package. So type
$ xev | grep keycode

in terminal, focus to the small window by clicking on it and look to the output in terminal.
Now press the ALT key(s).  You will see the keycode of the key and its name (e.g. keycode 64 and ALT_L for the left ALT key). Remember the displayed code and name. Let's assume that ALT-L has code 64 and ALT-R code 77. Now type in terminal:
$ xmodmap -e "keycode 77 = Alt_L"
$ xmodmap -e "keycode 64 = ALT_R"

Note: I don't know the "real name" for right Alt key, so the name in  second command will probably not be correct.
Now the behaviour of the keys should be changed. Try it.
This will only work until next reboot. If you want to make it permanently, you can add the two last commands to your ~/.bashrc.
Maybe it is not the simplest way, but it should work.


Is it possible to make a 1-bit (bitonal) JPEG?

Question: I think the answer is no, so I guess what I'm really looking for is an explanation. It seems as though with every library and tool I've tried for converting images, even when all of the pixels are black or white, the image is still 8-bit. Could someone kindly explain?
Answer: It depends what you mean by JPEG. Commonly, we're talking about JFIF/EXIF image file formats, which specify either one or three bytes per pixel (regardless of the colour space mapping those bytes to bits). Create a file that actually has only two discrete levels present, and it's no longer a JFIF/EXIF file. (And since throwing out high frequency information is the basis for JPEG compression, and all tonal changes in a bitonal image are by definition high frequency transitions, JPEG is a pessimal solution.)
For pure bitonal images using a JPEG-like compression, you'd need to be using JBIG or JBIG2, a format essentially for fax (and not commonly readable). A paletted solution that uses DEFLATE-style compression (redundancy mapping + Huffman or LZW-style bit reduction), such as PNG would be a better solution for most applications, however, since the position (and not merely the distribution) of the bits in the reconstructed image is guaranteed.
Answer: A 1-bit image would be like an ink blot. Each pixel would be totally black or totally white with no in between. An 8-bit B&W image allows for each pixel to be one of 256 shades including pure black, pure white and 254 shades of gray in between. Old newspaper photos used a primitive form of dithering to fool the eyes into thinking black dots on white paper were various shades of gray. But the images they were produced from had a much higher tonal range, and the result was a much lower resolution image than the original.
Comment: Thanks Michael. I get why you wouldn't want to do it...but that's what I'm dealing with; the spec I'm working against says '1-bit bitonal JPEG'. Here is a sample of my output http://www.princeton.edu/~jstroop/bitonal.jpg (scaled down) and it's dithered sort of as you describe, but still 8 bit; I'd like to make it 1-bit if possible, but it seems as though I need a bitmap format to do that, and that it's not possible with JPEG. This is all I'm trying to confirm.
Comment: JPEG is a bitmap format but it's 8-bit per pixel per channel.
Comment: FYI - JPEG2000 part 6 has options for bitonal content mixed with graduated tonal elements.


who is the of author of CN 101463502 B?

Question: who is the author of the patent number CN 101463502 B## Heading ## entitled Pineapple leaf fiber biochemical degumming technique?
Answer: Patents do not have authors, they have inventors and they have applicants. Typing the document number into google patents immediately brings the answer up. Only Chinese names of the inventors are shown.

Comment: thank you very much...
i also want to ask...what is the difference between the inventors and applicants?
i am just confused between the two terms..
thank you
Comment: Inventors are the actual people who had the novel idea. Applicants might be those same people or might be a company or a person that the inventors work for or sold the invention to. After the patent issues the applicant owns the patent and can sell it to yet another person or company who would then the owner.

who is the of author of CN 101463502 B?


Download and install newer KDE without root access?

Question: Without being root, is it possible to download a newer version of KDE and use that as your window manager for a RealVNC server?
Comment: do you have the ability to sudo?
Comment: I don't have root access.
Answer: It's absolutely possible.  If you can sudo, you can install the newer KDE via your favorite package manager (assuming it's available in the repositories).
If the version you want isn't in your distribution's repositories, you can build KDE yourself (Getting Started link).
If you can't sudo, you won't be able to install anything under /usr/local.  You'll need to install to your home directory instead.  Anytime the instructions list an "install prefix" variable, change it from /usr/local/... to /home/username or /home/username/....  If configure scripts are in use, this is easy:
./configure --prefix=/home/username

That change will allow you to install your build to your home directory, under $HOME/bin, $HOME/lib, $HOME/share, etc.  You'll need to update your login scripts to include your home directory in the PATH and LDPATH in order to access it.
Comment: not clean, but works indeed. +1 :)
Answer: Without root access (be it directly or via sudo(1)), installing something as invasive as a full desktop environment (including matching applets, plugins and whatnot) is probably impossible, and at best very ill advised.
What exactly is the objective of this? If it is just access to a newer KDE, updating the distribution is probably simpler and much less risky.
Comment: I know that it is hard to do.  I work inside of the Linux environment for a large corporation and getting new versions is like pulling teeth.  I can and do install Ubuntu on my own virtual machines and home machines all the time, but I can't do my job on these machines.
Comment: @RossRogers, better start your training as a dental surgeon then...
Comment: Indeed.  I recently tried installing gnome from jhbuild in order to get all the prerequisites for a recent monodevelop and that was quite the rabbit hole.  jhbuild is meant for installing and testing new releases of gnome in parallel to your normal desktop, yet it was endless dependency fetching.  Meanwhile, I can install monodevelop in a few clicks on Windows.  'tis a shame.


Limit country drop down input field Magento 2

Question: Currently my magento store shows all the country in shipping, billing, and register customer form. is there a way to show only some countries that i want ?
Answer: Please allow only that need from Admin > Stores > Configuration > General >
Country Options > Allow Countries
Comment: how to set the default selected country for the dropdown?
Comment: select "Default Country" from dropdown goto Admin > Stores > Configuration > General > Country Options > Default Country
Answer: You can set country drop down option from

Admin >> Store >> Configuration >> General >> General >> Country
  Options.

Default Country : Selected country will display as default country in drop down.
Allow Countries : Selected countries will display in country drop down options.


FLWR and curvature

Question: The FLWR metric or model I believe results from Einstein's equations of general relativity if it is assumed the universe is 1. homogeneous and 2. able to expand (or contract). Solutions can have positive spatial curvature, negative spatial curvature or be flat. My problem is that negative curvature, termed hyperbolic, often depicted as a saddle, seems to be in no way homogeneous. For example as you move around a sphere, or through flat space, the curvature remains constant but as you move along a hyperbolic curve, the curvature varies - it can't be homogeneous. How is this resolved?
Comment: Anti deSitter space is an example of a homogeneous spacetime with constant negative curvature https://en.wikipedia.org/wiki/Homogeneous_space
Answer: But it is. There can be an isotropic negative curvature distribution, as there was in the early universe, in the time of inflation. All points in that space were situated in the same surroundings as all other points. That's why all virtual particles accelerated away from each other in the same way as all other ones. You can imagine this as a torus cut open on one side, with a very small aperture in the middle. The open parts (two of them) extend to infinity.
The small "hole" in the middle of the torus (not an actual hole in the torus itself) represents the big bang.
Also note that space isn't actually expanding. It can't. It can be stretched due to matter/energy, but it cannot expand or contract. The galaxies don't move away from each other due to expansion. They actually move away from each other on a fixed background of negatively curved spacetime (dark energy). The universe looks like this (when normal matter-energy is present):

The hole has a much smaller size though and corresponds to time zero. Of course, a 3-d version is the real stuff but unimaginable.
The FLWR metric:
$$g=d{\tau}^2=dt^2-a(t)^2d{\Sigma}^2,$$
from which you can see that the space component of the metric is time-dependent. In reality, though the spacetime metric is fixed. Why should the metric change in time? It's a misleading picture (I was misled too). Spacetime is fixed in time (it can change of course but not in the way expressed by the above metric. This metric has to be replaced by the metric of a negatively curved spacetime. The metric can be equivalent, but it's certainly not the same.
Comment: Yes, your diagram looks like a hyperbolic curve, But it has variable curvature so how can it be homogeneous?

FLWR and curvature


Why is Resistance not a mage spell?

Question: I'm playing what's effectively a counter-caster, and a spell I noticed that is on both the cleric and druid spell lists is the cantrip Resistance. This spell gives a bonus to a single saving throw, and would fit well with what I'm playing. However, it's not on the mage spell list. Why? The only reason I could think of is the roles of clerics and druids versus the role of a mage, but that is fairly minor especially given that it's a cantrip.
Comment: Remember that "minor" doesn't mean "unimportant". Minor things can be the thin edge of a very important-to-avoid wedge when it comes to game design.
Comment: Note; for reference back in 3.5 it was available for Bards, Clerics, Druids, Paladins, Sorcerors and Wizards: http://www.dandwiki.com/wiki/SRD:Resistance
Comment: You can also multi-class to gain access to more spells and cantrips. So you could start as a Cleric and immediately switch to Wizard when reaching level 2 (assuming your DM is okay with multiclassing.)
Answer: Only the designers can accurately answer this; our answers would only be speculations.

It seems to me that each class's playtest spell list is made more distinct than in 3.x... by cutting spells from the list.
For example:

Bards no longer have Grease, Haste, Mirror Image, Blink, or other "mage-like" spells.  Less support and buff, which renders them a lot more trick-oriented.
Clerics lost Divine Favor, Magic Weapon, Wall of Stone, Astral Projection, etc. Less fighting and controlling, and slightly more about protection and anti-undead/outsider.
Even Paladins and Rangers now see a very different and unique spell list (aura, smite, arrow spells).
Mages lost Detect Poison, Tongues (now Holy Accord), Daylight, and your example of Resistance.  They are now slightly more focused on control (especially since they can only concentrate on one buff).

With the increased availability of healing/restorative spells (reducing diversity), and the introduction of sub-class spell list (further reducing diversity), I would say this is designed intentionally to keep the base classes more distinguished.
In fact, since cantrips can be cast at-will, they are the most used spells.  Do you light a camp fire with Thaumaturgy, Fire Seeds, or Prestidigitation?  Do you pray for divine Guidance before you do anything?  Perhaps you Ray of Frost all your drinks.  In real play, they really say a lot about your class.

Or you can work out an abjuration mage with your DM, with the Resistance cantrip as a class feature.

Why is Resistance not a mage spell?


Lions vs. dogs for defense?

Question: I am looking for a statement in Gemara or Halacha that one may own a dog for defense but not a lion. Does any of you know the source?
Comment: Seems like you're thinking of the the gem. BK 79b (see Yam Shel Shlomo BK ch. 7 §45) and codified in SA (CM 409) but don't know where (if at all) a lion is specifically excluded.
Answer: I found the source, I think. Mishnah Bava Kama 1:4. R. Eliezer holds that one could train a lion, the חכמים disagree.
Comment: Welcome to Mi Yodeya, user3140521! Remember you can edit your profile and make your username a bit more personal. Also, thanks for your answer! We hope you'll stick around.

Lions vs. dogs for defense?


In FEM, can each instance of a Transient Analysis be thought of as a Static Analysis of its own?

Question: Assume I have a cantilever beam fixed at one end. I can conduct a static analysis in FEM for a case where I apply a load on the other end, condition being the load is consistently applied on it and time is not an issue here. On the other hand, I apply the same load at the same location on the beam but not consistently, but instead only for a few miliseconds, for example. So my question is that during these miliseconds i.e. during which I apply the load, should the results of Displacements and Stresses within my model by any different to if I apply the same load at the same location consistently, without a duration of time. If not, then why do we even need to conduct a Transient Analysis when we already have the availability of a much simpler module i.e. Static Analysis?
Comment: Is that like calculus where only a small change is assumed?
Answer: I am not aware there is such an analysis method called "transient analysis" for civil/structural engineering, I think you mean the analysis of structure with the "transient loads.
By definition, the transient load is temporary and brief in nature. In structural engineering, except for the dead weight, almost everything else can be called a transient load, for example - live load, wind load, seismic load, moving load, etc. However, due to the uncertain natures of the transient loads (its intensities, durations, and potential of reoccurrences), historically, they have been evaluated using statistics means and formatted to fit the equivalent static analytical methods, or converted conservatively to the equivalent static loads by the code authorities for simplicity in general design tasks.
The static analytical methods and the equivalent static loads have been proven to yield satisfactory results prior to the advent of PCs, which have led to the fast advancement in structural engineering (capability) and material science. As the structures get more complicated, and the interests in saving by fully utilizing the strength of the materials, for certain cases, the use of the "equivalent static methods and equivalent static loads" are sometimes deemed no longer appropriate, thus the calls for the use of the "real loads" instead. The most noticeable cases are the time-history analysis of seismic resistant structures, and utilizing wind tunnel data for wind analysis. Without using the "real (transient) loads", many structures would not have been built.
Does the duration of load affect the performance of a structure? No, and yes. No, unless stressed to yield, a 1 kip force placed on the tip of a cantilever beam for 5 minutes and 5 hours or 5 days will yield the same amount of deflection. However, yes, the duration of the sustained load is the main concern of the long-term deflection due to creep.
Comment: Yes, exactly, that is my question. Why would transient analysis needs to be conducted in the first place when we already have the static analysis available? I mean we can just take the max value of the force during the transient phase and check out if the structure is failing or not, and make some necessary design modifications if needed. What else do we need to check out which makes the use transient analysis using transient loads to become compulsory, instead opting out for static analysis using static loads only?
Comment: @RameezUlHaq because you can load a human thigh bone slowly and it is strong, but hit it sharply with a hammer and it breaks easily…


How do I get the user ID from the $user_profile variable?

Question: How can I get the user ID and load the user with user_load() using the $user_profile variable in the user-profile.tpl.php template file?
Answer: Using the following code in a module will make the user ID available to the user-profile.tpl.php template as $user_id.
function mymodule_preprocess_user_profile(&$variables) {
  $account = $variables['elements']['#account'];
  // Add the user ID into the user profile as a variable
  $variables['user_id'] = $account->uid;
  // Helpful $user_profile variable for templates.
  foreach (element_children($variables['elements']) as $key) {
    $variables['user_profile'][$key] = $variables['elements'][$key];
  }

  // Preprocess fields.
  field_attach_preprocess('user', $account, $variables['elements'], $variables);
}

This means that you can then copy the user-profile.tpl.php template from the modules/user directory to your theme directory and change it to the following.
<div class="profile"<?php print $attributes; ?>>
  <?php print $user_id; ?>
  <?php print render($user_profile); ?>

Answer: You cannot get the uid from $user_profile as it does not contain any information we can use to get the current user.
To get the current user's object, use the following:
global $user;
echo $user->uid;

Comment: Thank you but I wanted the requested user not the current. Anyway, I've find another way to do
Answer: The user-profile.tpl.php template file doesn't get a variable containing the user ID, nor a user object. The $user_profile variable contains what needs to be rendered for the user profile. template_preprocess_user_profile() retrieves the user object used for the profile, but it doesn't pass it to the template file, nor does it pass the user ID.
If the user ID is necessary in the user-profile.tpl.php template file, implementing hook_preprocess_HOOK() helps.
function mymodule_preprocess_user_profile(&$variables) {
  if (isset($variables['elements']['#account']) && isset($variables['elements']['#account']->uid)) {
    $variables['uid'] = $variables['elements']['#account']->uid;
  }
}

The template file can then use $uid to get the user ID.
Notice that copying other code from template_preprocess_user_profile() is not necessary: template_preprocess_user_profile() is executed before any preprocess and process functions, whenever they are implemented in modules or in themes. An implementation of hook_preprocess_user_profile() doesn't override/replace template_preprocess_user_profile().


Minitng tokens automatically over a regular periods of time

Question: Is there maybe a way to program a contract to mint a certain amount of tokens over regular periods of time automatically?
Say, I would like a contract to create 1 000 new tokens once a year on Dec., 31st for next 100 years
Many thanks
Answer: Contract functions only run if some user or other contract initiates a call to that function. Therefore, it would not be possible to create a function which on its own runs regularly based on block number or date. You could create an external service which calls the addMoreTokens function regularly, but that does not sound like what you want.
It seems like you are trying to create a 'pot' of tokens which grows over time. I think you would be able to achieve this by minting all the tokens up front, and then limiting the number of tokens which can be 'withdrawn' using the current date.
Here is some pseudo-code:
function withdrawTokens (_amount) {
  //calculate fraction of tokens that should be available
  fraction = ((currentTime - startTime)/(finalTime - startTime))

  //calculate number of tokens available to give out
  tokensAvailable = (fraction * totalTokens) - tokensAlreadyGivenOut

  //check that the amount being requested is less than tokens available
  require(tokesAvailable > _amount)

  //increase number of tokens already given out
  tokensAlreadyGivenOut += _amount

  //grant the user the new tokens
  tokens[msg.sender] += _amount
}

I am not a super expert here, but sounds like this is a possible solution.


Is one "obligated" to eat donuts/latkes on Hanukkah (as to not deviate from customs)?

Question: In general one should not deviate from accepted customs (i.e minhag yisroel zu halacha). Does that obligate one to eat donuts/latkes/dairy on Chanukkah if he would prefer not to?
Comment: Probably inasmuch as one is obligated to each gefilte fish...it's not like matza.
Comment: Maybe dairy is healthy, and builds strong bones and teeth.  However, maybe jelly donuts are unhealthy, even in tiny doses, because of the sugar in the jelly.  So maybe this question should be split into multiple questions.
Comment: I think this delves into a more general question as to what is considered a minhag. I can't think of any food item that has become "halacha" come to think of it. There's a minhag to eat chulent and kugel on Shabbat but it is not halacha to eat these items. Perhaps, food or any minhag has less of this "halacha" status when it comes to rabbinical holidays?
Answer: Wikipedia cites R. Maimon, father of the Rambam, on this question:

אין להקל בשום מנהג ואפילו מנהג קל. ויתחייב כל נכון לו עשות משתה ושמחה
  ומאכל, לפרסם הנס שעשה השם יתברך עמנו באותם הימים. ופשט המנהג לעשות
  סופגנין, בערבי אלספינג, והם הצפחיות בדבש, ובתרגום: האיסקריטין, והוא
  מנהג הקדמונים משום שהם קלויים בשמן, זכר לברכתו".

According to R. Maimon, one should not be lenient even about a "light" custom, such as feasting on Hanukkah; likewise the custom has spread to make "sufganin." In the continuation of this quote, R. Maimon states that one should not be disdainful of such customs, and that one who fulfills them is one who has alacrity and who has expended effort (זריז ומשתדל). It would seem that one may not be dismissive, but is not obligated to actively fulfill such customs, although it is praiseworthy to do so.
Answer: According to the Minhag Yisrael Torah 670:3 cited in Jaeger and Barclay Guidelines, there is a minhag to eat oily foods on Chanuka.  I have seen in a collection of Sefardi Halachot that it is certainly a good practice to eat foods that have oil.  The accepted practice in EY is to eat doughnuts on Chanuka.  People also make Potato Latkes.  However, this is also custom and traditional.
The Aruch HaShulchan (670) brings a custom to have milky foods in remembrance of the event of Yehudis who killed a Greek General through giving him very salty cheese, and thus giving him wine to drink afterwards and making him drunk, at which point she severed his head.  The Aruch Hashulchan (670:8) mentions this episode, but suggests that this happened during the 2nd Beis Hamikdash period and is much later than thought to be.  It is certainly a matter of dispute over whether one should increase at your regular Seudah on Chanuka (see the Rama on 670, and Aruch Hashulchan 670:9).
None of the major Ashkenazi Poskim bring down this minhag of eating oily foods. Since this has become a widespread practice, it is certainly meritorious to do so.  However, many people find oily food to be sickening and one certainly should not over indulge or even eat oily food if it will make one sick.
To answer your question: No, there is no Torah or rabbinic obligation to eat any oily foods.
That being said, if one's preference is simply the taste of these particular foods (rather than due to a legitimate health consideration, in which case you should not partake if it would make you genuinely ill), one should at least try to fulfill the custom in another way in which oil is used — for example a stir-fry or fried fish.


Mysql client within ssh within expect quoting annoyance

Question: I'm trying to execute the following in a bash script:
REPLICATION_USER_SETUP=$(expect -c "spawn ssh $LDAP_USER@$MASTER_IP_ADDRESS \"mysql --user=$MYSQL_USER --socket=$MYSQL_SOCKET --execute \"GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO \'$MYSQL_REPLICATION_USER\'@\'$SLAVE_IP_ADDRESS\' IDENTIFIED BY \'$MYSQL_REPLICATION_PW\';\"\";expect Password:;send $LDAP_PASS\r;interact")

But I keep getting "extra characters after close-quote" whenever I try to run it.
I've tried variations of double and single escaped quotes, but nothing seems to be working.
Can anyone tell me what I'm doing wrong here?
Answer: try escaping backslashes of sql query:
REPLICATION_USER_SETUP=$(expect -c "spawn ssh $LDAP_USER@$MASTER_IP_ADDRESS \"mysql --user=$MYSQL_USER --socket=$MYSQL_SOCKET --execute \\\"GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO \'$MYSQL_REPLICATION_USER\'@\'$SLAVE_IP_ADDRESS\' IDENTIFIED BY \'$MYSQL_REPLICATION_PW\';\\\"\";expect Password:;send $LDAP_PASS\r;interact")


Python Azure blob storage upload file bigger then 64 MB

Question: From the sample code, I can upload 64MB, without any problem:
   myblob = open(r'task1.txt', 'r').read()
   blob_service.put_blob('mycontainer', 'myblob', myblob, x_ms_blob_type='BlockBlob')

What if I want to upload bigger size?
Thank you
Answer: I ran into the same problem a few days ago, and was lucky enough to find this. It breaks up the file into chunks and uploads it for you.
I hope this helps. Cheers!
Answer: I'm not a Python programmer. But a few extra tips I can offer (my stuff is all in C):
Use HTTP PUT operations(comp=block option) for as many Blocks (4MB each) as required for your file, and then use a final PUT Block List (comp=blocklist option) that coalesces the Blocks. If your Block uploads fail or you need to abort, the cleanup for deleting the partial set of Blocks previously uploaded is a DELETE command for the file you are looking to create, but this appears supported by the 2013-08-15 version only (Someone from the Azure support should confirm this).
If you need to add Meta information, an additional PUT operation (with the comp=metadata prefix) is what I do when using the Block List method. There might be a more efficient way to tag the meta information without requiring an additional PUT, but I'm not aware of it.
Answer: This is good question. Unfortunately I don't see a real implementation for uploading arbitrary large files. So, from what I see there is much more work to do on the Python SDK, unless I am missing something really crucial.
The sample code provided in the documentation indeed uses just a single text file and uploads at once. There is no real code that is yet implemented (from what I see in the SDK Source code) to support upload of larger files.
So, for you, to work with Blobs from Python you need to understand how Azure Blob Storage works. Start here.
Then take a quick look at the REST API documentation for PutBlob operation. It is mentioned in the remarks:

The maximum upload size for a block blob is 64 MB. If your blob is
  larger than 64 MB, you must upload it as a set of blocks. For more
  information, see the Put Block (REST API) and Put Block List (REST
  API) operations. It's not necessary to call Put Blob if you upload the
  blob as a set of blocks.

The good news is that PutBlock and PutBlockList is implemented in the Python SDK, but with no sample provided for how to use it. What you have to do is to manually split your file into chunks (blocks) of up to 4 MB each. and then use put_block(self, container_name, blob_name, block, blockid, content_md5=None, x_ms_lease_id=None): function from the python SDK to upload the blocks. Ultimately you will upload the blocks in parallel. Do not forget however that you have to execute also put_block_list(self, container_name, blob_name, block_list, content_md5=None, x_ms_blob_cache_control=None... at the end to commit all blocks uploaded.
Unfortunately I'm not Python expert to help you further, but at least I give you a good picture of the situation.


Converting Layered .ai to PDF via PHP

Question: I've a .ai file with 2 Layer Groups and I want to pipe them into a .pdf file with layers. I already tried ImageMagick but I can't get the selector.
I tried this:
<code>exec("convert 'test.ai[0]' output0.png");
exec("convert 'test.ai[1]' output1.png");
</code>
The First one gives me the whole document. I tried .png for a faster preview of the content first. Anyone have a clue how to handle this? The PDF File will contain more informations then the .ai later.
Friendly regards
Kevin
Answer: Layer 0 is always the "all lower layers combined" layer.
Comment: But why, if I put layer 1 or 2 as layer parameter it dont create a file. If I set 0 I succesfully get a pdf but at 1 or 2 I don't.

Converting Layered .ai to PDF via PHP


repotting a dracaena marginata plant

Question: I have had this plant (dracaena marginata) for some time and it is now drooping as it is now 3ft tall.  A new sprout is growing in the same pot.  Is there a way to cut off the tall part of the plant and repot it.  Any suggestions will be greatly appreciated.
Comment: Hi Brenda  it may help to see an image of it.
Answer: It is easy, just start at the top of the stems with leaves and cut the stem with a sterile and sharp knife or blade a few inches down from the part of the stem that has leaves and stick it in a jar with water, changing the water once every week or more often if the water goes cloudy. It should grow some roots over the next 2-4 months.
Next, take 9 inch cuttings of the leafless parts of the stem and lay them flat on  moist gritty well draining cactus mix in a sed tray, These may decide to bud over 6 months but your hope is it will grow some roots first at nodes but the success of this method is about 20-25% max but nothing ventured, nothing gained eh?
Keep taking cuttings until you get to a neater piece of 'stick' and in the next 6 months the old plant will at some point on the remaining stalk(s) begin to throw out some new buds which will then grow into new shoots and stems.
Good luck.

repotting a dracaena marginata plant


Slider Transition clipping

Question: I have a strange issue using jquery cycle. But I also think it might be css related. What happens is on transition to the next slide the incoming slide stops about a quarter of the way, then snaps to the end of the screen completing the scrollHorz transition that cycle2 uses. To get rid of the issue I have to set my screen with pretty wide to stop it from happening. I should also include that the slides are scaled to the browser and it only happens in one direction when the slides are moving right to left.
Answer: Got it. Had to scale the size of the containers to browser size

Slider Transition clipping


Mechanism behind QR code scanning of WhatsApp web/desktop app

Question:
I could not find any answers related to the working mechanism of QR code scanning used on WhatsApp Web.
How does the authentication happen when the phone (any smartphone running WhatsApp) scans the QR code on the browser.
I don't want to know about the technology stack behind them. Like WhatsApp uses modified version of xmpp, uses erlang, uses web technologies like socket.io and ajax for the web version to implement such functionality.
The question might be broad. But I am eager to know about the implementation behind it.
Answer: It works like this :
1- You open the following URL on your browser :  https://web.whatsapp.com/
2- The Browser loads the page with all sorts of JS and CSS stuff , but also opens a WebSocket    ( wss://w4.web.whatsapp.com/ws )  - Check this image :

2.1- Every 20000 milliseconds you see traffic on the WebSocket for a refresh on the QR code you have on you screen. This is sent by the Server to the Browser, throught the WebSocket (WS we call it from now onwards)

2.2- On each QR Code refresh received on the WS , your browser does a GET request for the new QR Code in BASE64 encode .
2.3 - Notice that this specific WS that the server has open between the Server and the Browser is associated with the unique QR code !!! So, knowing the QR code, the server knows which WS is associated with it!
----  At this stage your browser is ready do the WhatsApp App work , but it does not know what is your ID (Whatsapp identifier which is your mobile number) , because it can't really get you phone number from thin air .
It also does not require you to type it, because the server wouldn't be sure that the number really belongs to you .
So, to let the Servers know that the WS session belongs to a specific phone, you need to use the phone for QR reading
3- You grab your phone, which is authenticated (otherwise you wouldn't have access to the section to scan QR codes) , and do the QR Code reading thing
4- When your mobile reads the QR code, it contacts the WhatsApp servers and tells them : My number is XXXX ,  My auth creds are YYYYY , and the WS associated with this QR code can now receive my DATA
5- The server now knows that it can direct Traffic to the specific WS socket  that belongs to that QR Code, and does so !
6- On the Browser WS you can see the Server sending data regarding the user, regarding the conversations that you are having and which photo thumbnails to go and Grab.

7- The Browser gets this data from the WebSocket , and makes the corresponding GET requests to get the Thumbs, and other resources it needs, like an MP3 for notifications
7.1 - The WS listener on the Browser also makes Javascript calls, on the javascript files that were received at step 1 , to redraw the page DOM with the new interface .
8- The interface is now redraw to look like the WhatsApp app , and you continue to receive data on the WS , and sending when needed, and updates are made to the interface as data is arriving on the WS .
That is it.
Using Chrome, and Developer tools , you can see all this happening live. You can also see the WS communication (most of it, the binary frames you would need another tool ) and see what is happening all steps of the way.
Also:

Check a complete Tutorial on this : HERE
Source code for the Tutorial : Android Client
Source code for the Tutorial : Java Play Server
Comment: That is correct. I just didn't think that bit was relevant to the question, but it is fairly easy. The Whatapp APP keeps sending heartbeat to the server, a keep alive ping of sorts, so if you turn off the phone that keep alive ping stops, when it stops, the server stops delivering to the phone and the WS.  The WS can stay alive, just no data is received there.  Something of this sort.   The question was "Mechanism behind QR code scanning of whatsapp webapp" which is what  described , not the complete functioning of a whatapp mobile app and web app.
Comment: But, your phone also needs to be connected to the internet all the time to use whatsapp web. Where is that dependency used? Like when you say you continue to receive data on the WS, but if you disconnect your phone, you don't receive any data on the WS.
Comment: would you please elaborate on points 5 and 6 about how the web browser can be authenticated after getting information through a websocket? Thank you.
Comment: @ĐứcThanhNguyễn  I don't understand your question. There is nothing to elaborate. The Server creates a WS and a QR Code .  That is a Pair , if you know the QR code, you know the WS associated.  If a phone takes a picture of a QR Code, and send to the server : I took the picture of this QR Code, then you know what WS you should associate with that Phone,  ..... because the QR code is the same.    Also, I've provided both code and a complete tutorial explaining this in more detail.
Answer: It uses something like below.

Whatsapp web application is opened by user via web browser.
Server creates a UNIQUE token (number) and embeds that number in QR-Code
Whatsapp phone application reads QR-Code and decodes token.
Whatsapp phone application sends information about its current user and this newly read token to whatsapp server.
Whatsapp server matches token (+ phone app user information) with web browser.
It automatically authenticates user and open new web page with his/her information on it.
Comment: That is true When the user directly interacts with the browser (form loads -> user enters credentials -> presses login button -> gets redirected to dashboard). But here only QR code gets rendered then interaction happens between the phone and server.Once authenticated on server without any user interaction with browser.The browser is redirected to dashboard.
Comment: For Example if thousands of tokens are generated by the server when each user opens the web.whatsapp.com.As HTTP are stateless.How does the server initiate and find that particular user's browser window associated with that particular token.
Comment: @dewnor how stack overflow differentiate between you and me. This is similar, we each have different tokens.
Comment: wrt above comment please elaborate point 5 and 6 of your answer
Answer: there are two ways to implement QR login like whatsapp

Ajax polling
Websocket

I've made demos in php of
both

QR Login with Websocket

QR Login with Ajax polling

Note: Websocket apporach requires 2 port, one for main app and other for listening websocket connection.
Http server and websocket server can run on same port too with some proxy or some other way.
I found an example in nodejs too
QR login Websocket with nodejs


Efficient frequency offset estimation of known signals

Question: Let's say that my receiver will be receiving known data signals that range from the very simple (tone) to the complex (known data sequence that is modulated (PSK/QAM/OFDM/etc.)).  What are the most computationally efficient ways to get a reasonably accurate estimate of the frequency offset?
Comment: @Mohammad I know that I can do it that way, I'm just not sure that it's a computationally efficient way of doing it.  At the risk of beating a dead horse, the key, for me, is computational efficiency.
Comment: Have you tried plotting the I and Q results sample by sample against each other and looking at the rotation over time? That is, for every I(n) and Q(n) (n being the sample time number), plot those two values one on x axis the other on the y axis. Over time, you will notice they are rotating along the unit circle. The rate of rotation is your frequency offset.
Comment: Not to say that there arent other methods, but I do not think that this way would necessarily be computationally intensive. Afterall, all you are doing it comparing I and Q values (that have to be computed anyway since you are demodulating I imagine), and just comparing the current I/Q values to a previous I/Q value some time back. Perhaps there is something I am not aware of per your project that is making this intensive computationally... how limited is your computing power for this task?
Comment: @Mohammad I suppose you're right- it's not that intensive.  My particular situation is that I am looking at implementing packetization and sometimes demodulation of GSM (tone) and WiFi (PSK, OFDM) signals in an FPGA.  I guess I was hoping that there was a clever way of doing the frequency offset estimation at the same time as doing the signal detection, which I will probably do using FFT-based correlations.
Comment: Hmm, well I searched around and I have heard of some methods that use auto-correlation to do pitch detection, (see here: http://dsp.stackexchange.com/questions/1317/is-there-an-algorithm-for-finding-a-frequency-without-dft-or-fft), ... and since you are doing cross-cors it might be worth looking at. (Cntrl-F for 'autocorrelation' and look at @Phonon's answer).
Comment: http://meta.dsp.stackexchange.com/questions/165/should-we-conciously-manage-comments-clutter
Answer: Time aligned
If the signals are time aligned, you can conjugate-multiply the received signal with the reference signal and look for the dominant frequency.
Max-Likelihood estimation of the frequency shift and complex gain of a known signal in Gaussian Noise
Let $\vec r$ be the noisy observation of a frequency translated version of a sent $\vec x$ with unknown gain.
Here, let us consider the channel $\mathbf A \in \Gamma$
$$
\vec r = \mathbf A \vec x + \vec w  \in \mathbf C^N \\
[\mathbf A]_{nn} = \rho \exp(\omega n) , \rho \in \mathbf C^N , \omega \in \mathbf R \\
[\mathbf A]_{mn} = 0, \forall m \ne n  \\
p(\vec w|\tau) \propto \exp\left( \frac {-\| \vec w \|^2} {\tau}  \right)
\\
\mathbf A^* \triangleq
\operatorname*{argmax}_{\mathbf A}
\max_{\tau}
\underbrace{p(\vec r| \mathbf A,\vec x ,\tau)}_{  \propto \exp \left( \frac {-\| \mathbf A \vec x - \vec r \|^2} {\tau}  \right) }
\\
\mathbf A^* =
\operatorname*{argmax}_{\mathbf A}
\underbrace{
-\| \mathbf A \vec x - \vec r \|^2
}_{
\triangleq f(\mathbf A)
}
\\
f(\mathbf A)
=
- (\mathbf A \vec x - \vec r )^H
(\mathbf A \vec x - \vec r )
\\
= - \vec x^H
\underbrace {\mathbf A^H\mathbf A }_{|\rho|^2 \mathbf I
}
\vec x
+ 2\mathop{re}
(\mathbf A \vec x)^H \vec r
-
\underbrace
{\vec r^H \vec r}_{
\|\vec r\|^2}
$$
Notice the first and third terms have no dependence on frequency $\omega$ nor the phase of $\rho$.  So we simply need to find the frequency that best aligns $\vec x,\vec r$.  That will imply the phase.
$$
\omega^* = \operatorname*{argmax} \sum_n |\exp(-j\omega n) \bar {x_n} r_n|^2
$$
One can use an FFT or some such frequency estimator to recover the dominant frequency
Not Time-Aligned
If the signals are not time-aligned, then you've got a time and frequency search problem on your hand.  With low SNR, this is essentially the problem solved by the cross-ambiguity function (CAF).  If you've got several dB of margin you can take a shortcut.
If you have a reference signal with some AM variation; you can time-align first by AM detecting both signals and then correlating your input by the reference AM.  If your  reference signal doesn't have much amplitude variation, but its spectrum is "spikey" you might be able to correlate the magnitude spectra of the received and reference.  This is the same trick applied in the frequency domain, rather than time domain.
With the exception of the CAF, these are all fairly cheap operations.
Comment: Yes. If the result from the conjugate-multiply has linear phase, then it is tone-like in nature. That will correspond to a thin peak in the frequency domain, as you noted.
Comment: I'm not quite following the "conjugate-multiply" method.  I assume you are talking about multiplying the two sequences sample-by-sample, with one of them conjugated.  Each product, then, would have a phase of n*fo + phi, where n is the sample number, fo is the offset frequency, and phi is the starting phase offset.  Should I diff the phases to get the offset frequency phase increment?
Comment: Yes. If there is a constant phase offset, then the result from the conjugate-multiply operation will have linear phase. The slope of that line is the frequency offset, so differentiating will give you that.
Comment: It occurred to me that we multiply in the frequency domain to correlate/convolve in the time domain.  By conjugate-multiplying in the time domain we are cross-correlating in the frequency domain.  If we FFT the conjugate-multiply results we should have the frequency domain cross-correlation, right?  The peak of that cross-correlation should indicate what the frequency offset is.
Comment: Is the edited answer a bit clearer?
Comment: @MarkBorgerding Could you please expand on the last paragraph starting with "If you have a reference signal with some AM variation; you can time-align first by AM detecting both signals and then correlating your input by the reference AM.". Thanks
Comment: @Mohammed the magnitude of a complex signal is unaffected by frequency translation.
Comment: Performance of this algorithm degrades especially in lower SNR scenario. Is there any way to make it robust against white gaussian noise?
Comment: Oh wow.  I think that was more heuristic than thoughtful.  I will edit.


saying aleinu with a minyon obligation

Question: My Rabbi said that it is a halachah to interrupt (most places) in prayer to say aleinu together with a minyon. What is the source for this?
Comment: there is no halokho to so oleinu at all except for rosh hashono
Comment: @MoriDoweedhYaa3qob And Yom Kippur in a Yovel.
Comment: Closely related: http://judaism.stackexchange.com/q/22674
Answer: I assume he means places where one is allowed to interrupt anyway (i.e., not in the middle of a bracha, pesukei dzimra, birchat shma, shemoneh esrei, etc.) in which case his source is presumably e.g. the Mishna Brurah 65:9 or Yalkut Yosef (Tefillah vol 2, p. 462) where they rule that when the congregation is saying "Aleinu...", one should also say it along with them (see also: http://halachipedia.com/index.php?title=Tachanun,_Ashrei,_Aleinu,_Shir_Shel_Yom ).

saying aleinu with a minyon obligation


RESTful post in Oracle Service Bus

Question: Does anyone know how to create a proxy service that will handle this sort of thing?
What I'm looking for is a path parameter and a post body being formatted similar to this:
POST www.myurl.com/{123}
Post body:
myId=1&myOtherId=2
I am currently passing in an XML document and I'm doing an insert on the http:relative-URI element in the transport. This seems to work.
I am also currently doing an insert on the http:query-parameters for my post body name/value pairs.
I am inserting these on the outbound variable. When I debug, both are showing up and I'm contacting the REST service. I am getting a 400 -- Bad Request error. This happens when the post body is not configured correctly.
Any ideas how to do this?
Answer: If you are just Posting an XML, then while creating Proxy Service, Select Service Type as Any XML.

RESTful post in Oracle Service Bus


Creating shared data transfer classes generated by svcutil /datacontractonly and used in WCF web programming model

Question: I am creating a set of Web Services which share some common xml defined data elements.
I want to separate these entities into a common schema, service 1 specific schema, service 2 specific schema etc...  the service specific schemas will reference the common schema.  I
want to use svcutil /datacontractonly to generate classes that can be used to create and serialize these objects using the WCF web programming model.  The problem I am having is that
when I import the common schema into the service specific schemas the common schema entity classes are included in the code generated for the service specific classes.  This causes
compile errors later when a single client attempts to use the generated entity classes for two services which both use the common schema entities.  Is there anyway to get svcutil to only include the service specific entities in the generated code?  I'd just like to have a common dll which includes the common schema entities which the services may reference.
Answer: I think this is what you need (on svcutil options)
/reference:
References types in the specified assembly. When generating clients, use this option to specify assemblies that might contain types that represent the metadata being imported.
You cannot specify message contracts and XmlSerializer types using this switch.
If DateTimeOffset referenced, this type is used instead of generating a new type. If the application is written using .NET Framework 3.5, SvcUtil.exe references DateTimeOffset automatically.
Short Form: /r
here is where I found it


Why are parser generators used?

Question: I saw some projects require BISON to generate C++ code. What is the advantage of having BISON/Yacc etc. generate C/C++ code instead of writing it yourself?
Answer: The most important thing about BISON and YACC is that they generate a state machine which would parse exactly your grammar. This is for speed reason, since complexity of generated code is not O(n) with n = number of rules as it would be in most first-attempt implementations.
The state machine approach causes the number of states spawned to be very high  and thus it would be very error prone to write that code. Manteinance of that code would also be an hell (where hell = I would quit the job if someone suggested me to do that).
Bison and Yacc make you concentrate on the grammar instead of its implementation.
Comment: +1 for that last sentence.
Answer: The same reason that you don't write your own hashmap, or smart pointer, or threading library.  Its much better use of your time to use something that is already written and debugged that do it yourself.  There will always be certain people and certain situations where the best option is to roll your own, but these are rare.  Probably more rare than most people accept.
For parsers in particular, it is fairly easy to write a parser that works most of the time.  It is tricky to write one that work correctly for all input, including malformed input, and is easy to modify.  Its also tempting to impose some strange syntax on the input to make it east to parse, at the expense of making it harder to create input files.
For C++, I've had good results with Boost::spirit.  Its a parser framework that, through the use of lots of template magic, lets you embed BNF directly into your C++ code.  It has a bit of a learning curve, but once you wrap your mind around it, it make it easy to construct parsers for complex languages.
Comment: +1 for mentionning boost::spirit. I also had good result with it. Well I'm not sure if it is ready for big industrial use (problem with crashing intellisense and long compile time with the version I used) but for small/medium use it's just awesome.
Comment: I use emacs+gcc, so haven't noticed the intellisense problem.  The long compile times I solved by making the parser modular, and constructing parsers in source files, not headers.  Then, as long as you aren't changing the parser itself, you only pay the compile time cost once.
Answer: Two reasons:
Clarity: A parser generator can use a language (say, ABNF) that is geared towards the problem, that of describing a grammar. (Some languages arguably can get away with not needing a separate language: just build a DSL in the host language.)
Ease of use: You don't have to know how to write a parser yourself. Would you use a recursive descent parser? a pack-rat parser? etc. And do you care, if you just want to parse a SIP message?
Answer: If you know the grammar you need to parse, it's much faster to get working code by simply feeding that grammar to a parser generator and use suitable call-outs from that than to hand-code a parser.
If, however, you have a poorly-described file format you need to parse, it may be about as much work to hand-roll a parser as it would be to figure out the grammar, describe it to the parser generator and then get a parser.
Hopefully, you're closer to the first paragraph than the second.

Why are parser generators used?


Automatically rsync when hotplugging a sata drive(bay not esata)

Question: to keep up on my backups I want to run a specific rsync command when I insert a specific sata hard drive(s) into any or all of my hotswap bays. Would this be done using uuids somehow to keep track of the drives? whenever I search I find udev for usb drives, can this work here as well?
Answer: I use a simple udev rule for this. The backup drive is marked with a specific volume label (use tune2fs to set it). The udev rule starts a script:
<code>$ cat /etc/udev/rules.d/90-backup.rules
ACTION=="add", ENV{ID_FS_LABEL}=="backup", RUN+="/usr/local/bin/backup.sh"
</code>
(you can use ENV{ID_FS_UUID}="some-uuid" if you'd prefer not to use volume labels)
The script just runs the rsync:
<code>$ cat /usr/local/bin/backup.sh
#!/bin/bash

mnt=/media/backup

(
mount $mnt
rsync -avx --exclude lost+found /home/ $mnt/backup/
umount $mnt
) > /dev/null 2>&1 &
</code>
udev expects the RUN="" command to be short-lived, so the script runs the rsync in the background.
This will work for any type of drive and/or interface - as long as udev gets notification that the drive has been added.


Android HTC Flyer - Capturing stylus with MotionEvents

Question: I'm developing an app which is designed to capture writing on the canvas. The app is designed for use with HTC Flyer (Android 2.3.3).
This device already has Scribbler installed, so I have disabled "Auto launch Scribbler mode" but left "Pen history for each app" checked.
In my tests, I have found the app can detect my fingers on the touchscreen but not the stylus. I pressed a combination of buttons on stylus to no avail.
I have based the code on TouchPaint from Android Developers: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/TouchPaint.html
I did not import the package as described in the above code
com.example.android.apis.graphics;

In my Eclipse IDE, it reported the following as a problem suggesting I should remove the Override attribute.
@Override
public boolean onHoverEvent(MotionEvent event) {
    return onTouchOrHoverEvent(event, false /*isTouch*/);
}

So I did.
I have added the following to the manifest.
<uses-configuration android:reqTouchScreen="stylus"/>
<uses-configuration android:reqTouchScreen="finger"/>

The app can detect my finger movements on the touchscreen but never my stylus. Why?
I also noted that in Android Developers guide the MotionEvents refers to getToolType but I cannot see it in my "Intellisense" in Eclipse.
http://developer.android.com/reference/android/view/MotionEvent.html#getToolType%28int%29
The method getToolType is not available in my Android code. I thought I could use this method to check the type of the touch input e.g a finger or a stylus.
I also added a onTouchListener for the PaintView (based on TouchPaint code).
this.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return touchSurface(v, event);
    }
});

touchSurface code
private boolean touchSurface(View v, MotionEvent event) {
            boolean complete = true;
            int pAction = event.getAction();
            int pActionIndex = event.getActionIndex();

            Log.i("SignName", "touchSurface event fired.");
            Log.i("SignName", "Pointer Action: " + pAction + ", pActionIndex: " + pActionIndex);

            return complete;
        }

When I use my finger, the above event is fired. When I use a stylus, it's not fired. Why?
I wonder if this problem is isolated to the HTC Flyer, it's because it has a Scribbler app which overrides my app settings or my code is wrong.
Can you please help me?
(Update: 27th April 2012)
I found what the problem was. It was the dedicated stylus HTC Flyer that caused the confusion.
I thought if this stylus didn't work, then any other stylus won't work too. However, I did try a different stylus and it worked.
Thanks for your help, though.
Comment: Build and examine some of the HTC examples which use the pen.
Answer: first off, you should update your Flyer to Honeycomb (Android 3.2), also this example is specific to ICS (Android 4), but you can run this example by using a compatibility library and making some minor changes to code, more information will be available at http://htcdev.com
Comment: Thanks for your help. I found what the problem was. It was the dedicated Stylus that came with the Flyer.


Root document is not readable

Question: I'm receiving this message "Root document is not readable" when I try to run a document that I've created in TeXworks. (MiKtex)
The document type is a report and has several pages of tables with figures, and equations.
I've ran this document and it has worked fine before. I don't think I have made any changes to the code so that this could occur.
Any ideas on how to fix?
Answer: Solved,
I simply copied all of the code into a new blank document and then it worked!

Root document is not readable