Unity - Access animation clips/motion of an animator

Question: So I have an animator on my GameObject. I need to change the animation clip/motion of different states in my animator to the one I assign in my EditorGUILayout.ObjectField. Problem is, I have no idea how to access those clips. This is purely Editor Scripting.
Comment: You want to change it or replace it? You can create different states machine as per your requirements and use it through code.
Answer:
This is purely Editor Scripting.

Yes, you can do it. But take note that manipulating Animator's state machine and clip inside ONLY possible in Editor. (For automation editing/scripting, etc) It is very complicate process but I will try to cover as much as I can.
For side note, AnimationClipOverrides in Dmitri's answer is for game runtime. It 'overrides' the original animation clip to another set of animation clips.

Obtain reference to Editor's Animator
First in editor script or EditorGUI, obtain reference to UnityEditor.Animations.AnimatorController you are going to wotk with by any method, for example via field in custom EditorWindow:
using UnityEditor;
using UnityEditor.Animations;

AnimatorController m_CurrentAnimator;
m_CurrentAnimator = (AnimatorController)EditorGUILayout.ObjectField( "Animator", m_CurrentAnimator, typeof( AnimatorController ), false );

Access layer and get all states inside
First is layer that you have to peel off, for simplicity, I will operate on layer 0. Then there will be AnimatorStateMachine inside it, I will use List to collect all states recursively. (also travel through nesting sub-statemachines)
AnimatorControllerLayer[] layers = m_CurrentAnimator.layers;
AnimatorControllerLayer workingLayer = layers[0];

List<AnimatorState> stateList = _ExpandStatesInLayer( sourceStateInfoLayer.stateMachine );

where
List<AnimatorState> _ExpandStatesInLayer( AnimatorStateMachine sm, List<AnimatorState> collector = null )
{
    if( collector == null )
        collector = new List<AnimatorState>( );

    foreach( var state in sm.states )
    {
        collector.Add( state.state );

        foreach( var subSm in sm.stateMachines ) // Jump into nested state machine
            _ExpandStatesInLayer( subSm.stateMachine, collector );
    }
    return collector;
}

Peek into state's content (AnimationClip/BlendTree)
After long fight, now we can see contents in each state. The code is self explained. It is up to you how to modify these state.
foreach( var state in stateList )
{
    Motion m = state.motion;
    if( m is AnimationClip ) // It is single animation clip
        Debug.Log( "clip " + m.name );
    if( m is BlendTree ) // It is blendtree with multiple clips!
        Debug.Log( "tree " + m.name );

    state.motion = null; // TODO: Set something else to it.
}

Dont forget a call to UnityEditor.EditorUtility.SetDirty if you actually modify it. Or better alternative UnityEditor.Undo.RecordObject. (It also set dirty state)
If layer is SYNC layer (copy states from source layer), the workflow will be a bit different when getting state list and getting motion attached to it. It is not covered in this answer. You can lookup potential API from related class documents.
Answer: You cannot access the clip in the animator directly. Here is an example of how I used clip replacement. For more information, look into Unity's documents. https://docs.unity3d.com/ScriptReference/AnimatorOverrideController.ApplyOverrides.html
using UnityEngine;
using System.Collections.Generic;

public class AnimationClipOverrides : List<KeyValuePair<AnimationClip, AnimationClip>>
{
    public AnimationClipOverrides(int capacity) : base(capacity) { }

    public AnimationClip this[string name]
    {
        get { return this.Find(x => x.Key.name.Equals(name)).Value; }
        set
        {
            int index = this.FindIndex(x => x.Key.name.Equals(name));
            if (index != -1)
                this[index] = new KeyValuePair<AnimationClip, AnimationClip>(this[index].Key, value);
        }
    }
}

public class PlayerScript : MonoBehaviour
{
    [SerializeField]
    private AnimationClip[] m_Animations;

    private Animator anim;
    private AnimatorOverrideController animatorOverrideController;
    private AnimationClipOverrides clipOverrides;

    void Start()
    {
        anim = GetComponent<Animator>();
        animatorOverrideController = new AnimatorOverrideController(anim.runtimeAnimatorController);
        anim.runtimeAnimatorController = animatorOverrideController;

        clipOverrides = new AnimationClipOverrides(animatorOverrideController.overridesCount);
        animatorOverrideController.GetOverrides(clipOverrides);
    }

    public void Play(int numberClip)
    {
        clipOverrides["myAnimation"/*name *.anim file in State inspector*/] = m_Animations[numberClip];
        animatorOverrideController.ApplyOverrides(clipOverrides);
        anim.Play("start");

    }
}


Cardinality of $\sigma$-algebra generated by an infinite family of sets

Question: Let $\mathcal{F}$ be an infinite family of subset of $X$ of cardinality $\kappa$ (thus $\kappa$ is an infinite cardinal). From the recursive description of generated $\sigma$-algebra, I know that the $\sigma$-algebra $\langle \mathcal{F}\rangle$ which is generated by $\mathcal{F}$ has cardinality at most $\kappa^{\aleph_0}$. On the other hand, since $\langle \mathcal{F}\rangle $ contains $\mathcal{F}$,  $\langle \mathcal{F}\rangle$ has cardinality at least $\kappa$. Thus we have $\kappa\leq |\langle \mathcal{F}\rangle |\leq \kappa^{\aleph_0}$. Is is true that $|\langle \mathcal{F}\rangle |=\kappa^{\aleph_0}$? I'm not very familiar with cardinal arithmetic, thanks for any help.
Comment: Try to take $\mathcal {F} $ to be a sigma algebra itself. Then it is obvious what the cardinality of the generated sigma algebra is.
Comment: @PhoemueX In this case, I think we have $\kappa^{\aleph_0}=\kappa$. Note that there exists no $\sigma$-algebra with cardinality $\aleph_0$. Thus if $\mathcal{F}$ itself is a $\sigma$-algebra, it must has cardinality greater than $\aleph_0$. In this case, we may have $\kappa=\kappa^{\aleph_0}$. Indeed, if $\kappa=c$, the equality holds.
Comment: Deciding whether $\kappa =\kappa^\aleph_0$ seems to be a difficult problem (http://math.stackexchange.com/questions/184746/the-cardinality-of-the-set-of-countably-infinite-subsets-of-an-infinite-set), possibly even undecidable in ZFC. If we assume the generalized continuum hypothesis, this holds for all uncountable sets. But in general, it seems to be hard. Note also that every infinite sigma algebra has at least the cardinality of the continuum.
Answer: Yes. If $B$ is a sigma complete infinite boolean algebra, then $|B| = |B|^{\aleph_0}$. You can find a proof in the Handbook of Boolean algebra Vol. 1, theorem 12.2.
Comment: Thanks for your answer. From wikipedia https://en.wikipedia.org/wiki/Complete_Boolean_algebra, I know what is a complete Boolean algebra. But what does sigma complete infinite Bool algebra mean?
Comment: It means that every countable subset of $B$ has a supremum. So every sigma algebra is an example.
Comment: It's a weaker notion than complete  Boolean algebra, isn't it?
Comment: Yes but the proof just uses countable completeness.


installing GWT plugins to eclipse

Question: i started to explore GWT yesterday it self and was going basic tutorial in google documentation, I've downloaded GWT ran a sample project without Eclipse as the tutorial stated and then started to setup Eclipse.
I'm using Eclipse Galileo and according to given instructions i followed the steps and when i was installing GWT plug-in for eclipse i came across an error, so i re ran the plug-in installation and came across the same error again, this is my 3rd time of that procedure. so i turned on to you, I've pasted the error messages below, some one please help me out.
regards,
rangana
An error occurred while collecting items to be installed
session context was:(profile=epp.package.java, phase=org.eclipse.equinox.internal.provisional.p2.engine.phases.Collect, operand=, action=).
Unable to read repository at http://dl.google.com/eclipse/plugin/3.5/plugins/com.google.appengine.eclipse.sdkbundle.1.3.3_1.3.3.v201004231111.jar.
Read timed out
Unable to read repository at http://dl.google.com/eclipse/plugin/3.5/plugins/com.google.gwt.eclipse.sdkbundle.2.0.3_2.0.3.v201002191036.jar.
Read timed out
Comment: Why did you make this question CW?
Answer: Have you tried the alternative installation procedure (from a zip file)?
Comment: i didn't tried the .zip file installation, i will try it out, thank you!
Answer: Here is the work around :

Separately download the jar files for which read timeout is hapenning.
In this case download
com.google.gwt.eclipse.sdkbundle.2.0.3_2.0.3.v201002191036.jar.
com.google.appengine.eclipse.sdkbundle.1.3.3_1.3.3.v201004231111.jar.
using above url.
Note: both jars are above 80MB and takes a while for download.
copy the jars to plugin folder of eclipse
resume plugin installation once again.

installing GWT plugins to eclipse


How to delete an app from iOS Xcode Simulator?

Question: Just in case, we can delete apps by resetting contents and settings but an individual app could also be deleted from simulator in Xcode 7. This is not the case in Xcode 8. How can this be achieved? I have a forced touch trackpad, does it affect deleting the app from simulator?
Answer: I struggled with this too for a while until I figured it out. I'm surprised at how hard it is to find information about this...
As you mentioned, this is only an issue when using a trackpad that supports Force Click. @pingkai.tse's answer is a good one, but for me turning off "Use TrackPad Force" does not persist - I have to turn it off every time I restart the simulator.
The trick is to click without triggering a Force Click gesture. It's hard at first, but after some practice you'll get the hang of it. On the trackpad, click very lightly on the app and hold long enough to trigger the long press. While holding, if you see the text starting to blur you are applying too much pressure and are instead triggering a Force Click.
Comment: It took me a few tries to get it right! But finally got the hang of it :)
Comment: This is so great.... one of the more seemingly superstitious answers I've ever seen on StackOverflow but works perfectly!
Answer:
Open the Simulator.
Find the "Hardware" tab on the tool view.
Undo "Touch Pressure & Use TrackPad Force".
Answer: For iOS 11+ simulator you should long press the app icon :)
For iOS 13+ simulator you can long press the app icon. When "Rearrange apps" suggestion appears you can tap on it or continue holding the mouse button until its automatically applied
Before iOS 11: hold alt, then press the touch pad.
Comment: Exactly! Shift + Option (which is alt) lights up the "spots", then you can tap and hold over the app you want to delete. Icons start shaking as you would expect. Then Shift + Command + H to restore order.
Comment: It's also worth emphasising that you have to "click" the Trackpad so you get haptic feedback. If you have _Tap to click_ turned on, a long tap doesn't do anything. It has to be hard enough to count as a "click".
Comment: @amagain you should change the accepted answer to this
Answer: Step 1: On simulator, go to home screen with command + shift + H
Step 2: Click + hold on the app icon, release when an "x" button appears at the top left of the icon
Step 3: Click on the "x" button and choose Delete for any apps you want to delete
Step 4: When finished, press command + shift + H again to return the simulator to its normal state
With a Force Touch trackpad, just make sure you don't press it all the way down when clicking on the icon.  Use a normal click.
Comment: That works only with a mouse, using a force touch trackpad on a macbook pro doesn't replicate the same result.
Answer: 1) Click on simulator
2) On the top click on Hardware and then click on Erase all content and settings
Answer: This will uninstall the app from the booted simulator.
xcrun simctl uninstall booted com.app.identifier

