How to resemble hyperbolic trigonometric functions (HTF) from normal trigonometric functions(NTF)??

Question: There are many properties of HTF similliar but little different than NTF, Is there some pattern or rule that makes me, who only knows NTF, able to get HTF from direct resemblence to NTF?
Comment: This becomes transparent when looking at them in the complex plane. See http://en.wikipedia.org/wiki/Hyperbolic_function
Answer: One of the ways of defining sine and cosine is from the exponential function:
$$ \cos x = \frac{e^{ix} + e^{-ix}}{2} \qquad \sin x = \frac{e^{ix} - e^{-ix}}{2i}$$
You can also define hyperbolic trig functions like this:
$$ \cosh x = \frac{e^{x} + e^{-x}}{2} \qquad \sinh x = \frac{e^{x} - e^{-x}}{2}$$
The similarity is pretty obvious in this form. And it also makes it easy to get a relation for one in terms of the other:
$$ \cos x = \cosh ix, \ \cosh x = \cos ix, \ \sin x = -i \sinh ix, \ \sinh x = -i \sin ix $$


jquery hide leaves whitespace in unbounce landing page

Question: When adding custom javascript code in unbounce landing page, based on a yes or no question, the form fields and hidden and showed using jquery. The fields are hidden but there is a gap left within the form.
Comment: you are probably using visibility: hidden instead of display:none
Answer: Do you have an example? and is there padding or margin on the parent tag?
Answer: <code>use css display:block or display:none,
$("#selector").css("display","block") // show
$("#selector").css("display","none")  // hide
</code>


In TechTalk SpecFlow, how do I abandon a Scenario?

Question: My scenario reads a file with hundreds of lines. Each line calls an API Service, but the service may not be running. If I get a non-200 response (available inside the 'Then' method), I want to abandon the Scenario & save time.
How can I tell TechTalk SpecFlow to not carry on with the other tests?
Comment: I would question the approach here. Wouldn't you want to make sure your api service is active and 'warm' before running tests against it?
Comment: @Konzy262 that would make the test script more complicated - and I'm not the one who wrote it. It's quite difficult to follow, as it looks like it's written by an English major rather than a computer programmer, and the mapping to actual code almost but not quite quite different to the method names e.g. something like "If I read the file and call the functional api then verify that the names match what's on the label" but of course those are not the names of the methods.
Answer: You can use a concept like this .
<code>       public static FeatureContext _featureContext;

     public binding( FeatureContext featureContext)
            {

                _featureContext = featureContext;
            }

     [Given(@"user login")]
      public void login(){
      // do test
        bool testPassed = //set based on test. true or false
        binding._featureContext.Current["testPass"] = testPassed;
      }
</code>
Then in  BeforeScenario()
<code>    [BeforeScenario(Order = 1)]
    public void BeforeScenario()
     {

       Assert.IsTrue(FeatureContext.Current["testPass"];);

     }
</code>
Comment: This may be what I'm looking for, but IIRC I tried using the dictionary but it get's reset for each call. I'll have a look again later


prove $\lim_{n\to\infty}n!\sum_{k=n+1}^\infty\frac{1}{k!} = 0$

Question: Can someone help me with a proof that
$\displaystyle\lim_{n\to\infty}~n!\sum_{k=n+1}^\infty\frac{1}{k!} = 0$?
It would be great if the proof could avoid using the gamma function.
This limit is an intermediate value in a larger proof.  It is a lemma necessary in my proof that the Laplacian expansion algorithm of an $n
\times n$ matrix has complexity $(e-1)n!$.
The actual value of the complexity is
$T(n) = n!\displaystyle\sum_{k=1}^{n-1}\frac{1}{k!}$.
The summation term is the leading part of an infinite sum which converges to $e$.   If we add and subtract $e$ we end up with $T(n) = n!\Big(e - 1\Big) - n!\Big(\displaystyle\sum_{k=n+1}^{\infty}\frac{1}{k!}\Big)$.
The question posted here, is to show that the term being subtracted is asymptotically zero.
Comment: Welcome to [math.se] SE. Take a [tour]. You'll find that simple "Here's the statement of my question, solve it for me" posts will be poorly received. What is better is for you to add context (with an [edit]): What you understand about the problem, what you've tried so far, *etc.*; something both to show you are part of the learning experience and to help us guide you to the appropriate help. You can consult [this link](https://math.meta.stackexchange.com/q/9959) for further guidance.
Answer: This should work:
$$\sum_{k=n+1}^\infty\frac{1}{k!}=\frac{1}{n!}\sum_{k=1}^\infty\frac{1}{\prod_{l=1}^k(n+l)}\leq\frac{1}{n!}\sum_{k=1}^\infty\frac{1}{\prod_{l=1}^kn}=\frac{1}{n!}\sum_{k=1}^\infty\frac{1}{n^k}=\frac{1}{n!}\frac{1}{n-1}.$$
Now you can use the squeeze lemma to prove your limit. I believe you can finish it now.
The tricky part to "justify" in one's head should be clear with this:
$$\frac{1}{k!}=\frac{1}{\prod_{t=1}^kt}=\frac{1}{\prod_{t=1}^nt\prod_{t=n+1}^kt}=\frac{1}{n!\prod_{t=n+1}^kt}=\frac{1}{n!}\frac{1}{\prod_{t'=1}^{k-n}(n+t')},$$
assuming $k>n$, where in the last step we substituted $t'=t-n$. Now we will use the substitution $k'=k-n$ to derive the whole thing:
$$\sum_{k=n+1}^\infty\frac{1}{k!}=\sum_{k=n+1}^\infty\frac{1}{n!}\frac{1}{\prod_{t'=1}^{k-n}(n+t')}=\frac{1}{n!}\sum_{k=n+1}^\infty\frac{1}{\prod_{t'=1}^{k-n}(n+t')}=\frac{1}{n!}\sum_{k'=1}^\infty\frac{1}{\prod_{t'=1}^{k'}(n+t')}.$$
Now just rename $t'$ and $k'$ back to $l$ and $k$.
Comment: I get it that it's a bit cumbersome. Please try calculating the first few terms of that sum.
Comment: @JimNewton I edited the queston. Is it clear now?


What's the goal in the lighthouse puzzle (and how to achieve it)?