Based on simctl I have created a script RemoveIOSAppsScript that deletes all the non apple apps from the booted simulator.
Answer: You have 3d touch enabled, tap and hold "VERY" lightly (just feel the click, than maintain that force or less) on the app icon on the Simulator's home... Or in the System preferences, disable the "Force click and haptic feedback", than go back on the Simulator's home and keep clicked on app icon to delete it.
I prefere the second because I can't find useful this feature of my mac.
Answer:
press command + space and search the X-code
then press the enter then Opening Simulator.
in Simulator top of the bar Find the "Hardware" tab on the tool view.
click on Undo "Touch Pressure & Use TrackPad Force".
Answer: Just click and hold the app icon with the force touch track pad enabled... Newer MBPs work well with the simulator in my experience. If not follow the advice above.
Answer: For appleTv simulator:

Press Enter over the app you want to remove.
When it starts moving, tap on Space
You will see a new menu with the delete option there!


Reduce sizing of molecule - Oxygen

Question: Can the size of molecule oxygen reduce smaller? If yes, how is that possible? Is it related to proton and electron surrounding the nucleus?
Answer: Surprisingly enough, the answer is yes, though it would be extremely difficult in practice to reduce the size of a molecule as large as $\ce{O_2}$ by the method I will describe here.
First, I must be clear that "shrinking" as seen in many science-fiction stories is completely impossible. Size is not some arbitrarily determined parameter which you can change with a ray gun!
Though the concept of size is a little fuzzy at atomic/subatomic scales, we know it is the valence electrons who are responsible for determining the distance scales in atoms and molecules (since they're the farthest from the nuclei). After solving the Schrödinger equation for a system, one finds that the electrons are concentrated in regions around the nuclei called orbitals. A meaningful definition of size for these orbitals implies that they are around 100 picometres or more across, conveniently described as twice the Bohr radius.
Usually, this would be the limit for any atom or molecule. However, nature has a rather curious quirk. We have discovered that all atoms in the Universe involved in chemistry are made of electrons, protons and neutrons (the latter two being themselves made of different combinations of up quarks and down quarks). However, there are more subatomic particles out there, and there is nothing to stop (exotic) atoms being made out of these other subatomic particles, as long as they are combined in the right way.
Physics doesn't yet understand why, but the fundamental subatomic particles in the Universe come in three generations. That is, there are groups of particles which behave exactly the same (have the same spin, electric charge, among other parameters), but differ only in their mass. In particular, electrons are just one type in a group of three types of particles called leptons. The other types are called muons and taus (or tauons). Again, all leptons share exactly the same properties, except for mass; the muon is approximately 200 times heavier than the electron, while the tau is around 3500 times heavier. We don't naturally see atoms containing these heavier cousins of the electron because they decay very quickly and are hence much rarer. Even though the muon is one of the most stable subatomic particles, its mean lifetime is a mere $2.2\ \mu s$, and the tau is much more unstable still. In the case of the muon, however, it is long-lived enough to produce it artificially and get some chemistry done.
If one were to mix muons with normal atomic nuclei in an appropriate chamber, then for a fleeting moment it would be possible to make atoms and molecules where all the electrons are replaced with muons. The resulting atoms/molecules would have muon orbitals instead of electron orbitals. By solving the Schrödinger equation for muons instead of electrons (changing $m_e$ for $m_{\mu}\approx200\ m_e$), the Bohr radius becomes around 200 times smaller and as a direct consequence the muon orbitals are smaller by approximately the same factor. Thus, an oxygen atom where all electrons have been replaced by muons will be about 1/200th the size, but will display almost exactly the same chemistry; two such exotic atoms would be expected to combine exactly as normal oxygen atoms do, creating an $\ce{O_2}$ molecule with sixteen muons instead of electrons, with an expected bond length of around $0.6\ pm$ instead of the usual $121\ pm$.
This may all seem theoretical, but muonic atoms have already been made in the laboratory before. Given the difficulties in producing and manipulating muons in their short lifespan, the only atoms produced as of yet seem to be muonic hydrogen (where the single electron is replaced by a muon) and quite recently muonic helium where only one of two electrons was replaced with a muon. In the latter case, the mix of electrons and muons makes the atom behave chemically quite differently from regular helium or doubly-muonic helium.
Answer: If you could eliminate the Pauli exclusion principle then the size of all atoms and molecules would collapse.    Because electrons cannot have the same four quantum numbers in an atom, $n$, $l$, $m_l$, and $m_s$, the electrons in multi-electron atoms and molecules are forced to occupy the higher energy and larger radius orbitals.   More electrons: bigger atom.
You can read more about Pauli exclusion principle here:
http://www.grandinetti.org/Teaching/Chem121/Lectures/QuantumNumbers
and atomic radii trends here:
http://www.grandinetti.org/Teaching/Chem121/Lectures/MultiElectronAtoms
and here:
http://www.grandinetti.org/Teaching/Chem121/Lectures/AtomicRadii
Comment: Meaning that less electron will result to smaller radius orbitals. And what is the practical method to do that? Can the Far Infra Red energy make it done?
Comment: There is none.  You can't violate the Pauli exclusion principle any more than you can defy gravity.  Sorry.
Answer: This is going to sound simplistic relative to the previous 2 answers, but what about putting a crystal of solid oxygen into an anvil at a temperature below its solidification point, and compressing it. Phase diagrams (e.g. http://commons.wikimedia.org/wiki/File:Phase_diagram_of_solid_oxygen.svg) show that oxygen exists in different crystal forms at different temperatures and pressures. It becomes superconducting at low temperatures and high pressures.

Reduce sizing of molecule - Oxygen


How do I find the PDF from a multidimensional CDF with indicator functions?

Question: I have what I'm sure is a very stupid question.
When I have a two-dimensional random variable $\tilde{X}=(X_1,X_2)$ with the cdf $F(x_1,x_2)=(kx_1^2I_{(0,1)}(x_1)+I_{[1,\infty)}(x_1))(kx_2^2I_{(0,1)}(x_2)+I_{[1,\infty)}(x_2))$, how can I calculate the pdf from that? I get that I have to differentiate somehow, but what do I do with the indicator functions?
Comment: If this is homework, please add the `self-study` tag.
Comment: Did you make a typo? For your CDF to be a correct CDF you either need $k\leq 1$ or the boundaries of the indicator function need to relate to $k$.
Answer: Alternative way to describe the CDF without indicator functions
It is common to split up the CDF into cases like for the uniform distribution between $a$ and $b$ you have: $$F_X(x) = \begin{cases} 0 &:& x < a \\
\frac{x-a}{b-a} &:& a\leq x\leq b\\
1 &:& x>b
\end{cases}$$
and the density is the derivative $f_X(x) = {F_X}^\prime(x)$
$$f_X(x) = \begin{cases} 0 &:& x < a \\
\frac{1}{b-a} &:& a\leq x\leq b\\
0 &:& x>b
\end{cases}$$
You can get rid of the indicator in your function by describing it in the format above (only now you have to write the cases based on two variables together).

The derivative of a 2D CDF to obtain a PDF
The CDF is differently defined in a 2D case. One way is like
$$F_{X,Y}(x,y) = P(X\leq x, Y \leq y) = \int_{-\infty}^x\int_{-\infty}^y f_{X,Y}(t,s) ds dt$$
So you need to compute the derivative for both variables
$$\frac{\partial^2}{\partial  x\partial y} F_{X,Y}(x,y) = f_{X,Y}(x,y)$$
Answer: When in doubt, deal with indicator functions (and other awkward creatures like absolute values) by breaking the problem into cases.
Here we have
$$F(x_1,x_2) =
\begin{cases}
(kx_1^2)(kx_2^2)  & \text{if } x_1 \in (0,1) \text{ and } x_2 \in (0,1)\\
kx_1^2 &  \text{if } x_1 \in (0,1) \text{ and } x_2 \gt 1 \\
kx_2^2  & \text{if } x_1 \gt 1 \text{ and } x_2 \in (0,1)\\
1  & \text{if } x_1 \gt 1 \text{ and } x_2 \gt 1 \\
\end{cases}$$
Each of these is straightforward to differentiate.
Sometimes you'll be able to consolidate the cases afterwards. Here for instance, $\frac{\partial^2 F}{\partial x \partial y}$ is zero everywhere outside the unit square $0 \le x_1,x_2 \le 1$


What is the origin of "head off" in the sense "to prevent"?

Question: Where does the meaning of "to head off" in the sense

:to turn back or turn aside : block, prevent
// head them off at the pass
// attempts to head off the imminent crisis

(Merriam-Webster)
originate?
Answer: According to the AHD the phrasal verb head off dates back to mid 19th century:

Block the progress or completion of; also, intercept. For example, They worked round the clock to head off the flu epidemic, or Try to head him off before he gets home. [First half of 1800s]

This expression gave rise to head someone off at the pass, which in
Western films meant "to block someone at a mountain pass." It then
became a general colloquialism for intercepting someone, as in Jim is
going to the boss's office-let's head him off at the pass.
Answer: To head off (v.) seems to come from "A heading" - a direction of travel, which became a verb:
OED

†3. Hunting. With reference to a hunted (or occasionally hunting) animal: the action of changing direction suddenly and sharply while running; doubling. Also: an instance of this. Cf. head n.1 47. Obsolete.
1607   E. Topsell Hist. Foure-footed Beastes 152   The nature of this Hare is, sometimes to leape and make headings, sometime to tread softly.

Which then was used in a nautical context as a verb and a noun:

a. intransitive. To move forwards in a specified direction or towards a particular place or thing. Later also more generally: to go, make one's way. Also transitive: to follow (a course, way, etc.) in a specified direction.
1817   A. Delano Narr. Voy. & Trav. Northern & Southern Hemispheres xxiv. 468   I was just heading for the land, when..I saw one of my faithful sailors..making towards me with all possible exertion.

OED has the entry:

to head off

transitive.

a. To move ahead of so as to intercept, or so as to obstruct and cause to turn back or aside.
1825   E. Mackenzie Hist. View Northumberland (ed. 2) II. 144   The fox took towards Rotherbury Forest... Here it appears he was headed off.

Which then gave rise to your "to prevent [something from happening]

b. To stop (a person or thing) from accomplishing some purpose, goal, task, etc.; (also) to anticipate and prevent; to avert.
1866   Missionary Mag. July 232   The Pastors..have failed..to foresee
and head off disaster.
2008   B. G. Ramcharan Preventative Diplomacy at UN 1   Wherever
feasible, everything possible should be done to head off a conflict or
disaster.


Does setting a connection speed in Steam limit bandwidth usage?

Question: I always assumed that the speed setting is only informational and is used for download time estimates. I have never seen anything that would suggest otherwise - until I read this answer. I still don't believe that it is used as a cap; however I also think the remaining time estimate is computed from the current speed. How it really is?
Comment: A supplementary question might then be, if it _is_ computed from the current speed, what is that setting used for?
Answer: I don't believe that the Steam connection settings are used in any meaningful way to effect download speeds.  I know they are part of the Steam Hardware Survey, but your download speed is simply a factor of the maximum speed your connection to the Steam servers can sustain.
The "Time Left" is a reflection of the amount of data left to transfer, and recent instantaneous speeds between your machine and the Steam servers.
Comment: So it's what I thought; I just forgot about the hardware survey. Thanks. :)


Two Websites, two directories, two domains, one IP

Question: I am hosting two separate sites with two separate domain names on the same server. Without using some kind of NAT forwarding, how can I set up my apache server so that, depending on which domain is used, the index.html file from a different directory is referenced?
Comment: Beware ISP's that will be blocking you from serving a website from your home.
Comment: Also beware dynamic IP addresses. See http://www.dyndns.com/ for one solution to the problem of changing home IP addresses.
Answer: This question will probably be migrated to Server Fault shortly, but the basic answer is that you need to set up a Virtual Host for each of the domain names. This page has a thorough description but a basic example would be:
<code><VirtualHost *>
   DocumentRoot /path/to/site1
   ServerName site1.com
</VirtualHost>

<VirtualHost *>
   DocumentRoot /path/to/site2
   ServerName domain2.com
</VirtualHost>
</code>
Answer: Check out Apache's support for virtual named hosts, as described in the Apache 2.2 documentation. If both domains point to your home server's IP address in the DNS, you should be able to be up and running with a few changes to Apache's configuration file.
Answer: you will need a static ip address (or service that forwards to your ip address - pain in the back side as far as I'm concerned)...
but once you have that then you will need to configure virtual hosts...
If you have apache 2.2 you should have a 'extra' folder under 'conf' in your apache directory.
In this you will find httpd-vhost.conf which gives you the basic idea.
Finally in your main apache config file you will need to uncomment the line that includes teh vhost config...
<code># Virtual hosts
#Include conf/extra/httpd-vhosts.conf
</code>
and the line that loads the vhost module
<code>#LoadModule vhost_alias_module modules/mod_vhost_alias.so
</code>


What is this blue/violet flower?

Question: I found this blue/violet flower on an acre in the Polder of Holland. It was growing in a sunflower field. The picture was taken in mid-october.
Comment: Do you have a picture of the leaves, and the entire plant? That would help
Comment: Sadly no. but you can see two leaves at the bottom of the picture.
Comment: How tall was it?, and by two leaves, do you mean the broad leaves in back of the picture, or the smaller, composite leaf in the foreground at the bottom?
Comment: The smaller composite leaf in the foreground. Stephie seems to have hit the nail on the head though.
Answer: This is a Phacelia.
Contrary to your tags, this is no wildflower, but planted either as bee food or to be tilled under as fertilizer. As your specimen blooms late in the year, I suspect the latter use, probably some seeds were blown away.

What is this blue/violet flower?


How do I preserve my save data

Question: I recently got a hankering to play the game again. I've forgotten a fair amount of the game mechanics, and wanted to run through the first bit of the game again. However, my last game is about 66% of the way through, and I don't want to lose that progress. How do I preserve my prior data such that I can get back to it after playing the beginning again?
Answer:
The default location of the saved game state for the Steam edition is in:

C:\Program Files (x86)\Steam\userdata[user ID]\241930\remote\gamedata.sav`

That is assuming you installed Steam in the default location. The bold part is the ID of the game.
I haven't tried this myself, but I think you can copy that current file as a backup (a simple Ctrl+C and Ctrl+V to copy into the same folder and let Windows rename the file), and start a new game.
I would have liked to verify this first, but, as you likely know, these games are notoriously ginormous.

Alternatively, I can suggest to just pick up the game where you left. It's an open-world game, dying is nothing more than annoying, so there is plenty of freedom to reacquaint yourself with its mechanics. I just did the same with Shadow of War, after at least six months of not playing, and got into it again very quickly :)
Comment: I am accepting your answer because I did wind up going with the "just play it" option, although I wound up looking up a lot of maneuvers to remember the key combinations to do them. :)
Comment: In addition to death not being a big problem, There are advantages to dying once to any particular captain.
Comment: @SeanDuggan Yeah, you have to through a trial-and-error phase at first, which can be annoying and/or hilarious at times, but most of the combinations will quickly become intuitive again. Have fun!
Answer: Shadow of Mordor has multiple save slots.
You can just choose another one in the main menu, and play as much as you want without losing any progress on your main file.
Comment: Right, SoM has two save slots! I think SoW has similar-looking slots, but they're for the DLC storylines.
Comment: IIRC, it actually has over 5. DLCs are also saved on the same slots. There's nothing extra for them

How do I preserve my save data


Kaminari: Multiple paginations on a page, indexing and canonical

Question: In my ruby on rails app, I'm showing multiple paginated items on a single page. For a single items pagination, I know how to use pagination and rel='prev' and 'next' attributes and canonical. But in my case, there can be multiple permutations and combinations of a page and this confuses me. From a user's perspective in my case, he/she'll be happy to see different types of information regarding an object on a single page and paginations. But, from a search engine's perspective, it's not that friendly and may cause partial duplicate content. My intention is to get ranked for the index page and google to find the content from the index and paginated pages. Some of these items are accessible from other pages as well in different listings on the separate page. And I also intend to make a sitemap.xml file.
So I have following options:

Keep only index page in the index and make rest of the paginated pages in noindex using robots meta tag.
Use canonical URLs from the request URL and do not use rel='prev' and 'next', because otherwise it'll cause say 10x10= 100 variations of the page if each item has 10 paginated pages.
Use canonical URLs and rel='next' and 'prev' for one of the paginated items and ignore the rest of the URLs or use noindex meta tag for rest of the URLs. I'm leaning toward this solution. So it'll effectively make one pagination on my page and rest of URLs won't interfere with it.
Or I should only use a single page parameter and use that to paginate all other paginated models as well. And when one of the items doesn't have any more pages I should show content from the last page for that item and paginate other items. But I don't know how can I do that using Kaminari? As of now, I'm using three different page_param to paginate these models. I think it'll be the preferred and better solution.

Here is my current code:
def show
        @state = State.published.friendly.find(params[:id])
        @cities = @state.cities.published.sorted.page(params[:page]).per(10)
        @events = @state.events.published.sorted.page(params[:cities_page]).includes(:cities).per(10)
        @articles = @state.articles.published.sorted.includes(:user).page(params[:articles_page]).per(10)
        add_breadcrumb 'States', states_url
        add_breadcrumb @state.name, @state
    end

And cities page has two paginated items, events and news articles from that city.
I'm showing these three paginated items using tabs.
Answer: Why don't you create some simple index pages just for each type of record, and supply those to the search engines?
Steps to take:

Eliminate the combinations of different pagination values in robots.txt
Create index (perhaps paginated) pages for each record (state, city, event, etc)
Hide these pages to users, but allow robots.txt access

This eliminates some complexity dealing with pagination and indexing.
For reference, I just did this exact solution with three different pagination params and I plan on dealing with it from an SEO perspective.


Unsigned binary subtraction when numbers are too large to form two's complement

Question: I am in computer architecture and my prof. hasn't been able to give a satisfactory answer.
Assuming we have a 32-bit processor, if we have two unsigned integers x and y, both of which are greater than 231 (so that they are too large to be converted properly to two's complement form) how do we perform subtraction?
If the subtrahend was a constant I can see how the compiler could compensate for this in static analysis.  But how do we deal with this possibility at runtime, especially in a statically-compiled language like C?  Does this just throw an overflow error or do some architectures subu support special operations?
Everything I find for MIPS says that it just performs two's complement subtraction, but that shouldn't work in this case, should it?
Answer: The situation you pose is not a problem.  Specific example:
  0xFFFFFFFF -  0xFFFF0000
= 0xFFFFFFFF + -0xFFFF0000
= 0xFFFFFFFF +  0x00010000
= 0x0000FFFF

Comment: Somehow I messed up my subtraction on paper here, as I got different results. But this was what I thought as well. +1.


Source controlling (git) docker-compose.yml

Question: My docker-compose.yml file orchestrates the containers for a PHP API based app and a Nodejs web frontend. Both of these are in seperate git repos.
Question: Where and how should I check my docker-compose.yml file into git?
My containers:

Nginx
Redis
MySQL
Nodejs App
PHP App
Answer: I think that I've accidentally answered to this question in other thread: https://stackoverflow.com/a/34001663/381939 (perhaps it is a partial answer)
Anyway, for a situation similar to yours, I have a separate repository for deployment related scripts and configuration. Also, I use git submodules for linking the application repositories into the deployment repo.
Comment: Can you elaborate more in your answer, perhaps with some directory / submodule structure examples. Otherwise very much a good answer!


Method for discriminating power in seqecmpgroup()

Question: In the document for function seqecmpgroup(): "subsequences are then ordered by decreasing discriminant power."

Just wondering what is the method to compute the value? It looks like the 'statistic' column.
Answer: The test is performed by means of a Pearson chi-square independence test on the table obtained by cross tabulating the presence/absence of the subsequence with the group variable. The values returned by seqecmpgroup as statistic are the Pearson independence chi-squares.
The smaller the p-value of the test, the more powerful is the subsequence for discriminating between the groups.
The p-value is calculated with a Bonferroni correction when method = "bonferroni" and without correction when method = "chisq" (default value).
Note that the same Bonferroni correction is applied for each subsequence. Therefore, applying or not the correction does not change the ranking of the subsequences according to their discriminating power.


Best way to use a listview if it can be automatically updated

Question: I am working on an app that tells on campus activities and arranges them by date. I am a beginning developer and I would like to know if it is better to use the google calendar or a listview. I would rather use a listview but I am not sure on how to have the information automatically updated.
Answer: You could use a handler and a post delayed runnable to refresh the list and call the method to get the data into your listview, over again on a time you set, check link here for reference http://developer.android.com/reference/android/os/Handler.html


MS Flow Not Posting File to Sharepoint

Question: Apologies as I'm very new to MS Flow, but my FLOW isn't properly posting daily reports I'm receiving to sharepoint.

Here is a screen shot of previous passed test with 365.
Answer: i created a same flow with your settings. An xlsx file in the email attachment is successfully written into the newly created file in SharePoint. Could you explain a bit more about your issue? You can simply click on your flow to see the flow history and check more detailed error message.
Comment: There is no error message. It passes the test but when I received the email in the past two mornings, the flow doesn't execute.
Comment: @zach So the flow is not triggered by the email. Have you checked the trigger settings? Especially the from and to email address, and the filter.
Answer:
NB: Your flow is triggered only if the user email specified in TO receive email or in From has sent it, Not daily.

MS Flow Not Posting File to Sharepoint


When does a problem constitute a code review?

Question: I am wondering if my question about Clojure sequences could be considered an SO question instead, or if this is more a CodeReview question.
Answer: The distinction between Code Review and Stack Overflow is quite clear:

You have working code and you want to improve it? Use Codereview.
You have broken code and wonder how to fix it? Use Stack Overflow.

Your question is a fine fit for Code Review, I'd say.
Comment: Thanks. That's what I thought. My code is not broken; I just wanted to improve it.


Does the expanding space apparently slow down a very distant photon that moves towards Earth?

Question: To make a picture of what I am asking I have to use a comparission...So let say Adam walks on a 10km long bridge and wants to reach Sara at the end of the bridge but as he walks the Sun heats the bridge to gain length so it is then 10km and 10 meters long. For Sara waiting for Adam it seems he is a little bit slower than she expected assuming the velocity of Adam and his distance from her at the start. Is the same applied to a photon as Adam, space as bridge and planet Earth as Sara?
Comment: The speed of light to a *local* observer is always *c*, but that's not necessarily true for a non-local observer. There are a few different ways to [measure cosmological distance](https://en.wikipedia.org/wiki/Distance_measures_(cosmology)), and the speed you get depends on which distance (and time) measure you use.
Comment: But it's fair to say that expansion does slow down light. From https://physics.stackexchange.com/a/477761/123208 the region that emitted the CMB photons we receive today was 41.6 million lightyears (in proper distance) from our region when those photons were emitted around 13.7 billion years ago, but that region is now about 45 billion lightyears from us.
Comment: There are several posts here on this & related topics, eg https://physics.stackexchange.com/q/26549/123208 & https://physics.stackexchange.com/a/268237/123208
Answer: The answer of your question is simply No.  Speed of causality in universe is constant (C) and hence, the photon doesn't "apparently slow down", but rather it's wavelength changes (in an expanding space time). See https://en.m.wikipedia.org/wiki/Redshift
Answer: The answer to this question is pretty obvious. The speed of light does not change. It will still travel the same amount of distance at the same time in the same medium. Just there will be one amazing thing going on. If you send a light beam from one planet to other planet which are moving far apart then the distance between them will be increasing so the light would take more time than expected. But this is not due to the decreasing speed of light but because of the increasing distance between planets. The same thing applies to this question. The wavelength of the photons tend to increase due time and this phenomenon is called "wavelength shifting" .
You can look for wavelength shifting on Google and you can understand this phenomenon also.
AMAZING FACT: The speed of expansion of universe is continuously increasing and a time will come when this will be even greater than the speed of light.
Comment: If a single wavelength wave streches during trajectory the tail of the wave will apparently reach the target with more delay regarding the head of that wave differently than if the wave haven't been streched...
Comment: When you use the word "APPARENTLY SLOW" this means that "THE SPEED SEEMS TO TAKE MORE TIME THAN EXPECTED" but this does not mean that the speed has changed, right?


Alphabetize web albums

Question: I find that I have a number of albums with different titles but with the same pictures. It is difficult to organize 3000 albums when they are all over. I would like to alphabetize them so I can organize them better. Any ideas?
Comment: Are you sure you're talking about Picasa Web Albums and not Google Photos? The former has been mostly deprecated. Have you tried organizing your albums with Picasa (the downloadable software)?
Comment: Yes, I like the way Picasa web shows the pictures. Google photos shows pictures too big and again I am not able to alphabetize albums; in addition they multiply. Their search ok but not great. Picasa (I changed from Macosx to Mac mini because of pictures) does not have all my photos and I do not want to download from Picasa Web to Picasa all the duplicates. Do you have any suggestions?
Answer: In the list of albums, there's a sort menu on the right side near the top. If offers three options:

Album date
Upload date
Album title

Choosing "Album title" appears to do what you're asking.

Alphabetize web albums


(Solved) Voice isn't always clear through AT-2035

Question: I'm an audio noob and I would appreciate any help I can get here. I recently purchased an Audio Technica AT-2035 and I have it hooked up to a Focusrite Scarlett Solo Second Generation. I've been noticing that my voice often isn't coming through as clearly as I think it should be and is a little bit distorted throughout most of my recording. I made a quick clip to demonstrate it and also pointed out some of the worst parts of the recording. I didn't use any effects on this clip. Please take a look and I'd love to hear some advice, thank you!
Link
Comment: Perrin - what platform are you using this microphone on? Also - what type of drivers are you using? If Windows.... are you using ASIO or other?
Comment: I"m going to assume the answer is Windows for now. If it is, please undertake the following: Google for and download the DPCLAT.EXE utility. Run this on your machine and then post a picture of the result.
Answer: I too think it is probably your buffer settings. Usually it manifest as crackles and pops. It's definitely not anything to do with mic placement or gain or any of that. This is definitely a software/soundcard issue. First thing I would do is lower the buffer setting in your soundcard which will be accessible through your DAW preferences. Second I would make sure your using thd latest driver. I've had trouble with scarlett sound cards before.
Comment: Thanks for the help! I changed my bitrate and buffer size in OBS from 2500 to 6000 which seems to be making a difference. The biggest change I've made so far is changing my sample rate from 44.1 kHz in OBS to 48 kHz, which matches the sample rate of my ASIO driver. Here's the link to the new recording I made: https://www.youtube.com/watch?v=SswL0Kylr-E
Answer: Yes I hear what you are describing. Is it a condenser or just a regular dynamic mic? If it's a condenser it could possibly be a power thing.
I would think that it's not your microphone as they are usually are not intermittent.
I used to have something similar when doing recordings and I ended up working out it was my phone that had a rechargeable battery. Every few minutes it would draw power to charge the battery and when it did this it made a similar sound to what you are hearing. I hear it, but it isn't something I have heard before.
Borrow another mic and do some more recordings and see if it still happens. I have a feeling that it could be another piece of equipment. Start turning off everything you can and bring things back on to see what triggers it.
Comment: The microphone I'm using is the AT-2035 which is a condenser microphone. This is the first microphone I've had so far which uses phantom power. I haven't noticed anything like this with the previous microphones I've had. I'm using a desktop so I don't think that phantom power is the problem but I can't be sure.
Answer: To me it sounds like those little glitches are produced from buffer under-runs.
To be sure that this isn't causing the problem you might want to raise the ASIO buffer on the sound card.
Here is a link from Focusrite website on the topic of optimizing buffer values.
Mind that this will increase latency, if you're using the rig for live broadcast aplications.
Comment: I've made some changes in my recording software which has helped the audio quality so far. In OBS I changed the sample rate to match the sample rate of my ASIO driver. The ASIO driver is set at 48kHz but OBS was set to 44.1 kHz before. I've also increased my bitrate and buffer size so that both are at 6000. Here's a recording of what it sounds like now, do you have any more advice for me? https://www.youtube.com/watch?v=SswL0Kylr-E
Answer: Okay, I gave Audacity a shot and instantly the problem was gone. I have no clue what was causing the problem in OBS but one test recording in Audacity showed me that all of the problems I found were 100% with OBS. All of the comments I received were very helpful though and did help me improve the quality of audio in OBS as well, thank you all!
Comment: If you think this is the correct answer just mark it as the answer.
Comment: Rather than making this comment an answer, you should make it an edit in your question.


How many user accounts should i find when I run "useraccount list all"

Question: How many user accounts should be found when I run "useraccount list all" when there is only 1 person using personal computer?
Answer: The amount of useraccounts on a windows pc is not tied to the amount of people using the pc.
Although each user is likely to have one user, it is possible for anyone to create a user. This can be a testuser, or a user with admin rights together with a user with standard rights.
If we speculate that there is just one user account called "User" which the enduser is using and has administrative rights, then one could expect between 3 and 6 users to be present.
There always will be an Administrator user which is required for UAC and elevation to work, despite if a user has administrator rights or not.
I've also seen a Guest user, even though this is disabled.
Then there is a DefaultAccount, also disabled, which is used to create a new user. This user is copied. The reason behind this default account, is so you can setup rights for new users.
Then there is the WDGAUtilityAccount, also disabled, which is used for Windows Defender.
If you install certain software, such as IIS, it may also create additional useraccounts that are disabled. Earlier versions of windows may create serviceaccounts. If you used Windows 7 and upgraded to Windows 10, it is likely that you will see these useraccounts come back. I forgot however what their usernames are, but it are usually 2 accounts.
As you can see, I can't give you an exact answer, because there are many factors that will determine how many and which users you will find. Useraccount list all will in any case list all of them.
Is it bad if you see many accounts? No, but if you go to Computer management, Local users and groups, Users, you will find the same list of users, and a description for each user that is not an actual user, explaining what the user does. This should help you distinguish users that do not belong there vs users that should be there.
If you are still in doubt, then post a question and ask for that specific user, or google that username.
It is also possible that if your pc is managed by your organisation, that they create an admin user. In that case, you will find it here. The usage for an admin user is usually so access can be granted to a system where the user forgot their password and can no longer get in in any other way. The admin user could then be used to reset the password. Note, this is only common practice if the pc is not domain joined. A domain joined pc does not require the present of a second local administrator user.


どのように and どうやって - difference and usage

Question: どのように and どうやって are both question words used to to ask "how" to do something. But what is the difference between them? Actually, it's rare to see どのように in a written text. Can anyone show me how to use it?
Answer: The only difference between the two phrases is in their formality level.

どのように is more formal (and polite) than どうやって.

If you are familiar with the verb やる, you know that it is a casual/conversational verb. やって is a form of やる.
What is the verb that is more formal than やる but has the same meaning?  It is する.

Thus, you can also say どのようにして to mean "how" as して is a form する.
する : やる = して: やって

Extra: This means that you can say どうして to mean "how" as well, but careful speakers tend to avoid using it because どうして can also mean "why".
Answer: どうやって and どのように are not exactly the same.
どのように is How? - どうやって is By what?
どうやって = どう (how) + やって (a continuative form of do).
どうやって is like asking for experience.

例:彼はどうやってここへ来たのですか。
How did he come here? = By what means did he come here?

In such case, you cannot use どのように
If you ask the way (the methods or tools) of doing something, you can use both
「どのように」and 「どうやって」.

例:これはどのように食べますか/ これはどうやって食べますか。
How can I eat this?

If you want to ask methods or tools which also have the meaning of "in what way".
 You must use どう or どのように.

例:「AとBはどう / どのように違いますか。」
In what way are A and B different?

In this case, you cannot use どうやって.

どのように and どうやって - difference and usage


What happens to bond indices, say IBXXIBHY, when any underlying bond matures?

Question: This Index tracks HYG ETF, so What happens to that will help, if someone can explain. Thanks
Comment: In my experience, as the bond approaches maturity, it is either removed from the index without replacement, or it is replaced by another similar bond. Usually, the index definition states a minimum maturity of a bond to be allowed in the index, so bonds would be removed even before maturing (i.e. within 6 or 3 months of maturity).
Comment: Yes, typically in a monthly bond index, at the end of January all the bonds in the index have at least 1 month life (sometimes more), any bonds that mature in February have already been removed from the index. So bonds are dropped before maturity, when they don't meet the minimum life remaining criterion
Answer: According to the selection criteria in Section 2.3 of the iBoxx USD High Yield Developed Markets Index Guide

All bonds must have at the rebalancing day an expected remaining life of at least one year, and all new insertions must have an expected remaining life of at least one year and 6 months.

Since rebalancing happens once a month at month end, bonds are excluded from the Index at least eleven months before they mature. By the way, it's the ETF that tracks the Index, not the other way around. Hope this clarifies your question.


Trouble recreating mud texture from image

Question: I'm very new to PBR textures in blender and experimenting with them. I'm trying to recreating the look of the mud closely engulfing the woman in this picture using PBR but I'm having a lot more trouble than I thought... does anyone have any ideas?
Answer: Maybe something close to this?

I've mixed the Texture Coordinate with a Musgrave in order to get twisted noise later. There are 2 levels of noise to get some bumps. I've put a Separate XYZ into the Roughness to get something more glossy into the lower parts as if they were more humid. For the color, a mix of 2 greyish blue. Just before the Output, a Glossy mixed with a Layer Weight as factor in order to have additional glossiness on the surface:
Comment: Wow thank you! This looks pretty good, I'll try copying it and I'll play close attention to how each node affects the material


Can i double max current drawn, putting batteries in parallel?

Question: Im dimensioning a quadcopter,and from my math, everything will draw a maximum load of 58-63 A.
I need to choose Lipo batteries that can handle that current draw.
From what I know: Max current: Capacity*C-Rating.
For example, i cant use a 2200mAh 25C battery, because max current drawn will be 55A, but if I put 2 of those in parallel, I will maintain the 11.1V of 3S and will double the capacity. From that, my max current will be 4400*25=110A and I will be safe.
Is my thinking right? Can I do this?
Comment: I will never need to draw 110A, the max current that i will need from the motors+eletronics will be 58-63A. With one battery(2200mAh 25C), i cant get that high, thats why im asking if its possible to put 2 in parallel to double max current drawn.
Answer: Yes, this can and is commonly done in the RC modelling crowd with lithium polymer batteries. Just make sure that both batteries are at the same state of charge (voltage within 50mV) before hooking them up, or you might damage the less charged one by charging it out of spec.
You can even use batteries of different capacities in parallel (but never in series!) as long as they have the same cell count and battery chemistry.
It is also possible to charge multiple batteries in parallel. Again, make sure that the batteries are not too mismatched in voltage before connecting, and make sure that you connect the balance plugs in parallel when balancing (which you should do on every charge).
Your maximum current estimate is correct, but keep in mind that cheap LiPos often overstate the maximum discharge rate somewhat.
Comment: There's one more thing to consider, and that's what happens when a cell goes bad.  If you have one good cell in parallel with one bad cell (maybe it's gone short-circuit for some reason), then you also kill the good cell in rather short order, and possibly the wiring as well.  If you're okay with losing the *entire* composite pack if something goes wrong, then you're probably good, but keep that in mind.  It might be better to put the two 3S packs in series or use a single 6S pack, with a system designed for the higher voltage.  (less current for the same power too)
Comment: Putting two complete packs in parallel while discharging requires all leads to be connected through the balancing connector as well. Just at charging doesn't ward off the problems like hardening or inversion upon discharge. Not to mention that, realistically you need a BMS in both cases to monitor all cells, rather than the stack voltage, since more than 1C will degrade batteries much, much less balanced than sub-1-C through micro stresses from factory to user and slight manufacturing unevenness.
Comment: I agree that it's safer and better for the batteries to parallel the individual cells in the packs even when discharging, but it's not strictly necessary unless you are building a commercial product. RC batteries have matched cells, and discharging fully is avoided. *Nobody* uses a BMS in RC models.


Where do the research question and thesis statement go in a paper?

Question: My professor asked me to place both a research question and a thesis in my research paper. He said the thesis should answer the research question, which I understand, but usually my professors want me to put one or the other at the end of the introduction, not both. Where am I supposed to put them? Am I supposed to change the research question to a statement like a hypothesis?
Comment: What field are you in?
Comment: Does that Question not more likely belong somewhere such as SE Academia?
Answer: Your introduction should frame the course of your paper, which is written to answer a particular research question. Your thesis statement is your stance or answer to that question.
Let me illustrate this with an example I just made up:
"...and so, there is no general consensus among philosophers concerning the solution to Schmidt's Banana Paradox. The field is split down the middle: many hold Quintessential Bananaism to be true, and an equal number are vigorous proponents of Apathetic Bananaism.
"However, it can be said that Quintessential Bananaism is the only logical solution to Schmidt's Paradox. This is for three reasons..."
See how I posed both a question and answer? My research question ("What is the solution to this problem?") is clearly stated, as is my thesis ("The only logical solution is this.") When I write papers, this is usually what I aim to do. I start with a hook, introduce the topic, come to the issue and pose a solution. I can then spend the rest of my paper going over the issue in greater depth and giving support to my argumentation.
Ultimately, don't be afraid to ask your professor for clarification. I don't know what type of research paper you're writing, but in general this format should work: Hook, introduce, question, answer...and copious elaboration.
Answer: As I understand the term, a thesis statement summarizes your expected outcome at the end of the introduction, right after the research question.
The structure of your introduction would look something like this:

Introduction

What are you interested in?
Why is this relevant?
What is the current state of the research on this question?
What is the research question that you derive from both your interest and the state of the research?
What do you think will be the answer to that question? ← your thesis statement

The rest of your paper ...


How to render small object, as pixel art, without losing any of the pixels (Cycles render)?

Question: I am creating pre-rendered sprites like in those classic pixel art games such as Commandos or Desperados. I use low render resolution 60x60 but the render results were blurry. And I found a nodes tutorial for render layer that makes the rendered image have sharp edges. This all works fine for bigger objects but when rendering the smaller ones as gun or knife it sometimes just crop all the pixels and the result is that the object is not visible in the end. I also use freestyle line set for my character though the gun is in a group that's not have apllied freestyle on it. And I am wondering if it is possible to keep the blurred pixels but give them color and not look transparent?
Comment: Render at a higher resolution, then use the compositor to achieve pixelation.
Comment: I don't have the privileges to comment so posting this as an answer. Did you ever solve this? Also what does your Shader node graph look like. This is one of the better pixelation effects I have seen.
Answer: I would render at some multiple of the target pixel dimensions, and then take it into Photoshop.  Edit the original and/or the downsampled result to get the features you want.  For something that small, with just a few missing details, just paint it in using the pencil tool: turn anti-alised smudges into crisp (oversized) blocks; adjust the location of an edge so it downsamples nicely; etc.


How do I create a Django form that displays a checkbox label to the right of the checkbox?

Question: When I define a Django form class similar to this:
def class MyForm(forms.Form):
    check = forms.BooleanField(required=True, label="Check this")

It expands to HTML that looks like this:
<form action="." id="form" method=POST>

Check this: <input type="checkbox" name="check" id="check" />

<input type=submit value="Submit">

</form>

I would like the checkbox input element to have a label that follows the checkbox, not the other way around. Is there a way to convince Django to do that?
[Edit]
Thanks for the answer from Jonas - still, while it fixes the issue I asked about (checkbox labels are rendered to the right of the checkbox) it introduces a new problem (all widget labels are rendered to the right of their widgets...)
I'd like to avoid overriding _html_output() since it's obviously not designed for it. The design I would come up with would be to implement a field html output method in the Field classes, override the one for the Boolean field and use that method in _html_output(). Sadly, the Django developers chose to go a different way, and I would like to work within the existing framework as much as possible.
CSS sounds like a decent approach, except that I don't know enough CSS to pull this off or even to decide whether I like this approach or not. Besides, I prefer markup that still resembles the final output, at least in rendering order.
Furthermore, since it can be reasonable to have more than one style sheet for any particular markup, doing this in CSS could mean having to do it multiple times for multiple styles, which pretty much makes CSS the wrong answer.
[Edit]
Seems like I'm answering my own question below. If anyone has a better idea how to do this, don't be shy.
Answer: Here's a solution I've come up with (Django v1.1):
{% load myfilters %}

[...]

{% for field in form %}
    [...]
    {% if field.field.widget|is_checkbox %}
      {{ field }}{{ field.label_tag }}
    {% else %}
      {{ field.label_tag }}{{ field }}
    {% endif %}
    [...]
{% endfor %}

You'll need to create a custom template tag (in this example in a "myfilters.py" file) containing something like this:
from django import template
from django.forms.fields import CheckboxInput

register = template.Library()

@register.filter(name='is_checkbox')
def is_checkbox(value):
    return isinstance(value, CheckboxInput)

More info on custom template tags available here.
Edit: in the spirit of asker's own answer:
Advantages:

No futzing with CSS.
The markup ends up looking the way it's supposed to.
I didn't hack Django internals. (but had to look at quite a bunch)
The template is nice, compact and idiomatic.
The filter code plays nice regardless of the exact values of the labels and input field names.

Disadvantages:

There's probably something somewhere out there that does it better and faster.
Unlikely that the client will be willing to pay for all the time spent on this just to move the label to the right...
Comment: I like this answer. The implementation is simple, which is always a plus. It's clear what's going on just from reading the template. The only downside (in my biased and admittedly lazy view) is that my solution makes for shorter templates, and is closer to what you could have expected Django to have done in the first place.
Answer: I took the answer from romkyns and made it a little more general
def field_type(field, ftype):
    try:
        t = field.field.widget.__class__.__name__
        return t.lower() == ftype
    except:
        pass
    return False

This way you can check the widget type directly with a string
{% if field|field_type:'checkboxinput' %}
    {{ field }} {{ field.label }}
{% else %}
     {{ field.label }}  {{ field }}
{% endif %}

Answer: All presented solutions involve template modifications, which are in general rather inefficient concerning performance. Here's a custom widget that does the job:
from django import forms
from django.forms.fields import BooleanField
from django.forms.util import flatatt
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.translation import ugettext as _

class PrettyCheckboxWidget(forms.widgets.CheckboxInput):
    def render(self, name, value, attrs=None):
        final_attrs = self.build_attrs(attrs, type='checkbox', name=name)
        if self.check_test(value):
            final_attrs['checked'] = 'checked'
        if not (value is True or value is False or value is None or value == ''):
            final_attrs['value'] = force_text(value)
        if 'prettycheckbox-label' in final_attrs:
            label = _(final_attrs.pop('prettycheckbox-label'))
        else:
            label = ''
        return format_html('<input{1} /> {2}', attrs['id'], flatatt(final_attrs), label)

class PrettyCheckboxField(BooleanField):
    widget = PrettyCheckboxWidget
    def __init__(self, *args, **kwargs):
        if kwargs['label']:
            kwargs['widget'].attrs['prettycheckbox-label'] = kwargs['label']
            kwargs['label'] = ''
        super(PrettyCheckboxField, self).__init__(*args, **kwargs)

# usage in form
class MyForm(forms.Form):
    my_boolean = PrettyCheckboxField(label=_('Some label'), widget=PrettyCheckboxWidget())

I have PrettyCheckboxWidget and PrettyCheckboxField in an extra file, so they may be imported where needed. If you don't need translations, you can remove the ugettext parts. This code works on Django 1.5 and is untested for lower versions.
Advantages:

Highly performant, needs no template modifications
Easy to use as a custom widget

Disadvantages:

"as_table" renders the checkbox + label inside the second column
{{ field.label }} inside the template is empty. The label is instead bound to {{ field }}
More work than I planned on doing on a Saturday ;-)
Answer: I know that the user excluded CSS, but considering the top answers take about half hour of work to do such a small thing, but knowing that details like these are important on a website, I'd settle for the CSS solution.
checkbox.css
input[type="checkbox"] {
    float: left;
    margin-right: 10px;
    margin-top: 4px;
}

forms.py
class MyForm(forms.ModelForm):
    # ...
    class Media:
    css = {
        'all': 'checkbox.css',
    }

template.html
{{ form.media }}
{{ form.as_p }}

Advantages:

fast!
no futzing with template tags (just form.as_p)
no new damned widgets
the CSS file is automatically included in every form

Disadvantages:

the HTML doesn't reflect the presentation (but is good enough!)
your frontendist could complain
Comment: You can also add this css snippet into your current css file and you won't need to use `{{ form.media }}`
Answer: Here's what I ended up doing. I wrote a custom template stringfilter to switch the tags around. Now, my template code looks like this:
{% load pretty_forms %}
<form action="." method="POST">
{{ form.as_p|pretty_checkbox }}

<input type="submit" value="Submit">

</form>

The only difference from a plain Django template is the addition of the {% load %} template tag and the pretty_checkbox filter.
Here's a functional but ugly implementation of pretty_checkbox - this code doesn't have any error handling, it assumes that the Django generated attributes are formatted in a very specific way, and it would be a bad idea to use anything like this in your code:
from django import template
from django.template.defaultfilters import stringfilter
import logging

register=template.Library()

@register.filter(name='pretty_checkbox')
@stringfilter
def pretty_checkbox(value):
    # Iterate over the HTML fragment, extract  and <input> tags, and
    # switch the order of the pairs where the input type is "checkbox".
    scratch = value
    output = ''
    try:
        while True:
            ls = scratch.find(' -1:
                le = scratch.find('')
                ins = scratch.find('<input')
                ine = scratch.find('/>', ins)
                # Check whether we're dealing with a checkbox:
                if scratch[ins:ine+2].find(' type="checkbox" ')>-1:
                    # Switch the tags
                    output += scratch[:ls]
                    output += scratch[ins:ine+2]
                    output += scratch[ls:le-1]+scratch[le:le+8]
                else:
                    output += scratch[:ine+2]
                scratch = scratch[ine+2:]
            else:
                output += scratch
                break
    except:
        logging.error("pretty_checkbox caught an exception")
    return output

pretty_checkbox scans its string argument, finds pairs of  and <input> tags, and switches them around if the <input> tag's type is "checkbox". It also strips the last character of the label, which happens to be the ':' character.
Advantages:

No futzing with CSS.
The markup ends up looking the way it's supposed to.
I didn't hack Django internals.
The template is nice, compact and idiomatic.

Disadvantages:

The filter code needs to be tested for exciting values of the labels and input field names.
There's probably something somewhere out there that does it better and faster.
More work than I planned on doing on a Saturday.
Comment: Can you provide the code for pretty_checkbox?  My own preferred markup for this is  Check this
Comment: I don't have the code handy right now. It wasn't very elaborate, if I recall - it's simply a function that's fed a short HTML snippet, and swaps the label and input around if the input is a checkbox. The markup is generated by Django, so any preference you might have is probably irrelevant.
Comment: you have got to be kidding.  This is very simple in HTML.  So I use Django to make things hard, because I am a *real* programmer??  Django check forms are broken.  pure and simple.
Comment: It's even simpler in Smalltalk.
Answer: Changing checkbox position in Django admin can be quite tricky, but luckily there is a simple solution using custom widget:
from django.forms.widgets import Widget, CheckboxInput, boolean_check

class RightCheckbox(Widget):
    render = CheckboxInput().render

    def __init__(self, attrs=None, check_test=None):
        super(RightCheckbox, self).__init__(attrs)
        self.check_test = boolean_check if check_test is None else check_test

Django uses left position only when widget is subclass of CheckboxInput
Answer: Order of inputs and labels is provided via normal_row parameter of the form and there are no different row patterns for checkboxes. So there are two ways to do this (in 0.96 version exactly):
1. override _html_output of the form
2. use CSS to change position of the label and checkbox
Answer: I had this problem too and I just used this method :
post-detail.html

{% if field.html_name == "check_box" %}
      {{ field }}

    {{ field.label }}

{% else %}

   {{ field.label }}

  {{ field }}
{% endif %}
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Choose between words "perverse" and "deviant"

Question: I want to express the concept of a crowd of people with wrong idea of good and bad things (like people from some classical books who make principal characters abandon their love and so on). Can I use the expression perverse crowd or deviant crowd. I feel that something is wrong, because these words are usually used to refer to something sexually abnormal? What is a right adjective to use?
Answer: Go ahead and use perverse. OED:

1.a. Of a person, action, etc.: going or disposed to go against what is reasonable, logical, expected, or required; contrary, fickle, irrational.
  . . .
  3. Obstinate, stubborn, or persistent in what is unreasonable, foolish, or wrong; remaining set in a course of action in spite of the consequences.

Yes, there is also this:

5 That is (regarded as) sexually perverted.

But sexual meanings and applications of a word need not always utterly swallow up all others.
Answer: To denote people without morals, use amoral
To denote people who have other ideas about things than the majority, you could use aberrant
Comment: Well, I don't think that it suits here, because this crowd has its moral, the problem is that their moral is hypocritical. So I want to give them some delicate adjective.
Comment: @BukvaCe - Not having a moral would be immoral. Amoral means acting _against_ a moral. While following their own, they can very well go against the moral standards or your audience, which is often meant by amoral.
Answer: How about the word "corrupt"? But I would suggest that it is not the crowd that is corrupt, but the members of the crowd, and since all three terms ("corrupt", "perverse", and "deviant") have personal connotations to at least some degree, I would use a construction such as "the people of the crowd were corrupt / deviant / perverse".
Answer: When the words you listed are used without qualification, it's often to denote sexual preferences. But if you specify explicitly the nature of their deviation, or the context of the discussion makes it clear, this connotation no longer applies.

Choose between words “perverse” and “deviant”


Output of op-amp getting as a constant voltage of 500 mV in PROTEUS

Question: Earlier i tried generating a +5V to -5V square wave using an op-amp as an astable multivibrator . The wave had a frequency of 1 kHz. The op-amp was given +Vcc of 5.5V and -VCC of -5.5V. I got the desired square wave at the output. Now i want to generate 0 to 5V square wave using the same circuit. However when I tried simulating the circuit taking -Vcc as 0V im getting a constant voltage of 500mV. Can you please help me to troubleshoot the circuit. The op-amp I have used is an LM324.
Comment: Your opamp is trying its hardest to swing low, but the lowest it can go is 500mV (a little above the negative rail). At that point the junction of R1/R2 is about 250mV, so the opamp neg input is still higher than its pos input so the opamp is forever stuck low. In your original design the opamp was free to swing all the way down to -4.5V, and R1/R2 would then set the pos input to about -2.2V, allowing the opamp to flip when C1 voltage reached -2.2V.
Comment: Can you suggest a circuit employing op-amp i can use to get a 0 to +5V pulsating DC waveform at 1KHz? if not, please suggest me the sources which i could use to figure out the connections for op-amp.
Answer: You need to add a resistor to the junction of R1/R2 to bias it away from GND.
For a square wave you'd want it (roughly) half of Vcc. Not exactly because the op-amp output does not swing as close to the positive rail as it does to GND.
Eg:

simulate this circuit – Schematic created using CircuitLab
Comment: I Tried simulating the circuit you've given. However i am getting a constant 5V DC signal at the output instead of pulsating square wave of 0 to +5V at  1KHz. Can you guide me where i coudve made a mistake. I added a 10V DC source at the R1/R2 Junction through a 100k ohm resistor and changed the values of R1 and R2 as 100K ohm as well.
Comment: Either reduce the 10V source or increase the 100k resistor that is connected to it.
Comment: To get some intuition on this try calculating the threshold at which the output switches.
Comment: A real LM324 output can only swing from its negative rail to within 1.5V of its pos rail so should only be able to reach 3.5V max in your case. The fact that the simulation yields 5V under any circumstance is suspect. (Are you sure you didn't short the opamp output to 5V in your schematic?) Since the output swing is only 0 to 3.5V the R2/R3 ratio should be adjusted to half that, about 1.9V. Can do this by making R3 = 62K. If you make R4 = 62K too then the circuit should work and be pretty close to 1kHz. If you really need a full 5V swing you need to use a rail-to-rail opamp (e.g. LMV324)


Computing Some Integrals via Gauss Integral

Question: $ \displaystyle\int_{-\infty }^\infty e^{-\frac{1}{2} x^2} \; dx $
and
$ \displaystyle\int_{-\infty }^\infty x^{2}e^{-\frac{1}{2}x^2} \; dx $
how i compute these integrals via Gauss Integral?
Answer: Make the substitution $x = \sqrt{2}\  t$ in both, and use integration by parts in the second, by writing
$$2t^2 e^{-t^2} = -t \times \frac{d e^{-t^2}}{dt}$$
Answer: The one on the left is what I usually think of when I hear the term "Gaussian integral".  But some people, maybe especially physicists, omit the fraction $1/2$.  Including the $1/2$ makes sense because then the variance of the probability distribution that you get when you normalize the function to be a probability density is $1$.
If you know that
$$
\int e^{-w^2}\;dw=\sqrt{\pi},
$$
then you can write $x=\sqrt{2}\;w$ and $dx=\sqrt{2}\; dw$.  As $w$ goes from $-\infty$ to $\infty$, so does $x$.  So
$$
\int_{-\infty}^\infty e^{-\frac 12 x^2}\; dx = \int_{-\infty}^\infty e^{-w^2} \sqrt{2} \; dw = \sqrt{2\pi\;{}}.
$$
For $\displaystyle\int_{-\infty}^\infty e^{-\frac 1 2 x^2} \; dx,$ begin by observing that it's an even function integrated over an interval that is symmetric about $0$, so it's equal to
$$
2 \int_0^\infty x^2 e^{-\frac 1 2 x^2} \; dx.
$$
Then substitute $u=\frac 1 2 x^2$, $du = x\;dx = \sqrt{2u} \; dx$, so $\dfrac{du}{\sqrt{2u}} =dx$.  The integral becomes
$$
2\int_0^\infty  2u e^{-u} \frac{du}{\sqrt{2u}} = \frac{4}{\sqrt{2}} \int_0^\infty u^{\frac 3 2 - 1} e^{-u}\;du = 2\sqrt{2}\Gamma\left(\frac 3 2 \right) = 2\sqrt{2}\cdot \frac 1 2 \Gamma\left( \frac 1 2 \right) = \sqrt{2\pi}.
$$
Answer: An interesting alternate way to evaluate the second integral $\displaystyle\int_{-\infty }^\infty x^{2}e^{-\frac{1}{2}x^2} \; dx$  using the results form the first one is to utilize a technique called "differentiation under the integral sign".
From a substitution and our first integral's value in hand, we can conclude that $ \forall \alpha > 0 \in \mathbb{R} $,
$\displaystyle\int_{-\infty }^\infty e^{-\alpha x^2} \; dx = {\dfrac{\sqrt{\pi}}{\sqrt{\alpha}}} $.
Now we differentiate both sides with respect to $\alpha$ (under the integral sign on the left), and we obtain
$  \displaystyle\int_{-\infty }^\infty -x^2 e^{-\alpha x^2} \; dx$ = $-\dfrac{\sqrt{\pi}}{2\alpha\sqrt{\alpha}}$
Factoring out the $-1$ from both sides and plugging in $\alpha = 1/2$ gives us our answer:
$\displaystyle\int_{-\infty }^\infty x^{2}e^{-\frac{1}{2}x^2} \; dx = \dfrac{\sqrt{\pi}}{\sqrt{1/2}} = \sqrt{2\pi}.$


What are the Cantonese to English transliterations for 俊傑, 俊熙, 俊健, and 俊文? I found zeon3 for 俊. That does not sound right

Question: What are the Cantonese to English transliterations for 俊傑, 俊熙, 俊健, and 俊文?  I found zeon3 for 俊. That does not sound right.
Comment: Search *cantonese romanization*  and there are more than seven romanization systems. Different spellings are designed for the same sound. Better listen to the pronouciation and pick the one that fits your usage best.
Answer: /zeon3/ is a Jyutping. which is not meant to be written as English words
According to Cantonese to English Translator
The four names 俊傑, 俊熙, 俊健, and 俊文 are transliterated as Joon Jae, Joon Hee, Joon Kin, Joon Man

My Hong Kong-born nephew's name contains the word 俊
So I know it is written as Chun
The Hong Kong transliteration of 俊傑, 俊熙, 俊健, and 俊文 would be Chun Kit, Chun Hei, Chun Kin, and Chun Man
I just look up famous Hong Kong people whose names contain these Characters and read their Wiki profiles
For Mandarin transliteration, just use Google Translate
Result: Junjie, Junxi, Junjian, and Junwen
Comment: There are different translitation systems. The one you are using is Wade-Giles.
Answer: To use "standard" transliteration that I've commonly encountered it would be: Chun Chieh, Chun Hei, Chun Jian, and Chun Wen. The zeon is based on jyutping, one if the cantonese equivalents to pinyin.
I put standard in quotes because while it is commonly seen and familiar, Cantonese transliteration is more of something established without a standard. This is why Tang Ho found different versions when looking up people with similar names.
To this day, you will often see completely different pronounciations all transliterated into the same letters, such as Shi (si, sek, and sat being jyutping examples) or Kai (hoi and kai).
Sometimes, this is because the transliterator just ignores the Cantonese pronounciation and transliterates directly based on what Mandarin would be.  When you consider that the point of transliteration is to be understood by those who don't know the source language, it can be understandable why using more familiar versions are useful. Regardless of agreeing with the sentiment, it is a part of why this happens.
Another huge factor is that many of the transliterations are very old, from the 1800s or even further back.  In these cases there is the usual issue of no transliteration being accurate to the source language's sound, combined with pronounciation changing over time.  A famous example is MK aka Mong Kok, Hong Kong (wong gok, hoeng gong). I mention the two letter abbreviation since this not accurate transliteration is used in Cantonese speech frequently, really showing how established these are.
These phenomenon are the reasons the jyutping zeon looks so different from what you see in transliteration.  Differences between an accurate attempt transcribing the sound and regular transliteration is not unique to Cantonese either.  A famous Mandarin example is Peking. Few people would realize it is the same word as the modern and more accurate Beijing if they didn't have any Chinese knowledge.
P.S. in your image the machine translator has transcribed the names into Korean transliteration.  This is just an error of the machine and not related to any normal transliteration.
Answer: There's a Chinese University Hong Kong website that you can use as a reference
chinese characters database
俊 is listed as zeon3


Protection of Private Keys

Question: I've used mail encryption products like Mailvelope in the past, where you have to create a key pair to encrypt/decrypt data. I understand you have to hand out the public key to others that want to encrypt data back to you, but how should you protect your private key? And do these methods change depending on the software used?
Answer: The private key can be protected by several means:

Keep the (master) private key offline that means on a removable media that is not attached to the computer for daily use. E.g. in GPG/PGP you have different keys. One is master key and the others are sub keys. The master key is used to sign the sub keys (similar to a X.509 infrastructure where the root CA certificate is the master and the intermediate certificates are the sub keys).
Don't use the master key on a computer that is connected to the internet or could be compromised by any other means.
Use key lengths and hash algorithms that are considered secure.
Use a strong passphrase to encrypt your keys.
Revoke the certificates for the (sub) keys immediately if you suspect them to be compromised.

This approach is (nearly) independent of the software used. Only the first and second bullet can be unsupported depending on the software/key used (using S/MIME you only have one key under normal circumstances).
Comment: Thank you for your answer. So the sub keys are the one's performing the encryption at this point, whereas the master key is kept somewhere off line.
Answer: One other factor you may want to add to @uwe-plonu's answer: keep the keys in a device that will not let even you at them, such as an HSM, smart card or token. There is a small USB-attached HSM that is specifically for PGP, and offloads the crypto processing from the computer. This means that even if someone got physical ownership of the device, the keys would be very hard (barring a significant defect or amazing luck guessing the password, effectively impossible) to extract.

Protection of Private Keys


What is the trade off in converting a DFA into a NFA?

Question: When a DFA is converted into an equivalent NFA, the NFA gives more convenience to many yes/no kind of problems (such as a word belong to a language or not?). I want to know in general at what price this convenience is achieved?
Comment: A "DFA is a NFA ".. recall from the first principles, in DFA is $$\delta:Q*E \rightarrow Q$$ whereas the NFA has $$\delta:Q*E \rightarrow \mathcal{P}(Q)$$
so you can (intuitively) think of DFA as a 'special type of' NFA.
Comment: I wonder which problems you are referring to.
Comment: @Subhayan You should make this into an answer.
Answer: A deterministic finite state automaton (DFA) is in fact a non-deterministic finite automaton (NFA) where the transition function only maps to singelton sets.
Recall that from the first principles that the transition function, $\delta$, in a DFA is defined as
$$ \delta: Q*E \rightarrow Q,$$
whereas for an NFA it is
$$ \delta: Q*E \rightarrow \mathcal{P}(Q)$$
This means that you can (intuitively) think of a DFA as a "special type of" NFA.
Comment: @gpuguy – Subhayan answered this perfectly.  There is no price for this "convenience".  An NFA allows for the transition function to map to _sets_ of arbitrary sizes whereas a DFA maps to sets of size one.  You could ask "which convenience do a DFA have over a NFA?", to which the answer would be that it only maps to single states and not sets of states.
Comment: This is not precisely what I am looking for. Can you please read my question again.
Answer: It may be difficult to get an answer you like because given a DFA it is hard to find an equivalent NFA that has fewer states.  If all you know is the DFA, you are going to have to work extremely hard to get any equivalent NFA other than the DFA itself.
Suppose, however, that you do have an equivalent NFA and DFA where the NFA is smaller than the DFA.  (Perhaps because you had the NFA in the first place, and used the Rabin-Scott powerset construction algorithm to find the equivalent DFA.)  Given an NFA over $M$ symbols with $N_{\mathrm{NFA}}$ states, and an equivalent DFA with $N_{\mathrm{DFA}}$ states, and $N_{\mathrm{NFA}} \leq N_{\mathrm{DFA}}$, the DFA will be cheaper to simulate than the NFA.
For the DFA the current state is an integer $j \in N_{\mathrm{DFA}}$.  You keep a table with $M N_{\mathrm{DFA}}$ entries where the $i$ + $jM$th entry in the table gives you the next-state transition from state $j$ on symbol $i$.  The lookup is $O(1)$.
For the NFA the current state is a set $J \subseteq N_{\mathrm{NFA}}$, and is typically represented with an $N_{\mathrm{NFA}}$ bit vector.  (A $1$ at position $j$ in the vector means that $j$ is a member of the current state.)  Your state transition is much more expensive.  For each element $j_k$ in the current state set you need to look up the (possibly $N_{\mathrm{NFA}}$ element) next state set, and then union together all the results of the lookups.  Perhaps there is an algorithm for doing this faster than $O(N_{\mathrm{NFA}}^2)$, but I don't know it off hand.
There's a memoization based optimization that is typically performed during NFA simulation (you keep a cache that maps a hash of the current state and the current symbol to its next state, so that if you get that state/symbol pair again in the future you get the next state in $O(1)$), but this doesn't change the worst case bounds.
Answer: I assume you mean converting a DFA to a smaller NFA that actually uses the nondeterminism.
If your machine uses nondeterminism, it's more difficult to simulate in on a deterministic computer. You have to keep track of all possible computation states, since your computer can't "guess" the correct nondeterministic transition like the NFA would. This basically amounts to converting your NFA back to a DFA with (exponentially) more states.


Footer navigation menu

Question: Our website is https://de.ferberg.com and we are a manufacturer of warehouse equipment and mobile loading ramps. On our site the navigation menu is added to the footer via code and theme editor, it is duplicated from the main menu in the header, but we need to add elements there that are not in the main menu. We tried adding through the menu editor, but no new display areas are available in the theme. Can you tell me how to add a new menu display area in Wordpress?
Answer: you can add new menu from WordPress admin on this https://de.ferberg.com/wp-admin/nav-menus.php?action=edit&menu=0 and then you need to call this menu where you're calling your footer menu.

Footer navigation menu


Java what is the benefit of Throwing RuntimeException

Question: What is the benefit of declaring (Unchecked Exception)throws exception along method signature b/c it does not force caller to keep in try catch block.
public void testRuntimeEx()throws RuntimeException{

if(1==1){throw new RuntimeException()}

}

//Caller method
public void testCaller(){
// not necessery to handle even caller does not known which RuntimeException might be throws then what is the benefit throws clause with method signature
testRuntimeEx();

}

Comment: You don't have to declare it either, since it is unchecked.
Answer: It still serves as documentation, especially if you do not use a generic RuntimeException, but something more specific like IllegalArgumentException or UnsupportedOperationException or IndexOutOfBoundsException and also add some JavaDoc as to when that would happen.
In your example code snippet, it is pretty meaningless, though.
Answer: This declaring is a signal for developer who uses this code, that it throws RuntimeException.
 But it doesn't smell good.
P.S. Code you posted will not compile:
throw RuntimeException

This is not correct throwing.
Answer: The benefit is that typically caller does not have anything to do with the exception. It catches it, wraps with other exception and throws again. Or, alternatively, declares the exception using throws keyword and becomes transparent for this type if exception.
I'd say that the described situation is typical for applications where we usually write business code and have one centralized place that handles all exceptions. It is not correct for APIs. For example if you are using library that implements SSH you are expecting it to throw IOException (or even more specialize exception) when something is going wrong.
Answer: if you throw custom unchecked exception it becomes more meaningfull rather catching system exception and unchecked exception does not force to catch too.