Question: I'm stuck in this puzzle given by the cyclops at the lighthouse. What am I trying to accomplish here and how?
Comment: For those not wanting to just read a walkthrough: The aim is to powerup (#) the "? ?" tile.
Answer: The goal is to power up the [ ? ? ] block with a charge (#) and click it. If you want to know exactly how to accomplish this, read on.
I made a video of myself completing the puzzle, you can see it here:

How to read the instructions:

Letter-number combination tells you which block to click, check the image below to understand better. E3*6 means press E column, row 3, 6 times in a row.
A charge is represented by #.
To charge a block, you need two adjacent <3 blocks.
REMEMBER TO CHARGE ALL BLOCKS WHEN THEY PASS THE <3 BLOCKS!!!

Here's the full description; step by step. Click blocks in the following order:

D3 - D2 - E2 - D3 - E3 - E3 - F4 - F3 - E3 - G4 - G3 - G2
Repeat F2 and F3 until the nearby blocks are fully charged and always when there is a block with low charges adjacent to one of them.
D3 - E3*6 - C4 - C3 - C2 - E3 - E3 - A4 - A3 - A2 - A1 - C1
Repeat C1 and B1 until the nearby blocks are fully charged and always when there is a block with low charges adjacent to one of them.
E3 - B4 - B3 - B2 - A5 - B2 - B2 - B2 - B5 - E3 - B2 - E3 - B2 - E3 - B2 - A4 - E3*6 - B2*3
NOTE: Video takes a longer route, here's the shortcut.
Charge both A1 and F2 with at least one charge.
A1 - G2 - G1
Done!
Answer: So here's how it works:

V blocks make a block in the direction of the V
T block make a block above
<3 blocks power up all adjacent blocks
---> blocks move the row below along one
| blocks move the row to the left up one
# indicates how many charges a block has

The first few clicks should be:

Click the V/T block, then expand out the chain of Vs to get the --->.
Make a T block by clicking the centre block
Move the T block along to be one block to the left underneath the ?? block
Click it, and expand to get a <3
Click the <3 to charge
Move it along one again and expand. You now have two adjacent <3 blocks to make an 'engine'

You can now expand out the rest of the area using the same method. You should end up with two ---> blocks, and one |. You can use these blocks to move around the movement blocks so you can move an engine underneath the ?? block.
Power it up to win.
Comment: Got it - trial and error, but the answer was certainly helpful.
Comment: I can think of an easy way. A list of blocks to click on, in order.
Answer: I've made a close to minimal video showing the solution. It goes quickly, but doesn't have as many steps to follow. You can find it here Lighthouse Puzzle Solution
Comment: Can you summarize your solution here, please?  That way, if the video ever goes down, your answer is still valid.


Why $X^* X\in \mathfrak{g}(V)$.

Question: A finite dimensional vector space $V$ with a non-degenerate form (,) s.t. $(u,v)=\epsilon (v,u) \forall u,v\in V$ is called a quadratic space of type $\epsilon$.
Let $V$ be a quadratic space of type $\epsilon$ and $U$ be a quadratic space of type $-\epsilon$.
Let $X:V\rightarrow U$ be a linear map and the adjoint map $X^*:U\rightarrow V$ is defined by $(Xv,u)=(v,X^*u)$ for $v\in V, u\in U$.
Why $X^* X\in \mathfrak{g}(V)$(Lie algebra of V)?
Comment: Why are you vandalizing the question? =/
Comment: Looks like he's trying to delete his own question and doesn't know how.
Comment: Got the answer myself.
Answer: $(X^*Xu,v)=\varepsilon(v, X^*Xu)=\varepsilon (Xv, Xu)=-\varepsilon^2(Xu, Xv)=-(u, X^*Xv)$. That's it

Why $X^* X\in \mathfrak{g}(V)$.


Vue-cli3 demo use vue-router routing to pages not working

Question: I'm trying to learn vue-router and I have a problem with vue-cli3 + vue-router demo.
This demo use vue create default create.
I've tried to minimize the demo, but it is still not work.
this is main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'

Vue.config.productionTip = false
Vue.use(VueRouter)

const Foo = { template: '
foo
' }

const routes = [
  { path: '/foo', component: Foo }
]

new Vue({
  router: new VueRouter({
    mode: 'history',
    routes: routes
  }),
  render: h => h(App),
}).$mount('#app')

this is App.vue
<template>

    <router-link to="/foo">Go to Foo</router-link>
    <router-view></router-view>

</template>

vue and vue-router version
"vue": "^2.6.10",
"vue-router": "^3.1.3"

I don't know why it doesn't work. Can you help me?
Comment: Are any errors thrown in the console or browser? You might have missing dependencies? The code above should be working.
Comment: @MarcRo Christian Carrillo's answer is right, but thank you very much
Answer: You should use
import Vue from 'vue/dist/vue.js'
instead of
import Vue from 'vue'
here have a topic about this and vue template.


A weak version of König's Theorem - Does this depend on Choice?

Question: Let $X_1,X_2,Y_1,Y_2$ be nonempty disjoint sets, where $|X_i|<|Y_i|$. Here, we take this to mean that there is an injection $X_i\to Y_i$, but there is no bijection $X_i\to Y_i$. My question is, is the following statement true in ZF:
$\begin{align}
|X_1|+|X_2|:= |X_1\coprod X_2| < |Y_1|\cdot |Y_2|:=|Y_1\times Y_2|
\end{align}$
The $\leq$ part is easily seen to be true, but every proof i've found of König's Theorem in the general case fails without the axiom of choice even for the case of two sets (Even though we do not choice to claim the product is nonempty). In particular, the failure usually manifests as an assertion such as "There exists no surjection $X_i \to Y_i$" or an equivalent assertion. This claim is only equivalent to $|X_1|<|Y_1|$ in the presence of choice (Or the partition principle, but is not a priori true in ZF).
I am wondering if this claim is even provable in ZF, or maybe I am missing a very easy proof that does not depend on choice.
Comment: Cardinal arithemtic without AC is pretty wild... I strongly doubt that your statement is provable without it
Comment: Also, because AC is not provable nor disprovable in ZF, we have that ZF and ZFC are equiconsistent. Then the question whether your statement is true in ZF and whether it is provable in ZF are really the same question. It cannot be provably false. If it could then ZFC would imply that it is true and false and ZFC would be inconsistent, hence ZF would be inconsistent. So, if your statement can't be proven to be true, it can't be proven to be false either, meaning we can assume it is whatever we want, true or false.
Answer: Surprisingly enough, it does.
It is consistent that $\Bbb R$ is the union of two sets of smaller cardinality. Since $\Bbb{|R|=|R^2|}$, this provides a counterexample.

Monro, G. P., Decomposable cardinals, Fundam. Math. 80, 101-104 (1973). ZBL0272.02085.


If I delete the Undertale file in Steamapps, will it delete the soundtrack as well?

Question: I did a Neutral Run in Undertale where I decided to kill Flowey. I then reset hoping to do the full Genocide Run when as I approached where you are usually greeted by Flowey, he does not turn up.
I came here and found out you had to delete the Undertale file in Steamapps (because I have Steam) but I realized that I had bought the Undertale soundtrack. So I am wondering if you delete the Undertale file, if it deletes the soundtrack too. I don't want to lose the soundtrack!
Comment: Even if you delete it, you can download it again. Also, if you like the soundtrack so much, why keep it in your Steam folder where it's so hard to reach, when you can just copy it to your library's music folder where it's far easier to reach?
Comment: It is in my library, I just didn't know if it would delete it from there aswell.
Answer: First: It sounds odd that you'd have to delete some file(s) for this, but I'll leave this portion for others.
Since you've bought the game on Steam you can (re-)download the game and the soundtrack as often as you want. Everything is associated with your account. If you delete anything, you can open the game's properties and verify the local files to restore anything missing or modified.


What are the individual names of these nine different PVC fittings?

Question: What are the individual names of these nine different PVC fittings?

(source: pvcworkshop.com)
Answer: From left to right, top to bottom:

3 way elbow
4 way tee
5 way tee
tee
internal cap
cross
90 degree elbow
slip sling tee
45 degree elbow

Since these appear to be structural PVC fittings, one source: http://www.formufit.com/structural-pvc-fittings/?sort=featured&page=1


Value at position 0 while updating from Angular 8 to 9

Question: I was updating my project from Angular 8 to 9 when after following the update guide (+ running npm update) on update.angular.io and trying to compile the website using ng serve I get the following error:
ERROR in Failed to compile entry-point angular-font-awesome (es2015 as esm2015) due to compilation errors:
node_modules/angular-font-awesome/dist/angular-font-awesome.js:3968:26 - error NG1010: Value at position 0 in the NgModule.imports of AngularFontAwesomeModule is not a reference: [object Object]

3968                 imports: [CommonModule],

Any help is appreciated.
UPDATE
My ng version output:
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 9.0.2
Node: 12.13.1
OS: win32 x64

Angular: 9.0.1
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Ivy Workspace: Yes

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.900.2
@angular-devkit/build-angular     0.900.2
@angular-devkit/build-optimizer   0.900.2
@angular-devkit/build-webpack     0.900.2
@angular-devkit/core              9.0.2
@angular-devkit/schematics        9.0.2
@angular/cdk                      9.0.0
@angular/cli                      9.0.2
@angular/material                 9.0.0
@ngtools/webpack                  9.0.2
@schematics/angular               9.0.2
@schematics/update                0.900.2
rxjs                              6.5.4
typescript                        3.7.5
webpack                           4.41.2

My package.json:
{
  "name": "avior",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.1",
    "@angular/cdk": "~9.0.0",
    "@angular/common": "~9.0.1",
    "@angular/compiler": "^9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/forms": "~9.0.1",
    "@angular/material": "^9.0.0",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "^9.0.1",
    "@angular/router": "~9.0.1",
    "@fortawesome/fontawesome": "^1.1.8",
    "@ngtools/webpack": "^9.0.2",
    "angular-font-awesome": "^3.1.2",
    "angular-tree-component": "^8.5.4",
    "bootstrap": "^4.4.1",
    "chromedriver": "^79.0.3",
    "core-js": "^2.6.11",
    "font-awesome": "^4.7.0",
    "fontawesome": "^5.6.3",
    "gitignore": "^0.6.0",
    "jquery": "^3.4.1",
    "moment": "^2.24.0",
    "popper.js": "^1.16.1",
    "rxjs": "^6.5.4",
    "tslib": "^1.10.0",
    "webdriver-manager": "^12.1.7",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.2",
    "@angular/cli": "^9.0.2",
    "@angular/compiler-cli": "^9.0.1",
    "@angular/language-service": "~9.0.1",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "^2.0.8",
    "@types/node": "^12.11.1",
    "angular-ide": "^0.9.73",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "^5.4.3",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "^3.7.5"
  }
}

My tsconfig.ts:
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "downlevelIteration": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

UPDATE 2
After uninstalling the angular-font-awesome package I only get one error with an Angular plugin:
ERROR in Failed to compile entry-point angular-tree-component (module as esm5) due to compilation errors:
node_modules/mobx-angular/dist/mobx-angular.d.ts:8:22 - error NG6002: Appears in the NgModule.imports of TreeModule, but could not be resolved to an NgModule class

8 export declare class MobxAngularModule {

Answer: If you want to use font-awesome in angular 9+ you can use this command :
 ng add @fortawesome/angular-fontawesome

Credit goes to FortAwesome
Answer: So removing angular-font-awesome using npm uninstall angular-font-awesome and adding new package using ng add @firstname.lastname@example.com and then disabling IVY compiler by adding
"angularCompilerOptions": {
    "enableIvy": false
  }

into tsconfig.app.json and ts.spec.json seems to have solved the issues.
Comment: actually  i remove package and add version 0.6.0 and worked correctly
Comment: @Albaz But that's exactly what I did?.. I don't see your point.


How can I increase my war score when the enemy is fully conquered?

Question: I am fighting an enemy and I set just a single war goal with score 94. I already destroyed all their fleets and all their spaceports and I'm occupying all their planets, but I still haven't reached that score, and so I can't finish that war with any advantage.
Is there anything else I can do to increase my war score score, other than waiting? For instance, should I bother hunting down all their non-military stations?
Comment: Sue for white peace?
Comment: @DCShannon That's what I'll do if I can't find a way to increase my score. The question is, is there such a way :-)
Answer: You do not (despite what you might think), require 100 warscore in order to end the war.
Simply bring up diplomacy with your enemy and select your single wargoal. Whether or not they choose to accept your terms depends on their relative warscore (though 91 is a lot for a single planet, so I assume you would be fine) + other factors, such as relative military strength and length of war (with having a much smaller army increasing their willingness to negotiate, as does war that has been going on for longer times).
If you do not select the war goal, this method will offer white peace instead.
Comment: @Oak I'm not suggesting a White Peace - the capitulation mechanics mean you can get more wargoals with the same warscore as Time / Fleet Power changes.
Comment: My point is, I only have a single war goal, and it's higher than the current war score. I realize I can go with white peace instead, my question is whether there's a way to increase my score.
Answer: Non-military stations do add to war score if destroyed (they count as a battle), so if that's literally all they have left and can produce no more ships, go hunt them down.
Comment: Well, turns out that they had a hidden system somewhere, and occupying it sealed the deal. But I did notice non-military stations give war score, as you wrote, and it seems like a good way to get those last few points.


Let $A$ be positive semi-definite. Show that $a_{i,i}a_{j,j} \geq |a_{i,j}|^2$, $1\leq i<j \leq n$

Question: I was trying to do it by induction.
First let $$ A =  \begin{bmatrix} a & b \\ \overline{b} & c  \end{bmatrix}.$$
Since $A$ is PSD, $det(A) = ac - |b|^2 \geq 0$. So $ac \geq |b|^2$.
Now assume the hypothesis holds for all PSD matrices of size $(n-1)\times(n-1),$ and let $A$ be an arbitrary PSD matrix of size $n\times n$.
Since $A$ is PSD, it is also hermitian. So we can partition it as
$$ A =  \begin{bmatrix} B & y \\ y^* & a  \end{bmatrix},$$
where $B$ is of size $(n-1)\times(n-1)$, $y \in \mathbb{C}^{n-1}$, and $a\in\mathbb{R}$
Consider $a_{i,i}, a_{j,j}$ and $a_{i,j}$.
If $i,j \leq n-1$, then these entries correspond to the sub matrix, $B$. $B$ is also PSD, and so the claim is true via our induction assumption. Thus we only need consider the case where $i<j = n$.
And here's where I'm stuck. if $j = n$, then the inequality we're aiming for is $a_{i,i}a_{n,n} > |a_{i,n}|^2$.
Clearly $a_{n,n} = a$, and $a_{i,n}$ is one of the entires from $y$. But it's not clear to me how these will get me the remainder of what I need. I thought about doing the determinant again, but I don't think I can get it to workout.
Any thoughts would be greatly appreciated.
Thanks in advance.
Answer: No need for induction.
I am assuming that
$A$ is Hermitian.
Let $P=\begin{bmatrix} e_i & e_j \end{bmatrix}$, then $P^T AP \ge 0$.
Note that $P^TAP = \begin{bmatrix} A_{ii} & A_{ij} \\
\overline{A_{ij}} & A_{jj} \end{bmatrix}$, and since $\det (P^TAP) \ge 0$, you have the desired result.
Comment: This is really elegant.
Thanks again!
Comment: Well, $A$ is hermitian; not necessarily symmetric. But I think that your idea still holds.

Thanks for the suggestion!
Comment: Fixed :-). ${}{}$


Ring homomorphism and characteristic

Question: Let $F$ be a finite field. If $f : F \to F$, given by $ f(x) = x^3$ is a ring homomorphism, then

$ F = \mathbb{Z} / \mathbb{3Z}$
$ F = \mathbb{Z}/ \mathbb{3Z}$ or  $ F = \mathbb{Z}/  \mathbb{2Z}$
$ F = \mathbb{Z}/  \mathbb{2Z}$ or characteristic of $F$ is 3.
Characteristic of $F$ is $3$

For ring homomorphism, $f(x+y)= f(x)+ f(y)$ and $f(xy)= f(x) f(y)$ for $x,y \in F$. So, Charcteristic of $F$ must be 3 so that $ 3x^2y + 3xy^2= 0$, so $4$ option should be true but how to discard option 1?
Answer: Consider $(\mathbb Z/3\mathbb Z)[x]/(x^2+1)$. It is a field $\not=\mathbb Z/3\mathbb Z$ of characteristic $3$, so option $(1)$ is not true.

Similarly option $(2)$ is not a necessary condition for $x\mapsto x^3$ to be a ring homomorphism.

For option $(3)$, we shall show that it is necessary for $x\mapsto x^3$ to be a ring homomorphism that either $F=\mathbb Z/2\mathbb Z$ or $F$ has characteristic $3$.
By the binomial expansion, $x\mapsto x^3$ is a ring homomorphism if and only if $3(x^2y+xy^2)=0,\,\forall x, y\in F$. And this is true if and only if $3=0$ or $x^2y+xy^2=0$ in $F$.
The first case means $F$ has characteristic $3$.
The second case says that, when $x,y\not=0$, $xy$ is invertible, and hence $x+y=0$. This means that every non-zero element in $F$ is the additive inverse of $1_F$. As a consequence, there is only one non-zero element in $F$, i.e. $F=\mathbb Z/2\mathbb Z$.
Thus option $(3)$ is a necessary condition.

Since $\mathbb Z/2\mathbb Z$ has characteristic $2$, option $(4)$ is not necessary.

Hope this helps.
Comment: As an added bonus, if the characteristic of $F$ is $3$, the map $x\mapsto x^3$ is a generator for the (cyclic) Galois group of $F$ over $\Bbb Z/3\Bbb Z$. It's called the Froebenius morphism (the same is true for other primes as well).
Comment: @Gitika $x+x+x=(1+1+1)\cdot x=3\cdot x$. So $3(x^2y+xy^2)=0$ if and only if $3=0$ or $x^2y+xy^2=0$.
Comment: @Gitika In a group the inverse of an element is unique. Since a field under addition forms a group, the additive inverse of $1_F$ is unique, so there is only one non-zero element in $F$.
Comment: Thank you for the detailed answer.
Comment: What do you mean by 3=0? (What I understand by 3x in a ring is x+x+x.
Comment: If every non-zero element in F is additive inverse of 1, then how does it imply that there is only one non-zero element in F?
Comment: How to show that in a and d, ring homomorphism will be there between the fields?
Comment: @Gitika The function $x\mapsto x^3$ from $F$ to $F$ is a homomorphism if and only if the characteristic of $F$ is $3$. To see this, expand $(x+y)^3$ and see it is equal to $x^3+y^3$.
Comment: You proved it for $\Bbb{Z_2}$ which has characteristic 2..right?
Comment: Ah, sorry. I didn't think clearly about it. I meant to say that when the characteristic of a field is $3$, then $x\mapsto x^3$ is a ring homomorphism, without the other direction (only if).

Ring homomorphism and characteristic


select node ranges using XPath

Question: We are using XPath in a Java app and I was wondering: How do I select a set of nodes where the "terminating point" is a node not belonging to the same kind as it's siblings.
For example, I want to get two sets of  tags of size 3 and 2 from the example below:
<sample>

   <terminating />

</sample>

Comment: I can't see your example. Please post a complete (or complete within itself) XML file.
Comment: Post fixed. @ola_user: Have a look at the editor help box on the right side of the screen for your next post. :)
Answer: First of all, the result of an XPath expression is always either an atomic value, or a single node-set (or sequence in XPath 2.0). You cannot get a list of node-sets.
That said, for your specific example with just two groups and one terminator, you can just use preceding-sibling and following-sibling:
/sample/terminating/preceding-sibling::a
/sample/terminating/following-sibling::a

Answer: Extending on Pavel Minaev's answer - I would write a loop, like this ("i" being the loop index):

find all the <terminating> nodes with the help of
→ /sample/terminating
for each of them, find all the
→ ./preceding-sibling::a[count(preceding-sibling::terminating) = {i}]
for the last <terminating> node, also find the
→ ./following-sibling::a
Comment: I think it could be done even easier - given `$i`, it would be just `/sample/a[count(preceding-sibling::terminating) = $i - 1]` to get all `a` in `$i`th group.
Comment: You are right, this would give the same result. Complexity is about the same, though.

select node ranges using XPath


Kafka cluster on AWS crash

Question: I've been having a recurring issue with a kafka cluster running on AWS EC2 instances.
Description

Kafka cluster version 0.10.1.0
3 brokers cluster
topics have 6 partitions per broker
Instance type is m4.xlarge

Symptoms
The following will happen at random intervals, on random brokers
From the logs here is the information I could gather :

Shrinking Intra-cluster replication on a random broker
(I suppose it could be a temporary network failure but couldn't produce evidence of it)
System starts showing close to no activity @02:27:20 (note that it's not load related as it happens at very quiet times)

From there, this kafka broker doesn't process messages which is expected IMO as it dropped out of the cluster replication.
Now the real issue appears as the number of connections in CLOSE_WAIT
is constantly increasing until it reaches the configured ulimit of the system/process, ending up crashing the kafka process.

Now, I've been changing limits to see if kafka would eventually join again the ISR before crashing but even with a limit that's very high, kafka just seems stuck in a weird state and never recovers.
Note that between the time when the faulty broker is on its own and the time it crashes, kafka is listening and kafka producer.
For this single crash, I could see 320 errors like this from the producers :
<code>java.util.concurrent.ExecutionException: org.springframework.kafka.core.KafkaProducerException: Failed to send; nested exception is org.apache.kafka.common.errors.NotLeaderForPartitionException: This server is not the leader for that topic-partition.
</code>

The configuration being the default one and the use being quite standard, I'm wondering if I missed something.
I put in place a script that check the number of kafka file descriptors and restarts the service when it gets abnormally high, which does the trick for now but I still lose messages when it crashes.
Any help to get to the bottom of this would be appreciated.
Answer: Turns out there was a deadlock in the version I was using.
Upgrading fixed the issue.
See ticket about the issue :
https://issues.apache.org/jira/browse/KAFKA-5721

Kafka cluster on AWS crash


What's the most efficient way to replace old locomotives in OpenTTD

Question: I have a bunch of trains transporting coal back and forth and I wanted to know what's the most effective way to replace a locomotive when it expires.
Right now I tell it to stop at the depot, sell it, buy the new one, and tell it to go again (by telling it to stop at the depot for maintenance if necessary). It is a bit painful if you have 10 trains to replace. Is there a better way to do it?
Answer: There is an option to autoreplace trains when they go for servicing. Go to the Trains menu and select the 'Replace vehicles' button (this is also possible for all other types of vehicles)

Then choose the train you have currently and its replacement, and select the 'Start Replacing Vehicles' option to start autoreplacement.

When all vehicles are replaced the old vehicle in the autoreplace list will be greyed out, and you can choose 'Stop Replacing Vehicles' to remove it from the list.
Comment: Don't forget that if you upgrade to a different type, like Electric or something, that the track has to be able to handle it, or you've just replaced it with a dead weight.
Comment: Also, if you have a 14 unit train (one engine) and replace the train unit with a double-headed train (and end up with 15 units) you may need to expand your stations to avoid a load time pentaly.
Comment: Worse, especially if you've taken over any competitors, your new trains might be too long to fit in the double-track segments.


How to make touch-screen scrolling work in Firefox Quantum?

Question: Using Firefox quantum 57 and Ubuntu 17.10, I am unable to scroll a web page by touching the screen and sliding the page.  However this works in Chrome browser.
How to make touch-screen scrolling work in Firefox Quantum?
Comment: Does this answer your question? [How to enable touchscreen scrolling in FireFox?](https://askubuntu.com/questions/853910/how-to-enable-touchscreen-scrolling-in-firefox)
Answer: The same solution for Firefox 50 and Ubuntu 16.xx still works for Firefox Quantum 57 and Ubuntu 17.10: Ubuntu 16 and touchscreen scrolling in FireFox
The solution is to launch firefox using:
env MOZ_USE_XINPUT2=1 firefox

You can make this permanent by modifying the launcher using the following:
sudo sed -i "s|Exec=|Exec=env MOZ_USE_XINPUT2=1 |g" /usr/share/applications/firefox.desktop

To undo this change, use:
sudo sed -i "s|Exec=env MOZ_USE_XINPUT2=1 |Exec=|g" /usr/share/applications/firefox.desktop

EDIT: Per @poomerang's comment below, if you are using the Snap version of Firefox, the path in the above commands should be /var/lib/snapd/desktop/applications/firefox_firefox.desktop
Comparing touch scrolling in Firefox Quantum, using this solution. with touch scrolling in Chrome:

Scrolling is one finger only; two finger scrolling causes the web page to zoom.  This is different from Chrome, where you can scroll using two fingers, but still pinch to zoom or un-zoom.
You can only scroll vertically or horizontally, depending on which direction your initial motion is in; this is different from Chrome, where you can scroll horizontally or vertically (or in circles) without lifting your finger(s).
Comment: Ok so, when you extract the source, find:  /gfx/thebes/gfxPrefs.h . Open that file and look for ui.click_hold_context_menus.delay (    the full line is DECL_GFX_PREF(Live, "ui.click_hold_context_menus.delay",     UiClickHoldContextMenusDelay, int32_t, 500);   )  You want to change that 500 at the very end to 9999 (that's 500ms of delay to 10 second). That's it. You won't have a context menu anymore but at least touch will be stable in X11. Once you get touch working, I'd really recommend the Tablet Gestures addon, it puts ff on parity with chrome for touch at that point.
Comment: This still works for Ubuntu 22.04, BUT: the file to modify is no longer /usr/share/applications/firefox.desktop (doesn't do anything), but /var/lib/snapd/desktop/applications/firefox_firefox.desktop . Apparently
Comment: YOU ARE A GOD PJ!!! I've been searching for how to do that for 2 months now and using half baked extensions for touch dragging that really didn't work that well. Funny thing is that I came across this answer while searching for something completely different... Thanks!
Comment: After a bit of testing, it seems to be too unstable to be usable, probably why it's still off by default. It works great at first but as soon as you long click to select text, it makes a context menu popup and things turn really buggy after that. Ah well. Probably a work in progress.
Comment: @thebunnyrules I think I'm having the same problem as you, check out https://bugzilla.mozilla.org/show_bug.cgi?id=1451587 if you have the chance.
Comment: @blendmaster When I use FF wayland, the instability goes away. The popup menu still clashes with caret but a double tap  can be used instead of a long press to call it. For X11, I just disabled long press for context menu as a temp solution. I can tell you how to do so if you know how to compile ff.
Comment: Thanks for the details @thebunnyrules . If you can post the patch somewhere for disabling long press that'd be helpful. Might be able to add debugging info for the issue as well.
Comment: Sorry for the delay. I can give you some detailed instructions but I wouldn't want to upload the whole file because these files tend to get updated and changed and you don't want to overwrite those updates just for my one line patch.
Comment: @blendmaster I put a more complete post on the thread you mentioned.  Good luck!
Comment: Is adding `export MOZ_USE_XINPUT2=1` to `~/.profile` a good idea? It seems to work for me but I was wondering why no one proposed it


Is there an easy way to protect all endpoints?

Question: I have loads of endpoints to protect in my SvelteKit app. I dont' want to add following in all of them:
    if (!request.locals.user) {
        return { status: 401 };
    };

Can I do this from hooks.js or in another easy and safe way?
Answer: Currently there is no way to add hook per endpoint in sveltekit and implementing it in the global hooks.js will be difficult because you will have to maintain protected routes path every time you change it.
The only way to do it as you said is to add the auth check in every route which is also will be difficult to maintain. to avoid that we can extract the auth check logic into its own function. the function will accept the handler that holds the route hooks:
// compose one handler function out of number of handlers.
// it will execute handlers in sequence until one returned a value
function withHandlers(...handlers) {
    return async (request) => {
        for (const handle of handlers) {
            const result = await handle(request)
            if (result !== undefined) {
                return result
            }
        }
    }
}

// implementation of auth check
function authHook(request) {
    if (!request.locals.user) {
        return {
            status: 401,
            body: {
                message: 'unauthorized'
            }
        };
    }
}

// create a new handler with auth check
function withAuth(handle) {
    return withHandlers(authHook, handle);
}

// your final endpoint with authentication check
export const get = withAuth((request) => {
    return {
        body: `Hello ${request.locals.user}`
    };
});

Comment: I had to tidy up a bit but now I am ready to try out your answer...I am a bit dumb...would you mind to split your code example with an example for each file `hooks.js`, `index.js`?


Javascript Regex Form validation returning error

Question: I have been trying to validate my form email input with these line of codes.

function validate() {
  var emailFirst = document.getElementById('email1');
  var emailFirstRGex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  var emailFirstTest = emailFirstRGex.test(emailFirst);

  if (emailFirstTest === false) {

  alert('hello20');
}
   }

My form

<form class="needs-validation" novalidate method="POST" action="nomination2.php" onsubmit="validate()">

I keep getting the hello20 response. Meanwhile i have tried this regex against emails on the console without error. How do I solve this?
Answer: emailFirstTest is declared inside your function, so checking for it outside the function means it is out of scope and doesn't exist.
Just define it above your function:
var emailFirstTest  = '';

function validate() {
  emailFirst = document.getElementById('email1');
  var emailFirstRGex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  var emailFirstTest = emailFirstRGex.test(emailFirst);
}

Comment: I did not declare it outside the function, i posted the question wrongly and I have corrected it.
Comment: console log the emailFirst  var
Comment: I got the correct email I entered, when I console.log, it is just not passing the test
Comment: `emailFirstRGex` is a string. Where is this `.test()` function coming from?
Comment: Try `var regex = new RegExp(emailFirstRGex ); var emailFirstTest = regex.test(emailFirst);` If it works I'll update my answer
Comment: test returns a boolean true or false
Comment: try putting your regex string into a RegExp object like i commented above


How can I download the right printer driver for my new Epson ET-4810 with ubuntu 20.04 LTS?

Question: I am looking for VERY detailled help with the installation, because I have never done such a thing before...
Comment: Epson 4800-series printers should not require "printer drivers" at all. They speak IPP, a standard that does not need those pesky drivers at all. Connect to the printer using the Printers application.
Comment: First, try printing. The printer should be automatically recognized. If it does not work, try googling. I found [this tutorial](https://tutorialforlinux.com/2022/04/05/printer-epson-et-4850-ubuntu-22-04-installation-step-by-step/) for example. Try it and [edit your question](https://askubuntu.com/posts/1496912/edit) with details like what you did and exact error messages you got at which step.
Answer: Look for the Desktop Search icon on your dock or shortcut bar.

Click it.
Your Desktop Search screen will open. At the top of the screen is a Search box. Start typing "printers"

Click on the Printers application. A new window will open.

Click on Add.
Follow the prompts to add your printer.

Most new printers don't require drivers anymore. Use the hardware database at http://openprinting.org to check if your printer requires a driver to be compatible with Ubuntu.


How to balance thermostat settings between zones to maximize efficiency?

Question: I recently purchased a house so this is my first winter in it.  The house was built in 1939 so most of the house is on a single heating zone using hot water radiated heat.  The radiators are cast iron and recessed into the walls.  However, there is an addition to the house circa early 2000's that uses baseboard hot water radiators.  The addition also seems to be less heat efficient, probably because it has more windows, and has drywall instead of plaster.  The addition is on a separate heat zone from the rest of the house.  They are controlled by two different thermostats.
I'm trying to figure out how to set the thermostats to maximize heat efficiency.  So far I've been assuming that the baseboards are less efficient than the cast iron radiators, and so I've been setting the thermostat for the addition far lower (about 5 degrees) less than the main thermostat.  This basically means that the baseboards in the addition never switch on, and the addition remains cooler than the rest of the house (which is okay - it is a kitchen / dining room which we are okay with being cooler).  The addition just gets heated via heat transfer from the other rooms.
Is this the best approach?  Should I set the addition thermostat to the same temperature?  What other considerations are there in order to balance my zones correctly to maximize energy efficiency?
Comment: Don't assume that 75 on one thermostat is the same as 75 on another.  They all seem to have slight variations between them. Some models support "calibration" to put it in line with what you expect.
Comment: I found an interesting Q&A on this: http://www.finehomebuilding.com/how-to/qa/baseboard-vs-radiator-heat.aspx . Nothing about efficiency differences, but it is worth noting that a room heated with radiators may feel warmer than a room heater with baseboard convectors even when the air temperatures are the same.
Answer: I think you are saying that you have two zones on one boiler, each fed by its own pump and thermostat (i.e. the radiators have been converted to hot water).  My answer is based on this assumption.
Since they're both on the same boiler, the water is heated with equal fuel efficiency.
The two loops probably are different in how efficiently they transfer that heat to the room.  Low efficiency in transferring heat to the room will decrease the heating capacity of your boiler, which is a problem if you can't get the house warm enough on a cold night.  But as long as you're keeping up with heat demand, efficiency in transferring heat doesn't make a difference with fuel usage.  (You can tell how efficient they are in transferring heat to the room by feeling the temperature at the end of the loop -- if it's pretty cold, the heat was transferred to the room very well)
So, the answer is that you should set the thermostats to the lowest temperature where you're comfortable.  Your addition from 2000 likely has a lot more insulation than the original 1939 house (in 2000 the building code required a lot of insulation, 1939 not so much), so if you want to pick the more efficient one to heat, heat the addition not the main house.  It will be more efficient because you'll lose less heat because of the greater insulation.
Comment: +1 for "you should set the thermostats to the lowest temperature where you're comfortable".   Pretty much anything else is overthinking the problem.   Open new questions (or review existing ones) if you have questions about improving insulation, operation of your system, etc.


C++ desktop applications framework

Question: I am not new to c++,but i have not found a c++ desktop applications framework.I have found one and it seems to complex.Are there other frameworks available for c++ out there?.
Comment: @Undgerman: No, you're here for more than a month, and obviously haven't even bothered to read the [FAQ](http://stackoverflow.com/faq) yet. Schlecht.
Comment: I am new around,plus i have accepted all the last answers to my questions.
Answer: There are various choices when it comes to c++ Desktop app frameworks,
it mainy depends on your skills and on the plattform you want the app to run.
Two Opensource Frameworks that are plattform independent, I have used so far are
The QT-Framework from trolltech now nokia and wxWidgets
if you need something in the multimedia area have a look at openframeworks
Comment: true
but openframeworks still better in this area and also easyer to start with
Answer: Qt - forever! It is mature and cross-platform.
http://en.wikipedia.org/wiki/Qt_(framework)
Comment: qt licensing is complex. read more about it, before considering. https://www1.qt.io/licensing-comparison/
Answer: There's wxWidgets and Qt, both Open Source and free. Qt became very popular recently.
Also, you might want to look at C++ Builder, which allows you to build C++ applications in a VB-like way using a component framework built in Delphi. (That's a commercial one. They used to have a free version, but I don't know whether that still exists.)
Answer: A great framework is Qt.

C++ desktop applications framework


Matlab - How can I sort rows for a bar chart without losing row names?

Question: I am analysing double arrays in Matlab to create bar plots. Each row corresponds to a country and has specific values that are compared. The names of the rows are stored in a cell array and implemented in the bar chart by set(gca,'XTickLabel',{Combined{:,1}}). This assumes that the order of the rows remains the same during the analysis.
However, in my analysis I need to sort rows to find the best and worst performing countries. By doing this, I cannot plot the bar charts with the countries corresponding to their countries. This is how I sorted the double data:
[~,SortLR2018] = sort(d2018(:,4));
LR2018 = d2018(SortLR2018,:);

Does anyone know how I can sort the names of the countries (cell arrays) such that they match the sorted values (double arrays)?
Comment: does this `set(gca,'XTickLabel',{Combined{SortLR2018,1}})` work? I think you can use the indices of the sorted array.
Answer: The easiest way would be to index the cell array containing the names with the indices of the sorted data:
set(gca,'XTickLabel',{Combined{SortLR2018,1}})

I would recommend implementing your data as tables, which allows you to link the names to to all kinds of row data.
Comment: Thank you, this solution works! I think I made a mistake with selecting column data. I accepted your answer!


mapping of a point from a sphere into UV plane

Question: I am reading the book An introduction to raytracing by Eric Haines and it mentions an algorithm to map a point from a sphere into a UV plane, it calls it Inverse Spherical Mapping (page 49). I googled a lot about this term and could not find a single piece of information regarding it.
Given the normal to a point on a sphere (Sn) and the sphere's north pole unit vector (Sp) and a unit vector from the sphere's origin to the sphere's equator (Se) as shown below

Using the right-hand coordinates system. It drives the following formula for v and u

I understand the Dot product yields cosine of an angle between two vectors, but why -Sn? from the picture v starts from the south pole and varies towards the north, but why the minus sign? (the book mentions v varies from -Sp to +Sp )
As for u I am not sure why we do divide by sine phi. and why do we take the cross product to determine u? (I know the cross-product gives us a perpendicular vector to both, which is probably used to know on which side the normal is, but I am not sure exactly how that worked as the equator is changing, so it can be both right and left)
Comment: For the -Sn it has been sorted, the problem I had was I was using the left-hand coordinates system and the book strictly stated it was using right-hand coordinates (maybe my habit got me to keep using the left-hand coordinates)
However, I still don't know how the cross-product is used here, or why the division with sin(phi)
Comment: $(\vec A \times\vec B) \cdot \vec C$ is the "scalar triple" product, the sign flips under inversion.
Comment: hmm that was a little cryptic the scalar triple product can be rewritten as $\left \| \vec A \times \vec B \right \| \left \| \vec C \right \| sin(\theta)$
Comment: Thanks, I got it in the end, it seems to be a standard conversion from the spherical coordinate system.
Answer: IIRC this and some other texture mapping/projection techniques are discussed in Watt & Watt's Advanced Animation and Rendering Techniques
Skip forward to around page 180.  FWIW that has a reference to a 1946 (!) document but I haven't gone looking to see if it's the original source :)

Though 'old', Watt & Watt is well worth buying IMHO.
Answer: I found the answer, someone pointed me to the spherical coordinates system and it is the exact match. as shown here
The only difference is that, this assumes phi is actually calculated from the z-axis towards xy-plane, however in the picture I shared in the question V varies from south pole to north pole, for that we take the negative of the north pole in V calculation.


Permissions of a new User changed mine

Question: I have a pc which is running Linux Ubuntu 14.04 and few weeks ago a colleague of mine added him to the pc and since then I can do sudo something but I can't perform certain actions like:

installing a new printer
go to the System Folder
etc.
How can I solve this problem?

When, for example, I try to install a new printer I have the thing showed in this image:
Comment: That particular dialog is for policykit permissions, not sudo.
Comment: I know. It was an example to tell you what is happening in my computer. I was working before adding my colleague username to the computer. Now it asks for his password. How is it possible if this computer is meant to be for me?
Comment: How was this user added? Did your uid change? Or group memberships?
Comment: I don't know if it changed but now I have something like that:

me@flylab:~$ id me

uid=650403(me) gid=29077(groupXXX) groups=29077(groupXXX)

me@flylab:~$ id colleague

uid=200328(colleague) gid=29077(groupXXX) groups=29077(groupXXX),27(sudo)

I see that there is a 27(sudo) on my colleague account.
Comment: I don't know if my uid changed or not, but can my colleague do something to fix this?
Comment: Since your colleague is a sudoer, sure. He can add you to the `sudo` group: `adduser me sudo`.
Comment: But what does that SUDO mean? because I am able to do sudo right now.
Answer: From the what I can understand, this is the state of things:

You were the original user, and probably have sudo privilege either by your username or by your other groups.
But the PolicyKit privileges are still the default from Ubuntu (members of groups sudo and admin, and the root user). You can verify this: sudo cat /etc/polkit-1/localauthority.conf.d/51-ubuntu-admin.conf should give:
[Configuration]
AdminIdentities=unix-group:sudo;unix-group:admin

So if you add yourself back to the sudo group (or the admin group, if it exists), you'll gain the PolicyKit privileges as well:
sudo adduser $(whoami) sudo

Comment: Thanks a lot. You explained me well and I solved my problem.

Permissions of a new User changed mine


Draw sprite in cocos2d on top of others

Question: I am playing in cocos2d and wanted know how can i give a sprite a layer depth meaning how can i keep a sprite on top of others?
Answer: You could do something like this:
Assuming your class is a subclass of CCScene
<code>-(id) init
{
    if( (self=[super init] )) {
        CCLayer *foreground = [CCLayer node];
        CCLayer *background = [CCLayer node];

        CCSprite *sprite1 = [CCSprite spriteWithFile:@"sprite1.png"];
        CCSprite *sprite2 = [CCSprite spriteWithFile:@"sprite2.png"];
        CCSprite *sprite3 = [CCSprite spriteWithFile:@"sprite3.png"];

        [sprite1 addChild:sprite2 z:-1];   //This z:-1 means that sprite 2 is behind sprite 1

        [foreground addChild:sprite1];
        [background addChild:sprite3];

        [self addChild:background z:0];   // z:0 is default, you don't need to add it.
        [self addChild:foreground z:1];   // z:1 is infront of z:0

    }
    return self;

}
</code>
The bit you need to learn how to use is the z: parameter of add child. If you add a child without the z parameter, the child is placed on top.

Draw sprite in cocos2d on top of others


How to pass the value to the dropdown list to be highlighted value on Edit template?

Question: The label lblTempLib in the Form has the data coming from table A. This needs to be passed on to the dropdown list as the selected value to datasource in the edit template.
This is the object datasource for LibDS (markup):
SelectCommand="SELECT [LibName] FROM [tblBuilding]"></asp:SqlDataSource>

<asp:FormView ID="frmUpdateIncident" runat="server" DataSourceID="InciDetailDS" OnDataBound="frmUpdateIncident_DataBound">
    <EditItemTemplate>
        <asp:Label runat="server" ID="lblLib" Text="Library:" CssClass="style_bold"></asp:Label>

        <asp:Label ID="lblTempLib" runat="server" Text='<%# Eval("Library")%>'Visible="true"></asp:Label>
        <asp:Dropdownlist runat="server" ID="ddLib" DataTextField="LibName" DataSourceID="LibDS" >
        </asp:Dropdownlist>

VB.NET code:
Protected Sub frmUpdateIncident_DataBound(sender As Object, e As EventArgs) Handles frmUpdateIncident.DataBound
    Dim ddLib As DropDownList
   Try
        If Page.FindControl("ddLibrary") IsNot Nothing Then
            ddLib = DirectCast(frmUpdateIncident.FindControl("ddLibrary"), DropDownList)
            ddLib.Items.FindByText(strLibName).Selected = True
        End If
 Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Comment: What's wrong with your current code? Does it throw errors, or not work correctly?
Comment: Yes. The error is "Object reference not set to an instance of an object." when it hits ddLib.Items.... line.
Comment: It sounds like your DropDownList is not databound yet.  Can you use a debugger to check and see if `ddLib.Items` has anything in it when the FormView databound event fires?
Comment: Yes it has 3 items. This is my updated post: http://stackoverflow.com/questions/20804703/nullreferenceexception-was-unhandled-by-the-user
Answer: Ok, I finally got it. Need to pass the index value to the dropdown SelectedIndex value as this property can get and set the value unlike SelectedValue.
strLibName is the value passed on by the previous form.
I hardcoded ddLib.SelectedIndex in here to test it but I will be fixing it by passing the list index value.
VB.Net Code:
    Protected Sub frmUpdateIncident_DataBound(sender As Object, e As EventArgs) Handles frmUpdateIncident.DataBound
    If frmUpdateIncident.CurrentMode = FormViewMode.Edit Then
        Dim ddlib As DropDownList
        ddlib = DirectCast(frmUpdateIncident.FindControl("ddLibrary"), DropDownList)
        If ddLib IsNot Nothing Then
            If ddLib.Items.Count > 0 Then
                If strLibName IsNot Nothing Then
                    ddlib.SelectedIndex = 2
                    Dim strtest As String = ddlib.SelectedValue.Trim
                End If
            End If
        End If
    End If
End Sub


How to get current view HTML source and pass it JSF ManagedBean as String

Question: I want to get current view HTML source and pass it to JSF managed bean as a parameter. Is there anyway in JSF I can do this?
Comment: I wanted to geneate a pdf document on fly using Itext+flying saucer for I need the HTML of my page
Answer: You can't do it in JSF as it doesn't run in the webbrowser at all.
Your best bet is using JavaScript. The below example sets a hidden input value with the HTML source code when the submit button is clicked:
<h:form id="form">
    <h:inputHidden id="source" value="#{bean.source}" />
    <h:commandButton value="submit" action="#{bean.submit}"
        onclick="document.getElementById('form:source').value=document.getElementsByTagName('html')[0].outerHTML"
    />
</h:form>

In the action method, it's in the particular example then just available by the source property.
Comment: Awesome It's working perfectly fine.Thanks Balu....But I tried same with Jquery by getting HTML using .html() of the entire div but not able to pass to backend.
Comment: not always works. I implemented this example in my application, but when outerHTML is very large something goes wrong. On click I haven't the managed bean called, but only a page refresh. Maybe inputHidden can't contains this large value ? (outerHTML number char is : 1954000)
Comment: Not a JSF problem but a serverconfig problem. Most servers have a default limit of 2GB on POST body size. Consult server documentation how to adjust it.
Comment: but never reach 2GB, is impossible, is only text . Server is Tomcat 9. Maybe 2MB ? where I can change this value ?
Comment: Ok thank you. Changed server.xml , I've set maxPostSize="6291456" in Connector tag. Now works!


How to Invoke K2 workflow from MVC

Question: All
Just wondering if by any chance can we invoke K2 workflow from controller?
I have a UI developed in MVC and need to implement some workflow... Is there any way we can achieve this ? Are there any K2 APIs ? we can call directly from controller ?  Any pointers, example will help.
Thanks in advance.
Answer: You can most certainly do anything with K2 from MVC.  They have a full range of APIs (web services, dlls, etc.).  You can view the developers reference here.
Your K2 installation contains all the *.dll's you need.  The default location is C:\Program Files (x86)\K2 blackpearl\Bin.
Here is a simple example of starting a workflow using the SourceCode.Workflow.Client.dll: (NOTE: I write my own class libraries to handle all of my K2 interactions, to separate the work OUT of my controllers, but you could simply place the method below in your controller if you wanted).
<code>using SourceCode.Workflow.Client;

public class MySampleK2Service: IMySampleK2Service
{

    private readonly string serverHost;
    private readonly string impersonatedUser;

    public MySampleK2Service(string serverHost, string impersonatedUser)
    {
        this.serverHost = serverHost;
        this.impersonatedUser = impersonatedUser;
    }

    public int StartNewWorkflow(string processName, string folio)
    {
        using (var connection = new Connection())
        {
            connection.Open(this.serverHost);

            if (this.impersonatedUser != null)
            {
                connection.ImpersonateUser(this.impersonatedUser);
            }

            var processInstance = connection.CreateProcessInstance(processName);
            processInstance.Folio = folio;
            connection.StartProcessInstance(processInstance, true);

            return processInstance.ID;
        }
    }
}
</code>
Answer: You may also use the Web Services provided by K2 called K2Services. With those, you don´t need any reference.
You can for instance use the REST API and use the GET method to easily start a new process.
If you need more control and to pass data thru DataFields, you may use the POST method.
More information here.

How to Invoke K2 workflow from MVC


Router-level middleware order using Express.js

Question: I have the following routers:
/* GET /users/username */
router.get("/:username", function(req, res, next) {
  User.findOne({
    username: req.params.username
  }).exec(function(err, user) {
    if (err) return next(error);
    res.json(user);
  });
});

/* GET /users/id */
router.get("/:id", function(req, res, next) {
  User.findById(req.params.id, function(err, user) {
    if (err) return next(err);
    res.json(user);
  });
});

In the above order, /* GET /users/id */ will return null, and if I swap the order the /* GET /users/username */ will result in this error:

Cast to ObjectId failed for value "Guest" at path "_id" for model "User"

Basically, the second middleware is being ignored. However, both are needed for different behaviors. I'm using AngularJS $resource to interact with RESTful server-side data sources.

Why can't I use both simultaneously? Why is the second middleware ignored?
In which order should these two routers be to both working?
Answer: It's better to route by doing:
router.route('your/route').get(aJsFile.function);
Then, instead of the exec, just write
attributes: ['id', 'username']
where: {username: username}
Or something like this.
Answer: The second middleware is ignored, because the url pattern is the same... How do you want the router make the differenciation between an 'username' or an 'id';
You've got to check if it's an id first per exemple.
router.get("/:username", function(req, res, next) {
  const username = req.params.username;
  if (!isNaN(parseInt(username)) {     // <------ Check if it's an ID
     next();
  } else {
  User.findOne({
    username: req.params.username
  }).exec(function(err, user) {
    if (err) return next(error);
    res.json(user);
  });
   }
});

/* GET /users/id */
router.get("/:id", function(req, res, next) {
  User.findById(req.params.id, function(err, user) {
    if (err) return next(err);
    res.json(user);
  });
});

Comment: I see. that's right, the url pattern is the same. I've tested your solution, and it seems working fine. However, one minor issue is, what if the username is an Integer? Is there any alternative to check the username/ID type, e.g. Mongo Object for ID?
Comment: The other solution is really to set a specific pattern to your id route : `/connectById/:id`


Create class from color code with mixin sass

Question: I want to create a class with a color code, but I cannot split the color code to get only the text without the <code>#</code> character. See my example below:
<code>.background-ccc {
    background:#ccc;
}
</code>
I want to use mixin like this:
<code>@mixin background($color){
   $colorwithout: ...get color code without # here...
   .background-#{$colorwithout}{
      background:$color;
    }
}
</code>
using:
<code>@include background(#ccc)
</code>
Answer: Here it goes:
Demo
<code>@function str-replace($string, $search, $replace: '') {
    $index: str-index($string, $search);

    @if $index {
        @return str-slice($string, 1, $index - 1)+$replace+str-replace(str-slice($string, $index + str-length($search)),
            $search,
            $replace);
    }

    @return $string;
}

@function to-string($value) {
    @return inspect($value);
}

@mixin background($color) {
    $colorwithout: str-replace(to-string($color), '#', '');

    .background-#{$colorwithout} {
        background: #{$color};
    }
}

body {
    @include background(#ccc);
}
</code>


best practice: how to handle data entry / modification & storing changes thereof

Question: I have a page (HTML) containing multiple tabs, all filled with various settings. Those settings are further divided into groups which are nothing more than separate REST calls to the server. Each group can be stored / restored separately. Settings are of all possible types: select, input, checkbox, tables with hundreds of items, etc.
I have looked around this site what best practice for modifying these settings would be, but I seem to have only encountered questions where the asker had already decided on what approach to use. To name a few:

Save / revert buttons above &/ below the form (group of fields)
Save / revert buttons next to each & every entry field
General Save / revert button in page header, valid for entire page
No button at all, data is stored in the background as it is entered by the user (possibly supported by alerts notifying user that changes have been stored)
Page leave guard dialog prompting to save the changes
Some that I missed?

I've seen many different implementations on the web, but each seems to have its shortcomings. Sometimes the user will want to be able to cancel all changes, sometimes they want to have everything stored as soon as they enter it, etc. I know I can't make everyone happy, but I do want something that will be intuitive, even if it's not a particular user's preferred way of entering data.
What is currently the most intuitive way of supporting the user while they enter / adjust hundreds of settings?
Answer: You ask the most 'intuitive' way ... I think it is when user is able to 'know' at all times where he/she is while updating the settings. With hundreds of settings organized in groups, its easy to 'forget' what was changed and what was not during the course of huge update. A summary of log changes in the side bar (right side for ex: as shown in pic) would be invaluable. Log should also show when data was saved. For example user works with group 1 , changes bunch of check boxes, drop downs etc, the log should show each value change and time of save etc. It comes down to organization, proper intuitive grouping, UI separations (tabs, panels) or if it fits your model, tree structures where you can drill down to the data points (settings) etc.. Each section should have an auto save (again log showing in the right panel in real time).. I think this would be easy ,user friendly and more intuitive.
May be a check box to undo a change one by one or 'all' will be useful. Something as shown. I am sure I am oversimplifying, but hope it makes you think in the right direction.
Comment: We ended up implementing just this. Thanks for the tip.
Answer: The best solution I have seen so far is made by Intuit with their Online TurboTax product. The complexity of the domain is enormous, the price of a mistake is colossal. They've split the whole domain into groups of simple questions. By answering these questions users navigate their way in their tax report. If something is irrelevant to their particular case, the respective branch is not shown anywhere. There is also a multilevel, but intuitive navigation system enabling users to access the parts of their report, drill down, correct answers etc.
Applying this to your initial question, I would say that if you have a lot of settings which users can configure all it once, then this will lead to a confusion. That said, I would try to see, if we can split the universe of settings into smaller subsets, let user focus on a subset, provide navigation between the subsets.


How do I splice a drywall metal outside corner bead?

Question: When re-finishing my ceiling (formerly popcorn, now smooth) I had some trouble with the edge of the tray ceiling in the master bedroom. Since the length of the tray was longer than a standard metal outside corner bead, the builder spliced several together by overlapping a few inches.
For future reference, is that the correct method for splicing? It was really hard to get a smooth coat of mud over it, since it was a sharp irregularity on the corner. (I never did get it perfect.) If the corner beads were butted instead of overlapped, I don't think I would have run into this problem. Would butting the corner beads cause cracking at their joint? What are some other factors that I haven't thought of?
Answer: I've always butted them together, and I've never had any problems with doing it that way.
Not sure what your builder was thinking by overlapping them.
Comment: OK, that sounds right to me. I just wanted to make sure I wasn't going to run into problems on down the road.
Answer: Typically, when butting corner-bead you should, first, cut about a 2" to 3" piece of bead and place it under the butt joint. That way your two pieces will butt together neatly and will be smooth when you mud over them. If your run is longer than 10', you'll need to do this (most bead is 8', but 10' is also available).


How to check if script done running

Question: I'm injecting programmatically some text-code into script, and I need to run some code only after the script is done running.
My code:
const InjectScript = (scriptContent) => {
  const script = document.createElement("script");
  script.type = "text/javascript";
  script.text = scriptContent;
  document.head.appendChild(script);

 //run some code after script executed
   someCode()
};

How can I check if the script is done running?
Comment: By the time `someCode()` runs your dynamically inserted javascript will already have executed (except any async code in it).
Comment: Use promises in JavaScript it is what you are looking for see [MDN guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
Comment: @Sanmeet Nothing async in the question, so no use for promises.
Comment: @connexo I think the OP is looking for something async as it the above code doesn't needs anything more !
Comment: Why do you even add a script tag with custom content instead of just running the code directly? (or is this a content script in a browser extension?)
Comment: Fire an event from the dynamic script that `someCode` listens for.
Comment: Set a global variable that `someCode`  checks for.
Comment: Please add information if the inserted script runs async code that you need to wait for.
Comment: Attach to `window.someCode` then pass the name of the function to your dynamic script with `data-` attributes.
Comment: Use `MutationObserver` and have `someCode` `observe` a node the dynamic script modifies.
Comment: Try this https://stackoverflow.com/a/14644704/258174
Answer: I think as like this
  var IsRunning = false;
  function myFunction() {
   if (!IsRunning) {
    IsRunning = true;
    }
    }

Comment: This is either not needed (if the inserted JS is not async), or useless (if it is). Aside from  the fact that it is making use of global variables (which is generally frowned upon).
Answer: async await seems like the best choice if your runtime is okay with ECMAScript 2017 syntax, like so:
const InjectScript = async (scriptContent) => {
  const script = await document.createElement("script");
  script.type = await "text/javascript";
  script.text = await scriptContent;
  await document.head.appendChild(script);

  //run some code after script executed
  await someCode()
};

Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Comment: `appendChild` is not async so cannot be awaited, probably neither is `someCode` and it would not make a difference to await it anyway.
Comment: await is to ensure it runs in sequence, nothing to do with promises being compulsory. thanks for the feedback anyway
Comment: This does not prevent someCode from executing before the dynamic script finishes.

How to check if script done running


Supremum for pair of elements in Hasse diagram

Question:
I know infimum is greatest lower bound, and supremum is least upper bound.
I hope did this correctly.
\begin{align*}
\sup(\{3,4\})&=7\\
\sup(\{4,5\})&=6\\
\sup(\{3,1\})&=3\\
\inf(\{5,1\})&=1\\
\inf(\{8,7\})&=6\\
\end{align*}
But what is $\inf(\{1,2\})$ and $\sup(\{8,7\})$?
I mean two elements which aren't comparable.
Answer: The supremum or infimum of a subset of a poset does not necessarily exist: there might not be a least upper bound, or a greatest lower bound.  For instance, the set $\{1,2\}$ has no lower bounds at all, so it can't have a greatest lower bound, so the infimum does not exist.  Similarly, $\sup(\{8,7\})$ does not exist.
For a somewhat more interesting example, $\sup(\{1,2\})$ also does not exist.  There are upper bounds of $\{1,2\}$ (namely $3,5,6,7,$ and $8$), but there is no least upper bound, since there is no single upper bound that is less than or equal to every upper bound.  For instance, there is no upper bound that is both $\leq 3$ and $\leq 5$.
(In fact, two of your answers are incorrect, because you have given an upper or lower bound that is not the least upper bound or greatest lower bound.  See if you can find which ones.)
Answer: The upper bounds of $\{3,4\}$ are $7$ and $8$, and neither of these are a least upper bound.
Likewise the, lower bounds of $\{8,7\}$ are $1,2,3,4,5,6$, and neither of those are greatest.


Installing gfortran in Cygwin

Question: I am trying to compile a modelling program in Cygwin using either a gfortran or g95 compiler. I have installed both compilers, but when I go to configure the program, it checks for the compilers and does not find then (error: Fortran compiler cannot create executables). I am new to Cygwin-- I suspect it is something with how/where I installed the compilers...Any ideas?
Thank you,
L.
Comment: Welcome to Stack Overflow. It is not clear if you have an installation problem, or it is the way you are calling the compiler. Also there might be some typo (then?them?). please check http://stackoverflow.com/help/how-to-ask
Comment: @Laura Reynolds In my experience, it generally means the compiler was not found. Does it say something like `checking whether the Fortran compiler works... no` before the error? It would be more informative if you displayed the whole config.log.
Comment: The relevant part of `config.log` is really necessary.
Comment: Is the PATH environment variable set to include the directory the Fortran compiler is located in?
Comment: did the answer below help solving your problem? If it helped, please accept it to help those who have similar problem. If it did not help, please let me know so that I can delete it to save people from wasting their time looking at it.
Answer: For me, it's more helpful to have executable code to go through the process, so I'm going to put some in. This is addressing your concern,

I suspect it is something with how/where I installed the compilers...

because the installation from apt-cyg should be helpful in letting the system know where to look for the compilers. I'm also addressing a possible linkage issue.
bballdave025@MY-MACHINE /cygdrive/c/bballdave025
$ apt-cyg install gcc-fortran libgfortran5

If you don't have apt-cyg yet, follow these instructions from another answer.
# Get to where your setup executable lives.
# This is what you used to install Cygwin the first time.
# Note that mine is for the 64-bit version, and that
# I keep mine in C:\cygwin64. Your path might be
# different. You also might need to re-download
# The setup executable from Cygwin.

$ cd /path/to/setup_install/setup_x86-64.exe -q -P wget
$ wget https://raw.githubusercontent.com/transcode-open/apt-cyg/master/apt-cyg
$ chmod +x apt-cyg
$ mv apt-cyg /usr/local/bin

The libgfortran5 (or a more recent version, if available when you search) might be necessary. Here's why I think this might be the case.
bballdave025@MY-MACHINE /cygdrive/c/bballdave025
$ man gcc | grep -A 3 "[ ]*[-]l[ ]\{0,2\}library$"
       -llibrary
       -l library
           Search the library named library when linking.  (The second
           alternative with the library as a separate argument is only for
           POSIX compliance and is not recommended.)

(Note that I haven't included some parts of the result that aren't useful and can be fixed by prefixing the command with MANWIDTH=160, cf here.)
There is a little more detail and a little different result from the answer to a question about the lib prefix on files:

You can name a library whatever you want, but if you want gcc's -l flag to find the right one, you need to name it the way that link describes. For example, gcc -o myapp myapp.c -lm, [w]ill compile myapp.c, link the resulting object with libm.a, and output an executable called myapp. These days, there might be a more complicated search path involving dynamic library names, etc., but you should get the basic idea from this example. [In addition, you can look at this section f]rom the gcc man page:

-l library ...
... surrounds library with lib and .a and searches several directories.

The basic reason for all of that info is this: it is very possible that, in order to link with the gfortran library, you need to have installed a package named something like libgfortran. I don't know for sure how this works, especially with the Cygwin man page being slightly different, but it's worth a try. The likely extra thing you would need in this case is something like
apt-cyg install libgfortran
or
apt-cyg install libgfortran5

Here's some helpful info on how I found what to install. When I had a similar problem, I went to the Cygwin package search, but I only got three entries with three versions of netcdf-fortran

(archived). I wanted gfortran, so I kept looking
I found a great gfortran answer  in this SO answer. With that answer, I went back to the Complete Cygwin Package List, armed with my trusty Ctrl + F, since I knew there were packages different from what came back from the search. The complete list had

cygwin64-gcc-fortran GCC for Cygwin 64bit toolchain (Fortran)`
gcc-fortran GNU Compiler Collection (Fortran)

and entries for libgfortran.
Hopefully some of this information will be helpful, or at least educational.
Answer: This problem is common for beginners with autotools. It can be:

missing libraries; this can be missing libraries for your project or compiler/system libraries, like libgfortran or similar for g95.
autotools can not detect your compiler;
dynamic libraries problem; runtime path to the dynamic libraries not set. See LD_LIBRARY_PATH for linux environment.
cross-compiling problem, I do not know much about cygwin but that can be an issue. I am not expert of cross-compiling either. It can also be another situation that I am not aware of.

I ran into the 1st and 3rd situations.
Approaches of solutions.

make sure you can manually compile and run a simple hello world program. Install the missing libraries if necessary. Also make sure that you can link your hello world program against the same libraries used by your modelling program, this last statement could lead you to the 3rd situation.
add the path to your compiler to the PATH variable or similar variable in cygwin. Or explicitly give the full path to your compiler to configure.
add the path to your libraries to the runtime libraries path LD_LIBRARY_PATH for linux environment or similar variable in cygwin. In one of my cases, the problem was that the test program that autotools uses to test the compiler could not run. It was successfully compiled but could not run. I installed all the libraries that my project uses in a path that was not included in library path. What happened was that the path to those libraries were set in the configure.ac or makefile.am so that the compiling was OK. But the running of the test program included in configure could not find them. This is a problem mostly for dynamically linked libraries. Adding the path to my .so to the LD_LIBRARY_PATH solved the problem.
well, I can not really help. The only solution that I can suggest is to install a linux system (dual boot or virtual machine) if you know how to do it, because I will not be there to help.

The following link can also help.

Installing gfortran in Cygwin


How to load html modules via ajax?

Question: Depending upon a path that a user enters my site through I want to load the correct module?
Is this as simple as storing the HTML in a file called some_file.htm then ajaxing that file to the client than appending it to the DOM?
I'm wondering if it is that easy or if there are some caveats I'm not aware of?
Thanks!
Comment: Yes it can be really that easy - if you use a framework (like jQuery).

However be aware of escaping and code validity!
Comment: I'm not using a framework, what do I need to escape, can I just append to the .innerHTML property of the containing div?
Comment: I'll test it and let you know.
Comment: Yes you can just append the innerHTML property - http://jsfiddle.net/f4Sp9/ shows any html string can be appended, you dont need to escape anything if some_file.html is a static file containing some html structure
Answer: Simple example:
JavaScript:

HTML:

Documentation:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
Comment: I think OP wasnt asking how to do it but whether its possible :) However nice example :)
Comment: I know it is possible and how to do it, I was asking if there are any caveats?  Particularly, the escaping.
Comment: @www.arcmarks.com if your content is static and you know what it contains then you need NO escaping - you need the pure code :)

How to load html modules via ajax?


Clojure nested maps path

Question: This is really a followup to question Update hierarchical / tree structure in Clojure
I need to be able to change an Atom containing a map with lists of submaps. I would like to use fx assoc-in to do this, but i'm not sure how best to optain the path to the element i wich to change
My data structure:
(def x (atom {:name "A"
          :id 1
          :children [{:name "B"
                      :id 2
                      :children []}
                     {:name "C"
                      :id 3
                      :children [{:name "D"
                                  :id 4
                                  :children []}]}]}))

How do i make a function to find the path go a given id, fx give me path to map which contain #(= (:id %) 3):
(find-path 3 @x) ; => [0 :children 1]

So i can do this to get a new map:
(assoc-in @x [(conj (find-path...) :name)] "Jim")

Or update the Atom like this:
(swap! x assoc-in [(conj (find-path...) :name)] "Bob")

Comment: You could use a zipper from [clojure.zip](http://clojuredocs.org/clojure_core/clojure.zip).
Comment: I thought it should be easy to make a recursive function returning the path, but i cannot get it to work.
Comment: In my opinion it's a lot easier to reason about and manipulate persistent nested structures using zippers than to try to figure out a  recursive function to handle them.
Answer: Create a zipper with zipper, then iterate through each location with next and once you find the location that holds the node with the id you are looking for, start moving up building the path along the way.
The following is a function I've used to do the last step, which is move up to the root and build the path along the way.
(defn path-from-root
  [loc]
  (loop [path []
         loc loc]
    (if-let [parent (zip/up loc)]
      (recur (into [:children (-> loc zip/lefts count)] path)
             parent)
      path)))

Answer: There's a fundamental issue here is that your update process is now a two steps process: find-path and update-in. However you are working with atoms so the path returned by find-path may be incorrect by the time update-in gets to see the value of the atom.
So you should combine them in a single fn so as to not have one deref and one swap!.
(defn update-by-id [x id f & args]
  (apply update-in x (find-path x id) f args))

Now you can use a single swap!:
(swap! x update-by-id 3 assoc :name "Bob")

However if you constantly update and access through ids you should also evaluate switching to another (flatter) representation for this piece of data.
Comment: Good point. The data will be often read and seldom updated, but both operations might be to expensive with a deep structure.

Clojure nested maps path


How do I find out whether an object's type is a subclass of IEnumerable for any value type T?

Question: I need to validate an object to see whether it is null, a value type, or IEnumerable<T> where T is a value type.  So far I have:
if ((obj == null) ||
    (obj .GetType().IsValueType))
{
    valid = true;
}
else if (obj.GetType().IsSubclassOf(typeof(IEnumerable<>)))
{
     // TODO: check whether the generic parameter is a value type.
}

So I've found that the object is null, a value type, or IEnumerable<T> for some T; how do I check whether that T is a value type?
Answer: (edit - added value type bits)
You need to check all the interfaces it implements (note it could in theory implement IEnumerable<T> for multiple T):
foreach (Type interfaceType in obj.GetType().GetInterfaces())
{
    if (interfaceType.IsGenericType
        && interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
    {
        Type itemType = interfaceType.GetGenericArguments()[0];
        if(!itemType.IsValueType) continue;
        Console.WriteLine("IEnumerable-of-" + itemType.FullName);
    }
}

Comment: Is GetInterfaces sufficiently recursive to mean you don't need to worry about going up the parent types?
Comment: You don't need no recursion. A class either implements an interface, or it doesn't. It's a flat list, regardless of how the interfaces themselves "inherit" each other.
Answer: Can you do somethin with GetGenericArguments ?
Answer: My generic contribution that checks if a given type (or its base classes) implements an interface of type T:
public static bool ImplementsInterface(this Type type, Type interfaceType)
{
    while (type != null && type != typeof(object))
    {
        if (type.GetInterfaces().Any(@interface =>
            @interface.IsGenericType
            && @interface.GetGenericTypeDefinition() == interfaceType))
        {
            return true;
        }

        type = type.BaseType;
    }

    return false;
}


Is there any bluetooth module supports both Bluetooth/BLE 5.0 and 4.x at the same time?

Question: The recent mobile phones support BLE 5 and they are backward compatible. That means they can connect to both BLE 5 and 4 devices. When I read specs, I see that BLE 5 is backward compatible as well. What about on device side? If I develop new device with any BLE 5 module, Can I connect it to using a BLE4 supported mobile phone? If not, is there any module that support dual mode? I want my device to work with old devices but I also want to benefit from the BLE5 advantages with BLE5 devices.
Answer: Bluetooth versions are fully backwards compatible for all qualified devices, so in general any new device will talk to an old device using the "old" protocols.
The Bluetooth philosophy is that a new spec version always adds features and rarely if ever removes functionality from the old spec version.
So in your example, yes the 5.0 module will retain all 4.x functionality. A 5.0 device is a 4.x device for all intents and purposes.
One obvious but rare exception arises when it comes to optional features, but that doesn't seem to be your case here. Let's assume there is a feature X that is optional both in 4.x and in 5.0. If device A is a 4.x device and implements X, and if device B is a 5.0 device but does not implement X, then obviously A and B cannot use X together.
Also note that "dual mode" means that the device implements both Classic Bluetooth and Low Energy Bluetooth, and has little to do with versions.
Comment: @H.Gultekin Yes, you can.
Comment: Thank you @BogdanAlexandru for the detailed answer. My example case was followingthis: I have BLE5 devices implements 4x extended range BLE5 features and advertise that. Can I still connect to BLE4 phone and use all features within normal range


Does deconstruction/removal regain used materials?

Question: The question might be trivial, but I found nothing in the wiki to support it.
I have a pair of water wheels constructed. I have a herbalist in a fey mood, and he requires wood and cut gems. I have embarked in a place that is now devoid of surface trees. Due to several reasons, I don't want to breach the cavern layers just yet and the nearest trade caravan is 2 seasons away.
Water wheels are made of wood, would deconstructing them give back the logs?
Answer: Yes! Deconstructing buildings gives back the raw materials used.
Source: experience playing the game. :P
Comment: Felt dwarfy recently, built and deconstructed a floor, got all materials. Also was able to test with the water wheels, confirmed. Accepting.
Comment: For FUN, you can also embark with just enough materials to get started but have to successively construct and deconstruct buildings to succeed in the beginning. Ex: http://dwarffortresswiki.org/index.php/v0.31:Sample_Starting_Builds#The_It-Do-Yourself_Steel_Option_weApon_Pair_Strategy_or_TIDYSOAPS
Comment: For FUN, I embarked on a map without any sort of weapon-grade ore and surface wood (which prevents for the time being to build up the military I need to explore the caverns). Just some [worthless yellow rocks](http://dwarffortresswiki.org/index.php/DF2012:Native_gold).
Comment: An addition to the question would be does it give back the same resource used? Does deconstruction a bridge from mudstone bricks return mudstone bricks, and does a steel forge return a steel forge? I believe the answers to all these are yes.


Android Get next batch of sms/mms

Question: I need to retrieve the next 20 messages from the db in Android. I am retrieving the first 20 messages using the following code below:
Uri provider = Uri.parse("content://mms-sms/conversations/" + threadId);
Cursor cursor = contentResolver.query(provider, new String[]{"_id", "ct_t"}, null, null,
"_id desc limit 20");
//then used the id to get the actual message

This is working fine. But I need to get the next 20 messages starting from the last thread id and below. I have tried to add the selection:
"_id < lastMessageId"

But this gives me a null cursor. Another solution that i have in mind is to use the same code above but increase the limit by 20, but that will return unnecessary rows of data. Anyone can help me with this? Thanks!
EDIT:
I found this in logs.
SQLiteException: (ambiguous column name: _id (code 1): , while compiling: SELECT _id, ct_t FROM (SELECT DISTINCT date * 1 AS normalized_date, _id, NULL AS ct_t FROM sms WHERE (_id < ? AND thread_id = 25 AND (type != 3)) UNION SELECT DISTINCT date * 1000 AS normalized_date, pdu._id, ct_t FROM pdu LEFT JOIN pending_msgs ON pdu._id = pending_msgs.msg_id WHERE (_id < ? AND thread_id = 25 AND msg_box != 3 AND (msg_box != 3 AND (m_type = 128 OR m_type = 132 OR m_type = 130))) UNION SELECT DISTINCT date * 1 AS normalized_date, _id, NULL AS ct_t FROM cellbroadcast WHERE (_id < ? AND thread_id = 25) ORDER BY _id desc limit 20) ORDER BY _id desc limit 20)

Is there any way that i can only add the where clause on sms table only?
Answer: The cursor shouldn't be null as if the query doesn't return results, its size (cursor.getCount()) would be 0.
Be sure to use the selection and selectionArgs correctly that is -
selection ==> "_id < ?" and
selectionArgs ==> String[]{lastThreadId.toString()}
provided the lastThreadId is Integer or if its an int you can use String.valueOf(lastThreadId) to wrap it into a String.
Also, you can use "_id < " + lastThreadId.toString() as your selection statement with selectionArgs null.
Comment: I already tried that but still it returns null. I'm suspecting that the "_id" is not applicable in the where clause since it was left join to other tables?

Android Get next batch of sms/mms


Adding overlay to video which fades in and out intermittently

Question: first time posting. That said I've come up against a challenge and I need some input.
I've been trying to create a command to add a "watermark" or overlay to a vide which fades in, stays on screen for a certain duration and then fades out. This type of effect is common in "screeners" where a disclaimer like "for your consideration" fades in and out periodically.
I am currently able to do this by creating a separate overlay file which is of the desired duration, with a fade in and fade out. I then loop this overlay and achieve the desired effect. However, for a couple of reasons, I'd like to be able to achieve this in a single command.
this is what I need the command to do- any input would be greatly appreciated!
the overlay must fade in and fade out, with a total duration of 30 seconds
the overlay must reappear (with fade in and fade out, as above) every 5 minutes, for the entire duration of the main clip.
the overlay may consist of the any of the following:
a .png
custom text (currently using drawtext to generate the text)
a .mov file (an overlay with an animated intro, the last frame of which is looped to give desired duration)
in the case of the animated overlay, ideally the video overlay will not fade in but will fade out, so, for each instance where the overlay appears, the .mov is playing from the beginning, looping the last frame, and fading out.
.png + custom text (both fade in and out)
.mov + custom text (custom text fades in, both fade out)
Any help would be greatly appreciated.
Answer: loop:
<code>ffmpeg -i "input 1.mp4" -loop 1 -i logo.png -filter_complex "
[1:v]
fade=t=in:st=0:d=1:alpha=1,
fade=t=out:st=29:d=1:alpha=1,
loop=loop=-1:size=7500[fg];
[0:v][fg]overlay=W/2-w/2:H/2-h/2:shortest=1
" -c:a copy output.mp4 -y
</code>
size=7500 is number of frames 25 fps * 300 sec


Deriving master equation for discrete process

Question: Consider a group of $N$ professors, $Y$ of whom are wearing white socks and $X = N − Y$ others who are wearing black socks.
On each time step, one professor is chosen at random and he has to put a new pair of socks on, irrespectively of the color of the socks he is currently wearing. The probability of the professor choosing a white pair of socks is $p$ and the probability of him choosing a black pair of socks is $1 − p$, independently of the pair of socks he was previously wearing.
a) How can I derive a master equation for the model of how the probability $\pi(i,t)$ that $i$ professors are wearing white socks at time $t$ changes throught time, that is, how $\pi(i,t+1)$ varies with $\pi(i,t)$, $\pi(i-1,t)$ and $\pi(i+1,t)$?
b) How can I solve the master equation to show that, for $t \rightarrow \infty$,
$$ \pi(i) = \left( \begin{array}{c}
N\\
i\end{array} \right) p^i (1-p)^{N-i} \;?$$
MY ATTEMPT
a)
$$\begin{align}
\pi(i,t+1) = & \pi(i-1,t) P(X\rightarrow Y) + \pi(i+1,t) P(Y\rightarrow X) + \\ & \pi(i,t) P(Y\rightarrow Y) + \pi(i,t) P(X\rightarrow X)\\
= & \pi(i-1,t) p \frac{N-(i-1)}{N} + \pi(i+1,t) (1-p) \frac{i+1}{N} + \\
& \pi(i,t) p \frac{i}{N} + \pi(i,t) (1-p) \frac{N-i}{N}
\end{align}$$
Do you think this is correct?
b)
I've tried to assume $\pi(i)$ is as told, and then substitute it on the RHS of the master equation I derived, but I cannot reach an equality.
Thanks in advance for all the help you can provide.
Answer: This seems to be a variant of the 'Ehrenfest urn model'.
The equation you have derived provides the $(N+1) \times (N+1)$ transition matrix $P$ of a Markov Chain.
Your binomial distribution is the proposed steady-state distribution $(N+1)$-vector $\sigma$ of the chain.
If $\sigma P = \sigma$, then $\sigma$ is indeed the steady-state (stationary) distribution of the chain.
I believe this is what you must mean by 'master equation'.
Comment: Your eqn seems OK. I didn't check it step by step. Have a lecture in a few minutes. The validation would be whether it yields the desired binomial distribution. There may be ways of looking at this other than as the steady state of a MC, but I believe that is the standard way to handle this problem, and probably the most direct.
Comment: i) so the only way to arrive at the binomial distribution is by finding treating the problem as a Markov Chain and find the steady state?
ii) the equation I derived is correct, right?
thanks for your time.