Identifying a conditional posterior for $\mu$ and $\sigma^2$

Question: My Question
Consider the model $X_1, \dots, X_n \overset{\mathrm{iid}}{\sim} \cal N(\mu, \sigma^2), (\mu, \sigma^2) \in (-\infty, \infty) \times (0, \infty)$ with a product prior pdf $\xi(\mu, \sigma^2) = \xi_1(\mu)\xi_2(\sigma^2)$ where $\xi_1(\mu) = \cal N(a, b^2)$ and $\xi_2(\sigma^2) = \chi^{-2}(r,s)$ for some constants $a \in , b > 0, r > 0$ and $s > 0$. Let $\xi(\mu, \sigma^2| x)$ denote the posterior pdf given observations $x = (x_1, \dots, x_n)$.

Identify the conditional posterior pdf $\xi_1(\mu, | x, \sigma^2)$ of $\mu$ for a given $\sigma^2$.
Identify the conditional posterior pdf $\xi_2(\sigma^2 | x, \mu)$ of $\sigma^2$ for a given $\mu$.

My Thoughts
First, a helpful fact from my previous searching: $$\xi_1(\mu | x, \sigma^2) \propto \xi(\mu, \sigma^2 | x)$$ Given this, I fixed $\mu, \sigma^2$ in turn and saw what kind of pdf I got. For $\mu$, fixing $\sigma^2$, I got another Normal pdf, so my belief is that $\xi_1(\mu, | x, \sigma^2)$ should take the form of a Normal pdf.
Fixing $\mu$, I saw that $\sigma^2$ was in the denominator of the exponential term and in the denominator of the ${1\over \sigma \sqrt{2\pi}}$ term outside of the exponential term, and so I thought of the inverse-chi-square family or the inverse gamma family.
My Question
Given that I have reasonable beliefs about what form my answers should take, how would I go about finding explicit formulae for the updated parameters? I want to be able to explicitly write down a formula for $\xi_1(\mu, | x, \sigma^2)$ and right now, given that I identified the form they should take through (liberal) use of "$\propto$", I'm not sure what to do.
Comment: The inverse-chi-squared distribution has just one parameter $\nu$. Can you clarify the meaning of $r$ and $s$?
Answer: You have random variables $X_1,\dots,X_n$ that are, given that $M=\mu$ and $\Sigma^2=\sigma^2$, conditionally independent and identically distributed as $\mathrm{N}(\mu,\sigma^2)$.
You believe that a priori $M$ and $\Sigma^2$ are independent with $M\sim\mathrm{N}(a,b^2)$ and $\Sigma\sim\mathrm{IG}(r,t)$.
(please, check the definition of the Inverse-Gamma distribution).
Define $X=(X_1,\dots,X_n)$ and $x=(x_1,\dots,x_n)$. Also, define $\bar{x}=\sum_{i=1}^n x_i/n$ and $s^2=\sum_{i=1}^n (x_i-\bar{x})^2/n$.
The likelihood is
$$
  f_{X\mid M,\Sigma^2}(x\mid\mu,\sigma^2) = \prod_{i=1}^n f_{X_i\mid M,\Sigma^2}(x_i\mid\mu,\sigma^2)
$$
$$
  = (2\pi)^{-n/2} \sigma^{-n} \exp\left(-\frac{1}{2\sigma^2}\sum_{i=1}^n (x_i-\mu)^2\right) \, .
$$
But
$$
  \sum_{i=1}^n (x_i-\mu)^2 = \sum_{i=1}^n (x_i-\bar{x}+\bar{x}-\mu)^2
$$
$$
  = \sum_{i=1}^n (x_i-\bar{x})^2 +2 (\bar{x}-\mu)\sum_{i=1}^n (x_i-\bar{x}) + \sum_{i=1}^n (\bar{x}-\mu)^2 \, . \quad (*)
$$
The middle term in $(*)$ is zero (check it out), giving us the useful decomposition
$$
  \sum_{i=1}^n (x_i-\mu)^2 = n(\mu-\bar{x})^2 + ns^2 \, ,
$$
which allows us to rewrite the likelihood in terms of the sufficient statistics $\bar{x}$ and $s^2$ as
$$
  f_{X\mid M,\Sigma^2}(x\mid\mu,\sigma^2) = (2\pi)^{-n/2} \sigma^{-n} \exp\left(-\frac{n}{2\sigma^2}\left((\mu-\bar{x})^2 + s^2\right)\right) \, .
$$
Hence, using the most beautiful theorem ever, the posterior density is
$$
  f_{M,\Sigma^2\mid X}(\mu,\sigma^2\mid x) \propto f_{X\mid M,\Sigma^2}(x\mid\mu,\sigma^2) f_M(\mu) f_{\Sigma^2}(\sigma^2)
$$
$$
  \propto \sigma^{-n} \exp\left(-\frac{n}{2\sigma^2}\left((\mu-\bar{x})^2 + s^2\right)\right)
$$
$$
  \times \exp\left(-\frac{1}{2b^2}(\mu-a)^2\right) (\sigma^2)^{-r-1} \exp\left(-\frac{t}{\sigma^2}\right) \, ,
$$
in which the $\propto$ symbol means proportionality up to factors that do not depend on $\mu$ and $\sigma^2$.
To compute the full conditionals, note that, by the product rule for densities, we have
$$
  f_{M, \Sigma^2\mid X}(\mu,\sigma^2\mid x) = f_{M\mid\Sigma^2,X}(\mu\mid\sigma^2,x) f_{\Sigma^2\mid X}(\sigma^2\mid x) \, ,
$$
and hence
$$
  f_{M\mid\Sigma^2,X}(\mu\mid\sigma^2,x) \propto f_{M,\Sigma^2\mid X}(\mu,\sigma^2\mid x) \, ,
$$
in which the $\propto$ symbol means proportionality up to factors that do not depend on $\mu$.
Therefore,
$$
  f_{M\mid\Sigma^2,X}(\mu\mid\sigma^2,x) \propto \exp\left(-\frac{1}{2}\left(\frac{n}{\sigma^2}(\mu-\bar{x})^2 +\frac{1}{b^2}(\mu-a)^2\right)\right) \, .
$$
Completing the square, we have
$$
  \frac{n}{\sigma^2}(\mu-\bar{x})^2 +\frac{1}{b^2}(\mu-a)^2 \propto \left(\frac{nb^2+\sigma^2}{\sigma^2 b^2}\;\;\right) \mu^2 - 2\mu\left(\frac{nb^2\bar{x}+\sigma^2a}{\sigma^2b^2}\;\;\right)
$$
$$
  \propto \left(\frac{nb^2+\sigma^2}{\sigma^2 b^2}\;\;\right)\left(\mu - \frac{nb^2\bar{x}+\sigma^2a}{nb^2+\sigma^2}\;\;\right)^2 \, ,
$$
which gives you, by inspection, that
$$
  M\mid\Sigma^2=\sigma^2,X=x \sim \mathrm{N}\left(\frac{nb^2\bar{x}+\sigma^2a}{nb^2+\sigma^2}\quad, \frac{\sigma^2 b^2}{nb^2+\sigma^2}\;\;\right) \, .
$$
Now we take a deep breath and do it mutatis mutandis for the other conditional.
$$
  f_{\Sigma^2\mid M,X}(\sigma^2\mid \mu,x) \propto (\sigma^2)^{-n/2-r-1} \exp\left( -\frac{1}{\sigma^2}\left(\frac{n}{2}\left((\mu-\bar{x})^2 + s^2\right) + t \right)\right) \, ,
$$
which says that
$$
  \Sigma^2\mid M=\mu,X=x \sim \mathrm{IG}\left( \frac{n}{2}+r, \frac{n}{2}\left((\mu-\bar{x})^2 + s^2\right) + t\right) \, .
$$
Comment: No, I won't be implementing a Gibbs sampler with this particular conditional posterior, but I was asked about it, and wanted to see what it would come out to be. I'm not turning in this work, I just wanted to see what the steps would be to get this posterior in $\mu, \sigma^2$ repectively.
Answer: If your hyper parameters are fixed (without any random distribution), you can use the MCMC method to simulate and update your parameters. MCMC does not need exact distribution function of the posteriors (with normalization constant). It only needs some candidate distributions for your parameters that you can define based on your opinion about each posteriors.


Java application randomly errors with: java.util.ConcurrentModificationException

Question: So i'm trying to create simple gravity using LWJGL, but the application randomly crashes with the java.util.ConcurrentModificationExceptionexception. The strange thing is that is does not always happen at the same time. Sometimes it crashes instantly but other times it runs fine for 10 minutes before crashing.
Main game class:
public static ArrayList<Block> blocks;

public Game() {
    blocks = new ArrayList<Block>();

    for(int i = 0; i < 40; i++)
        blocks.add(new BlockTest(i, 21, new float[] {0.4f, 0.6f, 0.7f}, false, 0));

    spawnTimer.scheduleAtFixedRate(new TimerTask() {
          public void run() {
              spawnBlock();
          }
    }, 1000, 1000);
}
public void update() {
    for(Block b : blocks)
        b.update();
}

Block class:
/** Update block */
public void update() {
    if(hasGravity) {
        boolean colliding = false;

        for(Block b : Game.blocks)
            if(b.getBlockID() == 0) {
                if(Util.checkBlockCollision(this, b)) {
                    colliding = true;
                    setBlockID(0);
                }
            }

        if(fallDelay.over() && !colliding) {
            setBlockYPosWithoutBlockSize(y += 2);
            fallDelay.start();
        }
    }
}

The stack trace is the following:
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)
    at snakybo.gravitytest.block.Block.update(Block.java:26)
    at snakybo.gravitytest.Game.update(Game.java:34)
    at Main.gameLoop(Main.java:52)
    at Main.main(Main.java:21)

With (Game.java:34) being this line:
b.update();

And (Block.java:26) being:
for(Block b : Game.blocks)

If you need the full code, it's available on Github
Comment: Also, according to the Oracle Docs it mostly happens when using multithreading but i'm not multithreading here.
Answer: You are multithreading. The TimerTask runs on a separate thread.
What happens is this: the spawnBlock method that is being called on the timer task thread modifies the blocks list(adds one to the list).
On the main thread, the update method is called, in which the code iterates over the blocks list.
Because a block is added to the blocks list during that iteration(during the spawnblock method execution on the other thread), you get the concurrentModificationException.
Replacing "for(Block b : blocks)" by "for(Block b : new ArrayList(blocks))" is a very simple but not so performant solution: since you always iterate over a new copy, you can modify the original list as much as you want.
A better solution is probably to start making your methods synchronized or rethink your design, like wrapping the blocks list in a synchronized wrapper.
Comment: Okay, didn't know the TimerTask runs on a seperate thread, thanks for the info i'll have to look into that synchronized wrapper, but for now `for(Block b : new ArrayList(blocks))` seems to have fixed it. Thanks


$h(x) = \sum_{n=0}^\infty c_n x^n$ show h(x)=f(x)g(x)

Question: Given $f(x)= \sum_{j=0}^\infty a_j x^j$ and $g(x)= \sum_{k=0}^\infty b_k x^k$.
$f(x)$ has radius of convergence $R_1 > 0$ and $g(x)$ has radius of convergence $R_2 > 0$
Let $c_n= \sum_{j=0}^n a_j b_{n-j}$ and $R = min(R_1, R_2)$
If $h(x) = \sum_{n=0}^\infty c_n x^n$, show $h(x) = f(x)g(x)$ on $(-R, R)$
So what I got up to was:
$h(x) = \sum_{n=0}^\infty (\sum_{j=0}^n a_j b_{n-j}) x^n$
$h(x) = \sum_{n=0}^\infty (\sum_{j=0}^n a_j x^j b_{n-j} x^{n-j})$
from the previous step, is

$h(x) = \sum_{n=0}^\infty (\sum_{j=0}^n a_j x^j) (\sum_{j=0}^n b_{n-j} x^{n-j})$
$h(x) = (\sum_{j=0}^\infty a_j x^j) (\sum_{j=0}^\infty b_{n-j} x^{n-j})$
$h(x) = f(x)g(x)$

I am unsure whether step 2 is valid. Also, is there an example where h has radius
of convergence strictly greater than $R$
Answer: Formulas (1.) and (2.) are both wrong.
For the last question, consider $f(x) = 1/(1-x)$, $g(x) = 1 - x$.


How do I Group Repeatable Fields Programatically?

Question: I'm in the middle of coding a custom entity in Drupal 8. Currently, I'm defining fields using the baseFieldDefinitions method. I've run into a small problem now where I have a subset of fields that need to be grouped together and repeatable. For example, I have a checkbox, a text box, and a select box that all need to be associated while allowing someone to click an "Add" button to produce another set of those three fields.
It seems that if I was using the UI to create a custom content type, then I could use Paragraphs to handle this, but I wasn't able to figure out how to do that in code, and all the modules that are used in Drupal 7 as example of how to do this either don't exist in D8, or point to using Paragraphs instead.
Some ideas that I had:

Create all three as repeatable fields in baseFieldDefinitions and override the form to present them as a unit and write some ajax to make it work the way I want. I don't think this is ideal because it seems like I'm fighting the framework.
Make this group of fields into their own entity and try to figure out how to add an entity creation form inside my parent entity creation form. I'm not sure if this is possible, but it seems like it should be.
Use hook_schema to create a database table with the three fields that I need and an additional column to tie that record to my custom entity. This is the way I would have done it in Drupal 7, but I'm worried about the long term of running reports in Views using the data that isn't in the Entity itself. This seems like the quick and dirty way to do it but I don't want a Views headache later.
Figure out how to do this in Paragraphs.

Hopefully, someone with a little more experience than I have in D8 can point me to the most preferable way to handle this. Any help would be greatly appreciated.
Answer: I would pick option 3: Create a custom field type that holds all 3 values in one table. This works fine with views. This can be done with Drupal console to simplify the process, see generate:plugin:field. I would also create a separate module for the the plugin with the custom field type so you can test enabling and disabling you main module without running into dependency issues. The advantage of this method over all others is all the data is held in one DB table which keeps things simple and is more efficient.
To briefly touch on your other options, 1 seems dirty and prone to problems. 2 is not bad and does give you more flexibility but means more code and more database tables. If you don't need the added flexibility then there is no need. Paragraphs, Option 4 will create as many DB tables as a custom entity but with less flexibility (you can't add methods to the ContentEntityBase) and more reliance on contrib modules. This is only a good option if your a site builder and don't want to worry about coding.


The double partial derivative

Question: I have a differential of a function, $df(x,y)=y\sin(xy)\mathrm{dx}+x\sin(xy)\mathrm{dy}$.
How do I determine the double partial derivatives $f_{xy}, f_{xx}$ and $f_{yy}$?
I am fairly certain I have to use the chain rule, but I can't see how to apply because of the $y$ and $x$ in the front.
If it's true that I should use the chain rule, could you give me a hint?
Answer: Given
$df(x,y)=y\sin(xy)\mathrm{dx}+x\sin(xy)\mathrm{dy}$
By Using
$df(x,y)=f_{x}\mathrm{dx}+f_{y}\mathrm{dy}$
We can get that
$f_{x}=y\sin(xy)$
$f_{y}=x\sin(xy)$
From there:
$f_{xx}=y^{2}\cos(xy)$,
$f_{yy}=x^{2}\cos(xy)$
$f_{xy}=\sin(xy)+xy\cos(xy)$.
Comment: Thank you, I understand how you get $f_{xx}$ and $f_{yy}$, but why don't you get $f_{xy}=xy\cos(xy)$?
Comment: @dexterity: Because $f_{xy}=(f_{x})_{y}$, it should derivate about $y$ to $y\sin(xy)$, note that $y\sin(xy)$ is a product of two functions of $y$, then you should use Lebniz rule.
Comment: This answer seems to me to be "too much of an answer" for a homework question.  I thought we were only supposed to give hints?

The double partial derivative


E measurable then there is $F=\bigcup_{i=1}^NQ_i$ such that $m^*(E\Delta F)<\varepsilon$.

Question: Suppose $E$ measurable and let $\varepsilon>0$. Then, there is closed cube $\{Q_j\}_{j=1}^N$ such that $$m^*(E\Delta F)\leq \varepsilon$$
where
$$F=\bigcup_{j=1}^NQ_j.$$
I denote $A\Delta B:= (A\setminus B)\cup (B\setminus A)$.
I tried to make a draw, but I don't see what it mean concretely. Could someone show me on a draw ? Thank you very much.
Answer: Think of inscribing a square S in a circle C. now make the square a tiny bit bigger so it is now S'. now the square will not cover the whole circle, there will be a piece p1 left over. also the circle will not cover the whole square, there will be a piece p2 left over. $S' \Delta C = p1 \cup p2$
Answer: I tried to do my best to make the draw on the computer, but it's not that easy. Your formula says that if $E$ is measurable (and of finite measure), $E$ differ by a finite union of cube by a set of measure $\varepsilon$ (in the draw, the difference between $E$ and $F$ is the set in red and the measure of this set is $\varepsilon$.)
I don't know if you can imagine how strong (and important) is this result, but to vulgarize it, it mean that $E$ is a very nice set with a margin of $\varepsilon$.
In fact, $$E\subset E\Delta F\cup F\implies m(E)\leq m(F)+m(E\Delta F)$$
and $$F\subset E\Delta F\cup E\implies m(F)\leq m(E)+m(E\Delta F),$$
therefore, if $m(E\Delta F)<\varepsilon$,
$$m(E)<m(F)<m(E)+2\varepsilon$$
and thus, you can approximate every measurable set by a finite union of cube.


Decoding a list in python

Question: I have a list in python
['Deals', "\\\\xe2\\\\x98\\\\x85What\\\\\\'s New\\\\xe2\\\\x98\\\\x85", '\\\\xc3\\\\x80la carte & Value Meals', 'Crispy Chicken', 'Share Box', 'Happy Meals', 'Desserts', 'McCafe\\\\xc3\\\\xa9', 'Beverages', 'Side Lines', 'Snack Time']

I want to decode it like "\\\\xe2\\\\x98\\\\x85What\\\\\\'s New\\\\xe2\\\\x98\\\\x85", '\\\\xc3\\\\x80la carte & Value Meals','McCafe\\\\xc3\\\\xa9' to 'What's New, la carte & Value Meals,McCafe'
The desired output would be without any endcoding (\\x98)
Desired output:
['Deals', "What's New", 'la carte & Value Meals', 'Crispy Chicken', 'Share Box', 'Happy Meals', 'Desserts', 'McCafe', 'Beverages', 'Side Lines', 'Snack Time']

Comment: Possible duplicate of [Regular expression that finds and replaces non-ascii characters with Python](https://stackoverflow.com/questions/2758921/regular-expression-that-finds-and-replaces-non-ascii-characters-with-python) (per "please see this answer" link in second answer)
Comment: Really, your list is a bit garbled UTF-8 with result of `★What's New★`, `Àla carte` and `McCafeé`. Accented letters are letters, and _Black Star_ could matter as well…
Comment: Could you please be more specific? You can take your list and replace string.replace('\\x98','') This will replace '\\x98' with ''. It will effectively delete it.
Comment: It seems like what you're asking for is to replace / delete non-ASCII literals (e.g., `\xe2`) but keep any other spaces letters/spaces. [This answer](https://stackoverflow.com/questions/2758921/regular-expression-that-finds-and-replaces-non-ascii-characters-with-python) seems to be the general-purpose solution for finding/replacing non-ASCII characters in a string.
Answer: You can use the built in module, re:
import re
l = ['Deals', "\\\\xe2\\\\x98\\\\x85What\\\\\\'s New\\\\xe2\\\\x98\\\\x85", '\\\\xc3\\\\x80la carte & Value Meals', 'Crispy Chicken', 'Share Box', 'Happy Meals', 'Desserts', 'McCafe\\\\xc3\\\\xa9', 'Beverages', 'Side Lines', 'Snack Time']
l = [re.sub(r'x\S\d',' ',s).replace('\\','').strip() for s in l]
print(l)

Output:
['Deals', "What's New", 'la carte & Value Meals', 'Crispy Chicken', 'Share Box', 'Happy Meals', 'Desserts', 'McCafe', 'Beverages', 'Side Lines', 'Snack Time']

re.sub(r'x\S\d',' ',s) will return the string s with every 3 neighboring characters that are in this pattern:
x, any character that's not a space, number
replaced with a space.
Comment: I'm downvoting because it's not universal solution. For instance, _Latin Small Letter E With Diaeresis_ with UTF-8 byte sequence `0xC3`, `0xAB` does not match your pattern, see also [this comment](https://stackoverflow.com/questions/62352305/decoding-a-list-in-python#comment110277581_62352305).

Decoding a list in python


Looping through rows and columns in R does not work

Question: I am just trying to fill gaps but in a loop. It is a monthly data, and fill_gaps produces NAs for every day. I am not sure why.
for (x in 2:length(differencing)){
  for(micky in 1:length(differencing$`d_ BA`)){
    if(is.na(differencing[micky,x])== T){
      differencing[micky,x] = differencing[micky-1,x]
    }
  }
}

here is the error that I am getting:
Error: Assigned data `differencing[(micky - 1), x]` must be compatible with row subscript `micky`.
x 1 row must be assigned.
x Assigned data has 0 rows.
i Row updates require a list value. Do you need `list()` or `as.list()`?
Run `rlang::last_error()` to see where the error occurred.

Comment: `length` gives the number of columns for a dataframe. Try `nrow`
Comment: Instead of `is.na(differencing[micky,x])== T`, use `is.na(differencing[micky,x])`
Comment: length(df$column) gives you a value equal to nrow.
Answer: This can be easily done using fill
library(tidyr)
library(dplyr)
differencing %>%
    fill(everything())

Or we can use na.locf from zoo
library(zoo)
na.locf(differencing)

In the OP's loop, in the first line, it would be
for (x in  2:length(differencing$`d_ BA`)
   ...

as length of a data.frame will be the number of columns (as mentioned in the comments) and is different from length of a column i.e. vector

As the OP mentioned none of them works (OP didn't provide any example), using a small reproducible example ('tmp')
tmp %>%
   fill(everything())
#                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
#Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#Hornet Sportabout 18.7   6  258 110 3.15 3.440 17.02  0  0    3    2
#Valiant           18.1   6  258 110 2.76 3.460 20.22  1  0    3    1

or using na.locf
na.locf(tmp)
#                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
#Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#Hornet Sportabout 18.7   6  258 110 3.15 3.440 17.02  0  0    3    2
#Valiant           18.1   6  258 110 2.76 3.460 20.22  1  0    3    1

data
tmp <- head(mtcars)
tmp[c(2, 5, 6), c(3, 4, 2)] <- NA

Comment: None of these work for me. The first does not work at all. And the second solution fills the NaNs with -Inf values. It is a stock data, I want to fill it up with a previous known value.
Comment: @TommyTomsia I showed a reproducible example and it is working fine for me.
Comment: Got the data from quantmod and turned it into a tsibble. Something is just messed up with R. This loop would work perfectly fine in Python. Something is wrong with assign the values in a loop...
Comment: @TommyTomsia Ok, so the relevant info was missing in your post.  Can you please update your post with a small reproducible example
Comment: @TommyTomsia, mind that 999 times out of 1000, there is no real bug or 'something wrong with R', but rather a misunderstanding from the OP.


Why it shows error: expected expression before 'return'?

Question: #include<stdio.h>
int main(void)
{
int x=1,y=0;
x>y?printf("Hello World"):return x;
}

Why it shows error: expected expression before 'return'?
What is the thing need to be changed here?
Comment: May I ask what is the purpose of writing this, instead of an `if`?
Comment: This is improper use of a ternary (`? :`). Ternaries expect expressions: things that themselves evaluate to a value. `return` doesn't evaluate to anything though; it's a control statement. If you want to conditionally **do** something (instead of conditionally picking a value), use a full `if`. Even if what you're trying to do worked, it would be poor form.
Comment: Do yourself a favor and avoid ternary operators.  Modern compilers are good at optimizing `if-else` statements, so there is little use for the ternary operators.  In modern embedded systems, focus on readability and quality and less on efficiency and space concerns.  If your program doesn't fit, then optimize for space (with the compiler's help).  If your program is running too slow or missing timing opportunities, then optimize for speed, again, with the compiler's help.
Comment: I'm pretty sure this is ill formed, im not seeing anything [here](https://en.cppreference.com/w/cpp/language/operator_other) that says you can return from one of the branches of the ternary.
Answer:
Why it shows error: expected expression before 'return'?

The ternary operator is an operator, requiring three operands.  The first operand must be an expression of integer type.  The latter two operands must be expressions of type compatible with each other.
A return statement specifies a return value for the function in which it appears, and causes that function to terminate.  It is not an expression, and does not evaluate to a value, neither the specified return value or any other.  As such, it cannot be an operand of the ternary operator.
The error message is, therefore, expressing that the third operand of the ternary operator is missing, which it is, since the return statement cannot be considered an operand.  If it were present, that operand would appear before the return.

What is the thing need to be changed here?

To obtain the logic you appear to want, the thing to change is the ternary operator.  Use an if / else statement instead:
if (x > y) {
    printf("Hello World");
} else {
    return x;
}

Generally speaking, the ternary operator should be avoided.  It usually makes code harder to read and understand, with little or no offsetting benefit.  You may someday discover a programming context where a ternary is the cleanest, clearest way to go, but anywhere else, use if.
Answer: The main theme of the ternary operator is
condition ? value_if_true : value_if_false
The statement evaluates to value_if_true if the condition is met, and value_if_false otherwise.
Read more about 'ternary operator' [https://www.freecodecamp.org/news/c-ternary-operator/]
Try to avoid a ternary operator if your concept is not clear. Try to use if-else.

Why it shows error: expected expression before ‘return’?


Flex4. Get the second item from DropDownList

Question: Does any one know how it's possible to get in Flex 4 a value of the second item from Drop Down list, assuming I have 3 items listed there?
E.g.

5
4
9

I need 4
MyLable.text=myDDList.dataProvider.getItemAt(1).toString();

this one doesn't work
Answer: Without knowing your dataProvider structure; it is impossible to give you a definite answer.  This code will give you the object being displayed in the second item of the DropDownList:
var tempObject : Object = myDDList.dataProvider.getItemAt(1);

Using the default labelField, that object should have a field named label on it which will return your suggested value:
MyLable.text = tempObject['label'];

You can even make this slightly more flexible:
MyLable.text = tempObject[myDDList.labelField];

If you are using a labelFunction; you'll have to run your object through the labelFunction procedure.
If you're using custom objects in your dataProvider, you can use the approach in your own answer if you implement a toString() method in that object which returns the '4' string.
Comment: Found a workaround that fits me the best:

Included a identification into a data source of label.

    protected function richText_creationCompleteHandler(event:FlexEvent):void
       {
        getRecordCountResult3.token = Myservice.getRecordCount();

       }

Cheers


Drupal unable to login and logout several accounts in a single functional test

Question: I am trying to run some functional tests in DDEV that check functions of protected routes. I can log in the first couple of users fine, but after that drupaLogin() fails to generate a logged in session.
Example:
$this->drupalGet(Url::fromRoute('mymodule.secondary_login'));
$this->submitForm([
  'name' => 'firstname.lastname@example.com',
  'pass' => 'test',
], 'Log in');

// Try to go to /user.
$this->drupalGet('/user');
$this->assertSession()->addressEquals('member');

// More navigation and assertion checks here

// Make the cookie stale and test the redirect.
$this->getSession()->setCookie('session', NULL);
$this->drupalGet('/');
$this->assertSession()->addressEquals('member/login');
$this->drupalGet(Url::fromRoute('mymodule.secondary_logout'));
$this->assertFalse($this->loggedInUser);

// User is anon and session should be clear at this point, but drupalLogin fails
$authenticated_user = $this->drupalCreateUser([], 'Authenticated User', FALSE);
$this->drupalLogin($authenticated_user);
$this->drupalGet('/member');
$this->drupalGet(Url::fromRoute('mos_ticketure.logout'));
$this->assertSession()->statusCodeEquals(403);

Url::fromRoute('mymodule.secondary_login') is a login form that handles setting a cookie and registering a new user with ExternalAuth. secondary_logout handles destroying the user session (copied from Drupal core logout()) as well as cleaning up custom cookies.
By the time it gets down to log in the Authenticated User, drupalLogin fails an assert check with:
User Authenticated User successfully logged in.
Failed asserting that false is true.

If I move it to a brand new test method, this simple test works fine:
$this->drupalGet(Url::fromRoute('mymodule.login'));
$this->submitForm([
  'name' => 'email@example.com',
  'pass' => 'test',
], 'Log in');
$this->drupalGet(Url::fromRoute('mymodule.logout'));

$authenticated_user = $this->drupalCreateUser([], 'Authenticated User', FALSE);
$this->drupalLogin($authenticated_user);
$this->drupalGet('/member');
$this->drupalGet(Url::fromRoute('mymodule.logout'));
$this->assertSession()->statusCodeEquals(403);

If I click through these scenarios manually, the custom functionality does indeed appear to do what it should. Is this some sort of weird behavior with PHPUnit Functional tests with Mink unable to properly track cookies and session data in larger tests?
Answer: I was able to narrow it down to this block of code in an EventSubscriber:
if ($this->currentUser->isAnonymous() && $this->requestStack->getCurrentRequest()->cookies->has('session')) {
  $options = $this->sessionConfiguration->getOptions($event->getRequest());
  $cookie_domain = $options['cookie_domain'];

  $response = new RedirectResponse('/member/login', 302);
  $response->headers->clearCookie('session', '/', $cookie_domain);
  $response->headers->clearCookie('session_expires', '/', $cookie_domain);
  $event->setResponse($response);
}

Under test, Mink does not seem to be entirely eradicating cookies even though I have a logout hook and request event that sets them (and does erase them) in that certain condition. However, for anonymous users without that cookie this keeps being triggered, so I think functional tests may have some issue with custom cookies or clearing them properly in this regard with the Mink driver. Even calling ->drupalLogout() had no further effect.
I wound up having to do $this->getSession()->reset(); then I could do this in tests that do various types of user logins (custom or core):
$this->getSession()->reset();
    $authenticated_user = $this->drupalCreateUser([], 'Authenticated User', FALSE);
    $this->drupalLogin($authenticated_user);

It does seem to be an issue with Mink, based on some findings:
https://github.com/ariya/phantomjs/issues/11768
there are similar reported issues in various libraries... the tests will only work in this regard with a reset. Unsure of where the deeper issue lies, actual usage works (real person, real browser).
Added it here for tracking: https://www.drupal.org/project/drupal/issues/3398145
Comment: I have a similar problem trying to fix a unit test on a contrib module, but adding $this->getSession()->reset(); did not work. Do you add it right after drupalLogout() ?
Comment: Yes, I did. The session data is not fully clearing otherwise.


Expressão Regular R

Question: Tenho uma variável que indica o ano do Ensino Fundamental que um aluno está cursando, mas essa variável não foi preenchida de forma única.
Por exemplo  o 1º Ano do Ensino Fundamental por estar indicado como 1º ano, 1º Ano, 1º ANO, 1 º ano. Alguém sabe indicar como posso incluir todas as possíveis formas dentro de um grep por exemplo. Eu sei que posso fazer alguns grep, só que pra isso eu precisaria saber ao certo cada forma que foi preenchido e seria mais útil algo automático.
Segue um dput de parte das informações.
c("1º ano", "1º ano", "1º ano", "1º ano", "2º ano", "2º ano",
"2º ano", "2º ano", "3º ano", "3º ano", "3º ano", "3º ano", "4º ano",
"4º ano", "4º ano", "4º ano", "5º ano", "5º ano", "5º ano", "5º ano",
"1º ano", "1º ano", "1º ano", "1º ano", "2º ano", "2º ano", "2º ano",
"2º ano", "3º ano", "3º ano", "3º ano", "3º ano", "4º ano", "4º ano",
"4º ano", "4º ano", "5º ano", "5º ano", "5º ano", "5º ano", "1º ano",
"1º ano", "1º ano", "1º ano", "2º ano", "2º ano", "2º ano", "2º ano",
"3º ano", "3º ano", "3º ano", "3º ano", "4º ano", "4º ano", "4º ano",
"4º ano", "5 º ano", "5 º ano", "5 º ano", "5 º ano", "1º ano",
"1º ano", "1º ano", "1º ano", "1º ano", "2º ano", "2º ano", "2º ano",
"2º ano", "2º ano", "3º ano", "3º ano", "3º ano", "3º ano", "3º ano",
"4º ano", "4º ano", "4º ano", "4º ano", "4º ano", "5º ano", "5º ano",
"5º ano", "5º ano", "5º ano", "Anos iniciais 1º ano / Parcial",
"Anos iniciais 1º ano / Parcial", "Anos iniciais 1º ano / Parcial",
"Anos iniciais 1º ano / Parcial", "Anos iniciais 2º ano / Parcial",
"Anos iniciais 2º ano / Parcial", "Anos iniciais 2º ano / Parcial",
"Anos iniciais 2º ano / Parcial", "Anos iniciais 3º ano / Parcial",
"Anos iniciais 3º ano / Parcial", "Anos iniciais 3º ano / Parcial",
"Anos iniciais 3º ano / Parcial", "Anos iniciais 4º ano / Parcial",
"Anos iniciais 4º ano / Parcial", "Anos iniciais 4º ano / Parcial",
"Anos iniciais 4º ano / Parcial", "Anos iniciais 5º ano / Parcial",
"Anos iniciais 5º ano / Parcial", "Anos iniciais 5º ano / Parcial",
"Anos iniciais 5º ano / Parcial", "1º ANO - MATUTINO/VESPERTINO",
"1º ANO - MATUTINO/VESPERTINO", "1º ANO - MATUTINO/VESPERTINO",
"1º ANO - MATUTINO/VESPERTINO", "2º ANO - MATUTINO/VESPERTINO",
"2º ANO - MATUTINO/VESPERTINO", "2º ANO - MATUTINO/VESPERTINO",
"2º ANO - MATUTINO/VESPERTINO", "3º ANO - MATUTINO/VESPERTINO",
"3º ANO - MATUTINO/VESPERTINO", "3º ANO - MATUTINO/VESPERTINO",
"3º ANO - MATUTINO/VESPERTINO", "4º ANO - MATUTINO/VESPERTINO",
"4º ANO - MATUTINO/VESPERTINO", "4º ANO - MATUTINO/VESPERTINO",
"4º ANO - MATUTINO/VESPERTINO", "5º ANO - MATUTINO/VESPERTINO",
"5º ANO - MATUTINO/VESPERTINO", "5º ANO - MATUTINO/VESPERTINO",
"5º ANO - MATUTINO/VESPERTINO", "Anos iniciais 1º ano / Parcial",
"Anos iniciais 1º ano / Parcial", "Anos iniciais 1º ano / Parcial",
"Anos iniciais 1º ano / Parcial", "Anos iniciais 2º ano / Parcial",
"Anos iniciais 2º ano / Parcial", "Anos iniciais 2º ano / Parcial",
"Anos iniciais 2º ano / Parcial", "Anos iniciais 3º ano / Parcial",
"Anos iniciais 3º ano / Parcial", "Anos iniciais 3º ano / Parcial",
"Anos iniciais 3º ano / Parcial", "Anos iniciais 4º ano / Parcial",
"Anos iniciais 4º ano / Parcial", "Anos iniciais 4º ano / Parcial",
"Anos iniciais 4º ano / Parcial", "Anos iniciais 5º ano / Parcial",
"Anos iniciais 5º ano / Parcial", "Anos iniciais 5º ano / Parcial",
"Anos iniciais 5º ano / Parcial", "1º ANO", "1º ANO", "1º ANO",
"1º ANO", "1º ANO", "1º ANO", "2º ANO", "2º ANO", "2º ANO", "2º ANO",
"2º ANO", "2º ANO", "3º ANO", "3º ANO", "3º ANO", "3º ANO", "3º ANO",
"3º ANO", "4º ANO", "4º ANO", "4º ANO", "4º ANO", "4º ANO", "4º ANO",
"5º ANO", "5º ANO", "5º ANO", "5º ANO", "5º ANO", "5º ANO", "1 º ano",
"1 º ano", "1 º ano", "1 º ano", "1 º ano", "1 º ano", "2ºano",
"2ºano", "2ºano", "2ºano", "2ºano", "2ºano", "3ºano", "3ºano",
"3ºano", "3ºano", "3ºano", "3ºano", "4ºano", "4ºano", "4ºano",
"4ºano", "4ºano", "4ºano", "5ºano")

Comment: Se não me engano o `grep` possuí um parâmetro `ignore case`.
Answer: Complementando o exemplo do Henrique:
Seleciona todos os campos que possui o "1".
txt[grep("1", txt)]

Seleciona todos os campos que possui o "1" ou textualmente "Primeiro".
txt[grep("1|primeiro", txt, ignore.case = TRUE)]

Comment: eu pensei nesse caso agora, estava fazendo os testes. valeu
Answer: Pode utilizar o parâmetro ignore.case da função grepconforme consta na documentação.
Para seu caso:
txt <- c("1º ano", "1º ano", "1º ano", "1º ano", "2º ano", "2º ano",
"2º ano", "2º ano", "3º ano", "3º ano", "3º ano", "3º ano", "4º ano",
"4º ano", "4º ano", "4º ano", "5º ano", "5º ano", "5º ano", "5º ano",
"1º ano", "1º ano", "1º ano", "1º ano", "2º ano", "2º ano", "2º ano",
"2º ano", "3º ano", "3º ano", "3º ano", "3º ano", "4º ano", "4º ano",
"4º ano", "4º ano", "5º ano", "5º ano", "5º ano", "5º ano", "1º ano",
"1º ano", "1º ano", "1º ano", "2º ano", "2º ano", "2º ano", "2º ano",
"3º ano", "3º ano", "3º ano", "3º ano", "4º ano", "4º ano", "4º ano",
"4º ano", "5 º ano", "5 º ano", "5 º ano", "5 º ano", "1º ano",
"1º ano", "1º ano", "1º ano", "1º ano", "2º ano", "2º ano", "2º ano",
"2º ano", "2º ano", "3º ano", "3º ano", "3º ano", "3º ano", "3º ano",
"4º ano", "4º ano", "4º ano", "4º ano", "4º ano", "5º ano", "5º ano",
"5º ano", "5º ano", "5º ano", "Anos iniciais 1º ano / Parcial",
"Anos iniciais 1º ano / Parcial", "Anos iniciais 1º ano / Parcial",
"Anos iniciais 1º ano / Parcial", "Anos iniciais 2º ano / Parcial",
"Anos iniciais 2º ano / Parcial", "Anos iniciais 2º ano / Parcial",
"Anos iniciais 2º ano / Parcial", "Anos iniciais 3º ano / Parcial",
"Anos iniciais 3º ano / Parcial", "Anos iniciais 3º ano / Parcial",
"Anos iniciais 3º ano / Parcial", "Anos iniciais 4º ano / Parcial",
"Anos iniciais 4º ano / Parcial", "Anos iniciais 4º ano / Parcial",
"Anos iniciais 4º ano / Parcial", "Anos iniciais 5º ano / Parcial",
"Anos iniciais 5º ano / Parcial", "Anos iniciais 5º ano / Parcial",
"Anos iniciais 5º ano / Parcial", "1º ANO - MATUTINO/VESPERTINO",
"1º ANO - MATUTINO/VESPERTINO", "1º ANO - MATUTINO/VESPERTINO",
"1º ANO - MATUTINO/VESPERTINO", "2º ANO - MATUTINO/VESPERTINO",
"2º ANO - MATUTINO/VESPERTINO", "2º ANO - MATUTINO/VESPERTINO",
"2º ANO - MATUTINO/VESPERTINO", "3º ANO - MATUTINO/VESPERTINO",
"3º ANO - MATUTINO/VESPERTINO", "3º ANO - MATUTINO/VESPERTINO",
"3º ANO - MATUTINO/VESPERTINO", "4º ANO - MATUTINO/VESPERTINO",
"4º ANO - MATUTINO/VESPERTINO", "4º ANO - MATUTINO/VESPERTINO",
"4º ANO - MATUTINO/VESPERTINO", "5º ANO - MATUTINO/VESPERTINO",
"5º ANO - MATUTINO/VESPERTINO", "5º ANO - MATUTINO/VESPERTINO",
"5º ANO - MATUTINO/VESPERTINO", "Anos iniciais 1º ano / Parcial",
"Anos iniciais 1º ano / Parcial", "Anos iniciais 1º ano / Parcial",
"Anos iniciais 1º ano / Parcial", "Anos iniciais 2º ano / Parcial",
"Anos iniciais 2º ano / Parcial", "Anos iniciais 2º ano / Parcial",
"Anos iniciais 2º ano / Parcial", "Anos iniciais 3º ano / Parcial",
"Anos iniciais 3º ano / Parcial", "Anos iniciais 3º ano / Parcial",
"Anos iniciais 3º ano / Parcial", "Anos iniciais 4º ano / Parcial",
"Anos iniciais 4º ano / Parcial", "Anos iniciais 4º ano / Parcial",
"Anos iniciais 4º ano / Parcial", "Anos iniciais 5º ano / Parcial",
"Anos iniciais 5º ano / Parcial", "Anos iniciais 5º ano / Parcial",
"Anos iniciais 5º ano / Parcial", "1º ANO", "1º ANO", "1º ANO",
"1º ANO", "1º ANO", "1º ANO", "2º ANO", "2º ANO", "2º ANO", "2º ANO",
"2º ANO", "2º ANO", "3º ANO", "3º ANO", "3º ANO", "3º ANO", "3º ANO",
"3º ANO", "4º ANO", "4º ANO", "4º ANO", "4º ANO", "4º ANO", "4º ANO",
"5º ANO", "5º ANO", "5º ANO", "5º ANO", "5º ANO", "5º ANO", "1 º ano",
"1 º ano", "1 º ano", "1 º ano", "1 º ano", "1 º ano", "2ºano",
"2ºano", "2ºano", "2ºano", "2ºano", "2ºano", "3ºano", "3ºano",
"3ºano", "3ºano", "3ºano", "3ºano", "4ºano", "4ºano", "4ºano",
"4ºano", "4ºano", "4ºano", "5ºano")

grep("1º ano", txt, ignore.case = TRUE)

Um exemplo funcional no Rextester.
Comment: o caractere especial `?` define o caractere que vem antes dele como opcional. Deste modo, ficaria `1 ?º ?ano`, encontrando os casos quando os espaços estão presentes ou não.
Comment: `ignore.case` resolve os casos de letras maiúsculas e minúsculas e já é um adianto, só que pros casos de `1 º ano` e `1ºano` talvez tenha alguma saída

Expressão Regular R


Insert em tabelas relacionadas

Question: Eai pessoal, to criando um SQL pra insert em tabelas relacionadas, são as seguintes tabelas:
tb_Customer(id_Customer INTEGER [PK], nm_Customer VARCHAR, cpf_cnpj NUMERIC)

dm_address_type(cd_address_type CHAR(1) [PK], ds_address_type VARCHAR)

tb_customer_address(id_customer [PFK],  cd_address_type CHAR(1)[PFK], street VARCHAR, lot INTEGEER, references VARCHAR, zip_code VARCHAR)

SELECT * FROM dm_address_type
cd_address_type: R , C , O
ds_address_type: Residencial, Comercial, Outros

Minha dúvida é a seguinte, para cadastrar o cliente 'JOAZINHO' seria o SQL a seguir?:
Joãozinho Silva - 888.777.666-55
Endereço Residencial: Rua das Flores, 1. CEP: 01234-567
Endereço comercial: Rua das Pedras, 100 Conjunto 200. CEP: 01234-567
INSERT INTO tb_Customer(nm_customer, cpf_cnpj) VALUES ("Jãozinho Silva", "888.777.666-55")

SET @ic_Customer = LAST_INSERT_ID()

INSERT INTO tb_customer_address(street, lot, references, zip_code, id_customer, cd_address_type) values ('Rua das Flores', '1', 'references', 01234-567', @id_Customer, 'R')

INSERT INTO tb_customer_address(street, lot, references, zip_code, id_customer, cd_address_type) values ('Rua das Pedras', '100 Conjunt 200', 'references', 01234-567', @id_Customer, 'C')

E outra duvida é de quantos endereços diferentes posso cadastrar para cada clientes? Quantos necessário, né?
Vlww pessoal. Abraço!
Comment: Qual é o gerenciador de banco de dados: MySQL ou SQL Server?
Comment: MySQL, mas difere  muito o uso do insert? VLW
Answer: Pela sua escolha de TAG ficou difícil saber se você está usando SQL Server ou MySQL.
Portanto:

Se for SQL Server:
Você não consegue utilizar LAST_INSERT_ID, precisa pegar o dado de outra forma. Você pode fazer isso utilizando: SCOPE_IDENTITY(), @@IDENTITY ou IDENT_CURRENT. Você pode ler mais sobre estas 3 opções neste link.
Se for MySQL Server:
Criei um banco aqui conforme o que você disse que colocou no seu. Ainda assim algumas coisas vão depender de como você criou seu banco, mas:

1 - Quando você tenta executar esse INSERT você receberá um erro de dado truncado por causa do CPF conter pontos. Não sei te dizer se existem maneiras de formatar o CPF para inserir na tabela, mas você consegue fazer isso depois, na consulta e no programa que for utilizar os dados, então não há necessidade de gravar os dados com os pontos como você fez;
2 - Você definiu a variável como @ic_Customer, mas nas linhas debaixo você define @id_Customer;
3 - A palavra 'references' é uma palavra reservada do MySQL. Não é recomendado utilizar palavras reservadas na sua base;
4 - No segundo endereço, em '100 Conjunt 200' você terá problemas com dado truncado. Você definiu que este campo seria uma INTEGER. Pegando esse texto de exemplo você possui um campode tamanho 15B. Integers suportam até 8B (quando você usa a opção BigInt. Eu separaria o número da casa e o complemento em dois campos diferentes (um para número com valor numérico e outro para complemento com varchar);
5 - Existem alguns erros de símbolos aí, o correto seria que seu código fosse o seguinte:
INSERT INTO tb_Customer(nm_customer, cpf_cnpj) VALUES ("Jãozinho Silva", "88877766655");

SET @id_Customer = LAST_INSERT_ID();

INSERT INTO tb_customer_address(street, lot, reference, zip_code, id_customer, cd_address_type) values ('Rua das Flores', '1', 'references', '01234-567', @id_Customer, 'R');

INSERT INTO tb_customer_address(street, lot, reference, zip_code, id_customer, cd_address_type) values ('Rua das Pedras', '100 Conjunt 200', 'references', 01234-567', @id_Customer, 'C')

6 - Sim, você consegue cadastrar vários endereços para o mesmo cliente.

Insert em tabelas relacionadas


403 error in files while hosting drupal site in hostgator

Question: I'm trying to host my drupal site in Hostgator. Here what i've done so far:
a. uploaded files to server, created db and user and imported too.
b. Change settings.php database content.
My site is up and running although my css and files are not being loaded..when i check my browser console it shows 403 error, even i can't access my backend whenever i try to access it shows 404 error,although it seems to be working fine on my localhost.. i know it's permission problem but i don't know how to deal with it is there any steps i leftover which i need to follow, is there any step by step documentation on hosting drupal site on cpanel any help would be great.Thanks in advance.
P.S.-i'm using nginx, and linux system for my development environment.
And new to drupal :)
Comment: I'm voting to close this question as off-topic because it's a problem with loading static files, and wouldn't be different if these CSS would be Wordpress-created or manual. You should rather contact your hosting company, they are the ones who have technical means to know the reason behind your issue.
Comment: static :( could you elaborate in what logic you mean by static it's an e-commerce site build by drupal commerce and by other different modules..although thanks for your concern
Comment: I mean that this file was uploaded there and just sits on the server's filesystem. It's not created dynamically by Drupal's PHP.
Comment: i don't think by any mean you understood my last reply it was  site created by drupal and almost every files are dynamically created with drupal using several module and problematically...any way thanks for you concern hoping for better answer :) kudos
Comment: Sorry, but that (usually) does not work like that. Drupal themes provide CSS files. They are just regular files that sit in `/sites/*/themes/`. And they are accessed like any other CSS you would ever upload to your server. OK, if you turn on CSS aggregation, Drupal creates aggregated CSS files - but then again they are just files on server's disk, accessed in good old regular way. Unless, of course, something generates them dynamically, but that's an exception and you should describe it with greater detail if we are to help you. First step: URI of resources that fails.
Comment: well my problem is with the drupal right permission on every files and folder in drupal i guess since it's 403 error..i just wanted to know is there anyway i could bulky manage the file permission of hosted file so that it meets drupal standard on server side..like something like script if so how am i suppose to do...i'm kind of lost over here.The site i'm trying to host is www.drupalizenepal.com
Answer: Read up on the basics of linux permissions. Figure out which user nginx is running under. Make sure that user has read access on files and read/execute access on directories.


Strong convergence of subgradients of a convex Fréchet differentiable function on a normed space

Question: This thread is meant to record a question that I feel interesting during my self-study. I'm very happy to receive your suggestion and comments. See: SE blog: Answer own Question and MSE meta: Answer own Question.

Let $X, Y$ be normed spaces, $A$ a subset of $X$, $f:A\to \mathbb R$, $\Phi: A \to \mathcal P(Y)$ a multivalued mapping, and $a \in A$.

The subdifferential of $f$ at $a \in A$ is the set
$$
\partial f(a)=\left\{x^* \in X^* \mid f(x) - f(a) \ge \langle x^*, x-a \rangle \text { for each } x \in A\right\}.
$$
The elements of $\partial f(a)$ are called subgradients of $f$ at $a$.

The image by $\Phi$ of a subset $E$ of $A$ is defined as $\Phi(E) := \bigcup_{x \in E} \Phi(x)$. We say that $\Phi$ is single-valued and continuous at $a$ if $\Phi(a)=\left\{y\right\}$ and
$$
\forall \varepsilon>0, \exists \delta>0:\left[x \in A, |x-a|<\delta \implies \Phi(x) \subset B \left(y, \varepsilon\right)\right] .
$$
It can be proved that $\Phi$ is single-valued and continuous at $a$ if and only if $\Phi(a) = \{y\}$ and $[A \ni x_{n} \rightarrow a, y_n \in \Phi (x_n) \implies y_{n} \to y]$.

Theorem:  Let $A$ be open and $f$ convex continuous. Then $f$ is Fréchet differentiable at $a$ if and only if $\partial f$ is single-valued and continuous at $a$.

A direct corollary is as follows:

Let $A$ be open and $f$ convex continuous. If $f$ is Fréchet differentiable at each point of $A$, then $f \in \mathcal{C}^{1}(A)$.
Answer:
Let $\partial f$ be single-valued and continuous at $a$.

Let $x^* \in \partial f (a)$. Let $r>0$ such that $B(a, r) \subset A$. Let $h_n \in B(0, r)$ such that $h_n \to 0$. By this result, $\partial f (x) \neq \emptyset$ for all $x\in A$. Let $x^*_n \in \partial f (a+h_n)$. Then
$$
0 \le \frac{f(a+h_n)-f(a) - \langle x^*, h_n \rangle}{|h_n|} \le \frac{\langle x_n^*, h_n  \rangle - \langle x^*, h_n \rangle}{|h_n|} = \frac{\langle x_n^* -  x^*, h_n  \rangle }{|h_n|} \le \| x_n^* -  x^*\|.
$$
It follows from $x_n^* \to  x^*$ that
$$
\lim_n \frac{f(a+h_n)-f(a) - \langle x^*, h_n \rangle}{|h_n|} = 0.
$$
Hence $f$ is Fréchet differentiable at $a$.

Let $f$ is Fréchet differentiable at $a$.

Then $f$ is Gâteaux differentiable at $a$. By this result, $\partial f (a)$ is a singleton. Let $x^* \in \partial f (a)$.  Let $x_n \to a$ and $x_n^* \in \partial f (x_n)$. It suffices to show that $x_n^* \to x^*$. Let
$$
\varphi(v) := \frac{f(a+v)-f(a) - \langle x^*, v \rangle}{|v|}.
$$
We have

$-\langle x^*, v \rangle = |v| \varphi (v) +f(a)-f(a+v)$.
$f(x_n+v)-f(x_n) \ge \langle x_n^*, v \rangle$.

By this result, there are $L,h>0$ such that $B(a,h) \subset A$ and that $f$ is $L$-Lipschitz on $B(a, h)$. For all $0<r<h/2$, we have
$$
\begin{align}
\|x_n^*-x^*\|  &=  \sup_{|v|=r}  \frac{\langle x_n^* - x^*, v \rangle}{r} \\
&\le \sup_{|v|=r} \frac{f(x_n+v)-f (x_n)  +|v| \varphi (v) +f(a)-f(a+v)}{|v|} \\
&= \sup_{|v|=r} \left [\frac{[f(x_n+v) - f(a+v)]+ [f(a) - f (x_n)]}{|v|}  +\varphi (v) \right ]\\
&\le \sup_{|v|=r} \left [\frac{2L|x_n-a|}{|v|}  +\varphi (v) \right ] \\
&= \frac{2L|x_n-a|}{r}  + \sup_{|v|=r}  \varphi (v).
\end{align}
$$
For all $0<r<h/2$, we have
$$
\lim_n \|x_n^*-x^*\| \le \frac{2L}{r} \lim_n |x_n-a| +  \sup_{|v|=r}  \varphi (v) = \sup_{|v|=r}  \varphi (v).
$$
Notice that
$$
\lim_{r \to 0^+} \sup_{|v|=r}  \varphi (v) = 0.
$$
So $\lim_n \|x_n^*-x^*\| = 0$. This completes the proof.


Está certo utilizar string quando o valor é inteiro?

Question: Hoje me deparei com certa situação, que me deixou com duvida:
Em minha aplicação tenho algumas ID's vindas de uma tabela, essas ID's são valores inteiros (1,2,3, e assim por diante) e todas eu trato elas como string.
Uma dos motivos que faço isso é para não utilizar o método: Convert.Toint e acabo utilizando o método : .ToString()
Não vou realizar nenhuma operação matemática, é somente para identificação de registros (primary key).
Estes ID's são obtidos de uma GridView populado por um DataTable que por sua vez tem os dados vindo do BD, esses ID's são gerado pelo banco por uma coluna com Identity então nunca teremos valores duplicados.
Também não me interessa se o valor é o primeiro, ultimo, qual é o próximo, é apenas para identificar a ação de exclusão do registro.
Esse tratamento, esta correto? qual a forma indicada nesses casos?
Comment: E como você grava esses IDs? Como garante que eles são únicos? Como sabe qual é o próximo? Dê mais contexto.
Comment: como vc trata o ID tem a ver com as necessidades da sua aplicação...  se você não tá usando pra nada então nem binda esse valor no objeto da aplicação
Comment: pelo oq eu entendi são inteiros que ele trata na aplicação como string... e a dúvida é se esse tratamento tá correto
Comment: @J.Guilherme preciso desses valores, pois ele identifica o registro a ser excluído, e a duvida e essa mesmo, se o tratamento esta correto.
Comment: @bigown fiz uma revisão na pergunta
Comment: O ID do banco de dados é numérico, certo?
Comment: Veja se te ajuda: http://pt.stackoverflow.com/q/136398/101, http://pt.stackoverflow.com/q/45213/101 e http://pt.stackoverflow.com/q/16967/101.
Comment: @bigown sim, no banco é int, obrigado vou ler essas perguntas, mas essa daqui já ta mais que respondida, se é inteiro trate como inteiro, sem surpresas, obrigado.
Answer: Não existe correto ou errado propriamente dito nesse caso. Existe o indicado e o mais eficiente. Se os campos são inteiros, trate-os como tal. Pode parecer que não tenha qualquer coisa o impedindo de usar os inteiros convertidos para string nessa situação, mas existe uma "regra" em desenvolvimento de sistemas que costumo seguir com muito sucesso: Faça a coisa menos surpreendente. Sempre.
Surpreendente, no caso, deve ser lido como "algo que gere menos surpresa".
Nesse caso, se o campo é inteiro (ou long) no banco de dados, trate-o como tal no seu código também. Isso gerará menos surpresa a algum outro programador, ou até à você mesmo quando vier resolver um bug no código daqui a alguns anos. Ademais, usar Convert.ToInt32() no lugar de ToString() não terá qualquer diferença, mas apenas o fato de você se perguntar se tratar o inteiro como string no seu código é o certo, já mostra que o ideal seria nem precisar fazer essa pergunta e tratar inteiro como o inteiro que é.
Te garanto também que no DataTable esse campo é inteiro. Se for comparar o ID do GridView com o id no dataset/datatable, pode vir a ter que converter de volta para inteiro de qualquer
Há ainda funcionalidades futuras que possam ser afetadas por essa conversão desnecessária feita hoje. Por exemplo, você pode vir a precisar colocar os Ids dentro de um Hashset e se forem strings as operações serão mais lentas (não muito, pois o Hashset usa um hash para ser encontrado, mas há perda de performance). Você pode querer ordenar os Ids para saber qual foi criado antes no banco de dados (já que é identity) e a ordenação de strings, além de muito mais lenta, não segue a ordem numérica: "10" < "2" enquanto que 10 > 2.
Resumindo: enquanto existem motivos para usar inteiro como inteiro, com vantagens, não existem vantagens nem motivos (no seu caso) de tratá-los como string.
Não pregue peças em si mesmo (e nos outros que usem seu código). Faça o que gere menos surpresa. Se pergunte: O que é o mais esperado? Que um campo inteiro no banco seja tratado como string no seu código, ou que seja tratado como inteiro mesmo?
Answer: Apesar de você não utilizar as IDs para operações matemáticas, você certamente faz comparacoes, principalmente na busca de dados no seu banco. Pensando em performance, a melhor pratica ainda e utilizar numeros, pois as comparacoes podem ser feitas em um ciclo, ao passo que comparacao de strings requer que cada caractere seja comparado (a menos que voce converta para numeros).
Com relacao a sua preocupacao de chamar ToString repetidamente, pode ficar tranquilo, pois este metodo e muito rapido e otimizado a nivel da CLR, entao jamais sera o bottleneck em nenhuma aplicacao. O que poderia ser um problema e o boxing e unboxing dos valores, ou seja, deixando que o C# faca o trabalho pra voce.
Por exemplo, o codigo
for(int i = 0; i < 50; i++) {
    sb.Append(i.ToString());
    sb.Append(",");
}

é mais rapido do que
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 50; i++)
    sb.Append (i + ",");

Justamente porque o segundo requer operacoes de boxing e unboxing extras.
Desta forma, faz mais sentido se preocupar com a eficiencia da busca no seu banco e outras comparacoes entre as IDs do que com ToString, o que significa que, no geral, int seria uma escolha melhor.
Comment: Na verdade o que ocorre então é uma otimização do compilador. Por isso queira ver o IL gerado e, novamente, tem que testar a performance, uma vez que o otimizador pode muito bem evitar o boxing desnecessário. Ainda há o caso de haver uma chamada de método a mais no segundo exemplo. Concordo com você sobre o hit de performance com operações de boxing e unboxing, mas não acredito que o exemplo específico resulte em código mais lento, pois não isola o problema do boxing/unboxing. Mais tarde meço ambos os métodos.
Comment: Fiz os testes de performance e, inclusive, comentei na resposta no Stack Overflow em inglês. O grande culpado da perda de performance nesse exemplo é o `string.Concat()` que acaba ocorrendo no primeiro exemplo e que não acontece no segundo. Isso dá uma diferença de uns 30ms em 1 milhão de iterações. Se mudarmos o código para forçar o boxing, mas deixarmos separados em duas chamadas ao `sb.Append()` essa diferença cai para 5ms. Ou seja, você está certo, tem um impacto negativo, mas o maior impacto nesses exemplos não é do boxing!
Comment: Você mediu a performance dos dois casos usando uma quantidade alta de iterações? Pode se surpreender... Sem falar que provavelmente ocorre boxing nos dois casos, já que para chamar `ToString` tem que ser tratado como object... Mas teria que ver o IL de ambos os casos.
Comment: Sim. Este exemplo eh conhecido, tirei do livro c# in a nutshell. Existe uma pergunta desse exemplo no SO tbm onde a pessoa explica mais afundo a diferenca. Quando voce chama ToString em um tipo, por exemplo i.ToString, onde i é um inteiro, voce pula a parte do boxing porque a informacao ja e conhecida. Voce pode ver na IL gerada pelo compilador. http://stackoverflow.com/questions/18293932/c-why-does-tostring-append-text-faster-to-an-int-converted-to-string


Exibir dado em tempo real

Question: Estou tentando exibir um dado retirado diretamente de meu banco de dados com esse script:

Já inclui no início do arquivo todos os dados de conexão e etc... Gostaria de exibir esses dados em uma div, estilo "card"... Saberiam me dizer o que está errado?
Comment: Você já ouviu falar de linguagens do lado do servidor e do lado do cliente? Por exemplo, PHP atuará no lado do servidor, enquanto JavaScript, neste caso, atuará no lado do cliente. O **único** jeito deles se comunicarem é por HTTP. Pesquise sobre isso, pois parece que ainda lhe falta alguns conceitos **básicos** e **necessários**.
Comment: Amigo, você não vai conseguir rodar um código php dentro de um escopo javscript.
O que você pode fazer é enviar um ajax com os dados pro servidor php, fazer a consulta, e exportar os dados de volta pro javascript. Ai então você faz o setInterval e atualiza de x em x tempos.
Comment: Siga isto: https://aiocollective.com/blog/auto-refresh-content-after-changes-in-database-ajax/
Comment: Tudo bem, muito obrigado!
Comment: div `estilo "card"...` como assim?
Comment: Bem-vindo Erick Figueiredo, não deixe de ler esses posts para poder obter boas respostas https://pt.stackoverflow.com/help/mcve
Comment: Uma boa pratica será aceitar uma resposta que porventura tenha resolvido seu problema. Veja como em  https://i.stack.imgur.com/evLUR.png e porque em https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Answer: No javascript chame via ajax a página PHP que executa o SELECT e retorna o resultado pretendido mostrando-o na

.

selectNumUsuarios.php
<?php
$mysqli = new mysqli("localhost", "USUARIO", "SENHA", "Nome_DB");

/* checa conexão */
if (mysqli_connect_errno()) {
    printf("Conexão falhou: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT id FROM cadastro")) {

    /* determina o número de linhas retornadas */
    $numUsuarios = $result->num_rows;

    printf($numUsuarios." Usuarios");

    $result->close();
}

/* fecha a conexão */
$mysqli->close();
?>

Comment: Caro Leo, setInterval vai executar deliberadamente, seria melhor setTimeout, que "deve" ser configurado para ser executado quando terminar a requisição XmlHttpRequest
Comment: @GuilhermeNascimento, bem lembrado, mas não sei qual a intenção do AP, resolvi então colocar uma OBS a respeito.
Comment: Caro Leo, não é questão de intenção do AP, setInterval com requisições assincronas do qual você não tem ideia de quando vai responder pode ocasionar um efeito colateral terrivel, pois o setInterval não esperada nada, o problema esta no seu código proposto.
Comment: O que o guilherme está tentando dizer é: Ao invés de fazer um setInterval pra rodar o ajax, coloque um setTimeout dentro do escopo do sucess dentro do ajax. Assim ele só vai chamar novamente quando a primeira requisição estiver completa e funcional. Caso contrário, pode acabar mandando outra requisição enquanto uma ainda está ocorrendo, que pode se resumir numa grande quantidade de problemas.
Comment: Valeu GuilhermeNascimento e @Máttheus Spoo, resposta editada.

Exibir dado em tempo real


Fila é criada mas nunca é executada

Question: Eu estou tentando criar filas para disparar notificações push e emails a partir de uma API com o Lumen. Tenho a classe WarningUser que faz os disparos assim:
<?php

namespace App\Utils;

use App\Jobs\ProcessNotification;
use App\Mail\AllMail;
use Illuminate\Support\Facades\Mail;

class WarningUser
{

  public static function send($user, $message, $url, $data = [])
  {
    $url = env('APP_URL_FRONT') . $url;
    dispatch(new ProcessNotification($user, $data, $message, $url));

    $emailData = EmailTexts::texts('pt', $data)[$message];
    Mail::to($user->email)->queue(new AllMail($emailData['title'], $emailData['content']));

    return true;
  }
}

O primeiro Job envia a notificação via Firebase:
<?php

namespace App\Jobs;

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\Notification;
use Kreait\Firebase\Messaging\CloudMessage;

class ProcessNotification extends Job
{
    protected $user = null;
    protected $data = null;
    protected $message = null;
    protected $url = null;

    public function __construct($user, $data, $message, $url)
    {
        $this->user = $user;
        $this->data = $data;
        $this->message = $message;
        $this->url = $url;
    }

    public function handle()
    {
        if (\is_string($this->user->token) and $this->user->token !== '') {
            $messaging = (new Factory())
                ->withServiceAccount(__DIR__.'/../../private-key.json')
                ->createMessaging();

            $notificationData = NotificationTexts::texts('pt', $this->data)[$this->message];
            $messageAlert = CloudMessage::withTarget('token', $this->user->token)
                ->withNotification(Notification::create($notificationData['title'], $notificationData['content']))
            ->withData([ 'url' => $this->url ]);

            $messaging->send($messageAlert);
        }
    }
}

O segundo envia um simples email:
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class AllMail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;
    protected $title;
    protected $body;

    public function __construct($title, $body)
    {
        $this->title = $title;
        $this->body = $body;
    }

    public function build()
    {

        return $this
            ->subject($this->title)
            ->view('email')
        ->with([
            'title' => $this->title,
            'body' => $this->body
        ]);
    }
}

O código dos dois funcionam, já testei antes de colocar na fila e funcionam, basta eu colocar na fila que não funcionam mais. Olhei no meu banco, os jobs estão sendo armazenados como podemos ver na imagem:

Mas a fila nunca está sendo processada, eu já tentei executar php artisan queue: work e php artisan queue: listen, mas nunca funciona.
A fila nunca nem tenta ser processada, pois nunca tem nada na tabela failed_jobs.
Meu config/queue.php está assim. E no meu .env tenho o QUEUE_CONNECTION = database.
<?php

return [
    'default' => env('QUEUE_CONNECTION', 'database'),
    'connections' => [
        'sync' => [
            'driver' => 'sync',
        ],

        'database' => [
            'driver' => 'database',
            'table' => 'jobs',
            'queue' => 'default',
            'retry_after' => 90,
        ],

        'beanstalkd' => [
            'driver' => 'beanstalkd',
            'host' => 'localhost',
            'queue' => 'default',
            'retry_after' => 90,
            'block_for' => 0,
        ],

        'sqs' => [
            'driver' => 'sqs',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
            'queue' => env('SQS_QUEUE', 'your-queue-name'),
            'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
        ],

        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
            'queue' => env('REDIS_QUEUE', 'default'),
            'retry_after' => 90,
            'block_for' => null,
        ],

    ],
    'failed' => [
        'driver' => env('QUEUE_FAILED_DRIVER', 'database'),
        'database' => env('DB_CONNECTION', 'mongodb'),
        'table' => 'failed_jobs',
    ],
];

Alguém pode me ajudar? Estou a um tempo nisso mas não consegui progredir.
PS: nenhum erro é mostrrado no navegador ou terminal.
Answer: Não sei porque o voto negativo em uma pergunta válida e bem documentada. Enfim, consegui resolver, para o Mongo precisamos usar algumas configurações a mais:
A conexão no queue.php deve ser:
'connections' => [
    'database' => [
        'driver' => 'mongodb',
        'table'  => 'jobs',
        'queue'  => 'default',
        'expire' => 60,
    ],
...

E precisamos registrar o provedor do pacote que trabalha com mongo:
Jenssegers\Mongodb\MongodbQueueServiceProvider::class,

Fila é criada mas nunca é executada


what does #+ mean in bash scripting?

Question: I was reading a tutorial about bash scripting on https://www.tldp.org/LDP/abs/html/special-chars.html
and noticed that some comments begin with #+ instead of #
echo ls -l | sh
#  Passes the output of "echo ls -l" to the shell,
#+ with the same result as a simple "ls -l"

I'm guessing the author decided to use #+ to mention continued comment from the previous line.
Is this the case and is it a common convention in bash?
Comment: It's just their own (silly) convention (for comment continuation). By the way, the ABS used to be frown upon by Bash guys, as it used to be full of antipatterns. I don't know how the recent revisions are, but I believe there are much better sources out there.
Comment: @gniourf_gniourf could you please recommend a better source or two then?
Comment: Have a look at the resources in the [Bash tag](https://stackoverflow.com/tags/bash/info). I guess that Lhunath's Bash guide must be good... at least it will focus on writing proper scripts (you know, quoting expansions, not using external tools in silly ways, etc.). The [BashFAQ](http://mywiki.wooledge.org/BashFAQ) is also awesome (yet, not really a tutorial, but definitely worth reading!).
Comment: Thanks! @gniourf_gniourf
Answer: Comments start with #. There is no convention associated with comments (well, they should be readable and about the code..........). The standard does not mention what syntax should a comment have. The string after # is not parsed, so #+ is equivalent to #!!@#$%^&*() and is not anything special when parsed by Bash. The #+ is just the author's convention to continue a comment in the next line if they didn't end the sentence in the previous line.
Answer: This is not a convention but here, I assume like you, the author wanted to link both comments.
The real way to do it in bash is to use the multiline comment:
    : '
    This is a
    multiline comment.
    '

Please note that the space between the : and ' is important.
Comment: @KamilCuk: Since both `true` and `:` are builtin commands, the shell is unlikely to execute `fork()`. But I wouldn't write a multi-line comment that way. Any decent editor will let you insert a `#` at the beginning of each line in a range without having to type it N times.
Comment: The `:` is a shell special utility as specified by POSIX, with it's (original ;) ) purpose to write empty `if` or `while` statements, ie. `if smth; then :; else :; fi`. POSIX documentation available [here](http://pubs.opengroup.org/onlinepubs/009695399/utilities/colon.html).
Comment: Wrong, this is a multiline comment. Much easier to use than multi `#` :)
Comment: Comments with `#` are ignored by bash, but this, bash is gonna try to run this.
Comment: For those having problem with this, here is a cheat sheet: https://devhints.io/bash with `: '` as multiline. I've always used it without issues.
Comment: It _can_ be used for somewhat _hack_ as a multiline comment, as bash does not support multiline commenting, but it __IS__ a command equivalent to `true`. When you write `: something` the shell executes `fork() -> exec(true ....) -> waitpid() -> etc.. `. When you write `# something` the shell ignores it. These are not equivalent.

what does #+ mean in bash scripting?


Defining a contact form

Question: I am trying to understand contact structures. To this end, as an exercise, I intend to define a contact form on $S^3$. Here is what I have so far:
Since $S^3$ is in $\mathbb R^4$ one can specify a point on $S^3$ by a $4$-tuple $(x,y,z,w)$. If one endows $S^3$ with stereographic coordinate charts one obtain coordinates as follows: $({2X\over X^2 + Y^2 + Z^2 + 1}, {2Y\over X^2 + Y^2 + Z^2 + 1}, {2Z\over X^2 + Y^2 + Z^2 + 1}, {X^2 + Y^2 + Z^2 - 1\over X^2 + Y^2 + Z^2 + 1})$ where $(X,Y,Z)$ is a point in $\mathbb R^3$.
The standard contact structure on $S^3$ is given by  $xdz - z dx + y dw - w dy$.
My question is:

Does $xdz - z dx + y dw - w dy$ mean the contact structure is
  ${2X\over X^2 + Y^2 + Z^2 + 1}d{2Z\over X^2 + Y^2 + Z^2 + 1} - \dots$
  and so on?
Answer: Yes, if you use the stereographic projection then it is the form you indicated.
To be precise, $\alpha = x dz - zdx + y dw - wdy$ is a one form on $\mathbb R^4$. So the contact structure on $\mathbb S^3$ is really $\iota^* \alpha$, where $\iota : \mathbb S^3 \to \mathbb R^4$ is the inclusion.
Comment: Hm... This suggests I can take any $1$-form in $\mathbb R^{2n}$ and then the inclusion of it will make it a contact form on $S^{2n-1}$?
Comment: Is the inclusion map $i: S^3 \to \mathbb R^4$ the map $(x,y,z) \mapsto (x,y,z,0)$?
Comment: No, wait, it's $(x,y,z) \mapsto (x,y,z)$, right? But isn't then $\iota^\ast \alpha = \alpha$ because $\iota^\ast$ is the identity?
Comment: $\mathbb S^{2n-1}$ itself is a manifold, and $i$ is really the set inclusion mapping @self-learner
Comment: But $\iota6\ast \alpha = \alpha$, right? Because $\iota^\ast$ is the identity.
Comment: $\alpha$ is not a one form on $\mathbb S^{3}$. It's a one form on $\mathbb R^4$. there is a difference between $\iota^*\alpha$ and $\alpha$. For example, if $\beta = x dx + ydx + zdz +wdw $ on $\mathbb R^4$, then $\iota^*\beta$ is actually zero. The identity $\iota^* \alpha = \alpha$ just don't make sense since they are different object. @self-learner
Comment: I believe to have found an easier way: to use the contact structure on some $\mathbb R^n$ on a sphere by moving up the dimension. For example, on $\mathbb R^5$ the standard contact structure is $$ \alpha = dz + \sum_{j=1}^2 x_j dy_j$$
Now since $S^3$ is a subset of $\mathbb R^5$ we can use this structure as is on $S^3$. This works, right? Or am I missing something?

Defining a contact form


Finding plane from from the projection of a line

Question:
The projection of line $$\frac{x}{2}=\frac{y-1}{2}=\frac{z-1}{1}$$ on a plane $P$ is $$\frac{x}{1}=\frac{y-1}{1}=\frac{z-1}{-1}$$ Determine the equation of the plane.

What I tried:

Clearly, $(0,1,1)$ lies on both the plane and line.
$$\cos\theta=\dfrac{2(1)+2(1)+1(-1)}{3\sqrt3}=\dfrac1{\sqrt3}\\ \sin\theta=\sqrt{\dfrac23}$$
The angle between the line and the unit normal is $\arccos\left(\sqrt{\dfrac23}\right),$ and the unit normal is perpendicular to the projected line. Using dot product:
\begin{align} (a,b,c)\cdot(2,2,1)&=3\sqrt{\dfrac23}\\
2a+2b+c&=\sqrt6\tag1\end{align}
\begin{align}
(a,b,c)\cdot(1,1,-1)&=0\\
a+b-c&=0\tag2\end{align}
But they are underdetermined. What am I doing wrong?
Comment: "*But they have no solution.*" This is misleading; better to say that they are underdetermined, or have no definite solution, or somesuch. On the other hand, something like `a+b=1; a+b=2` certainly has no solution.
Answer:
$$(a,b,c)\cdot(2,2,1)=3\sqrt{\dfrac23}\\2a+2b+c=\sqrt6\\ (a,b,c)\cdot(1,1,-1)=0\\a+b-c=0$$

The first dot product gives $2a+2b+c=\sqrt6$, then you combine with $a+b-c=0$ to get
$$c=\frac{\sqrt6}3,~~~a+b=\frac{\sqrt6}3\tag{1}$$
Note you assume the normal vector has unit length, which means
$$a^2+b^2+c^2=1\tag{2}$$
From (1) and (2), you can solve $a$ and $b$.
Comment: Ah, yes, thank you! @ryang
Answer: That is a great question!
we have the two lines,
$L_1:\frac{\mathrm{x}}{2}=\frac{\mathrm{y}-1}{2}=\frac{\mathrm{z}-1}{1}=\lambda$
Direction cosines : $(2,2,1)$ and Point on the line being : $(0,1,1)$
$L_2:\frac{\mathrm{x}}{1}=\frac{\mathrm{y}-1}{1}=\frac{\mathrm{z}-1}{-1}=\mu$
Direction cosines : $(1,1,-1)$ and Point on the line being : $(0,1,1)$
As $L_2$ lies on the plane, let it pass through a point 'A' whose parametric coordinates as a function of $\mu$ be $(\mu,\mu+1,-\mu+1)$, similarly Let $L_1$ pass through a point 'B' whose parametric coordinates as a function $\lambda$ be $(2\lambda,2\lambda+1,\lambda+1)$, for simplicity sake let $\lambda$ = 1 which makes B$(2,3,2)$. Now the most important fact to create any plane equation is we need a point on the plane and we need a normal vector to the plane, and luckily we do have a point on the plane as seen from $L_2$ line which passes through $(0,1,1)$ and so does the plane, now the fight is to get the normal;
Join A($\mu$) and $B(2,3,2)$ to get $AB$ vector and let us consider a situation $AB$ vector is perpendicular to the line $L_2$, hence their dot product of their direction ratios is 0, i.e.,
AB.$L_2$ =0
Substituting AB line = $(\mu-2)i+(\mu-2)j+(-\mu-1)k$ above,
On solving,$\mu$=1
How?, well the direction ratio of $L_2$ is $i+j-k$ and how was AB made? $(x_2-x_1)i+(y_2-y_1)j+(z_2-z_1)k$
So, AB vector(say n) = $-i-j-2k$, aka your normal,
The equation of plane using a point on the plane and normal to the plane is
$(r-n).a=0$ (where a = $(0,1,1)$ and $r = xi+yj+zk$)
Hence your plane equation is $x+y+2z-3=0$
Answer: When setting the condition $(a,b,c)\cdot(2,2,1) = 3\sqrt{\frac{2}{3}}$ you should also set $||(a,b,c)||=1$ , otherwise it won't give you what you want and then you'll get weird results.
But $(a,b,c),(2,2,1)$ and $(1,1,-1)$ are in the same plane, so, the cross product of $(2,2,1)$ and $(1,1,-1)$ is perpendicular to $(a,b,c)$.
$$(2,2,1) \times (1,1,-1) = (-3,3,0)$$
$$(a,b,c)\cdot(-3,3,0) = 0 \iff a=b$$
Also, as you already stated, $a+b-c=0$
$a=b$ and $a+b-c=0$ , gives $c=2a$ and $b=a$.
So, $N=(a,a,2a)$. In this case, it's not necessary that $||N||$ equals $1$, so $N$ may be, for example, $(1,1,2$).
So the plane you're looking for is $x + (y-1) + 2(z-1) = 0$


How add CVV's custom validation before order review in Ubercart

Question: I'm developing a Gateway Payment module for Ubercart. It is necessary to validate that the User does not digit three ceros -000- (bank policy) before the order review form. I've seen that Ubercart does the CCV's validation in the uc_credit.module
<code>      if (variable_get('uc_credit_cvv_enabled', TRUE) && !_valid_cvv($cc_data['cc_cvv'])) {
        if (!$silent) {
          drupal_set_message(t('You have entered an invalid CVV number.'), 'error');
        }
      $return = FALSE;
      }
</code>
How could I add my validation without hacking Ubercart modules.
Thanks in advance.
Answer: You can create a custom validation function in your module and name it whatever you like for example 'custom_validation_function'. and in the same module add this validation function to the form's validation list by using form_alter.
<code>function <module_name>_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == '<ubercart_form_id>') {
    $form['#validate'][] = 'custom_validation_function';
  }
}
</code>


Java:How to populate jtable with one only column?

Question: I have to display authors on a table and I made only 1 column for it. I have used a jtable before but with 2d arrays and multiple columns. I'm having problems with this one.The 'authors name' are stored in mysql.
tblAuthor.setModel(new javax.swing.table.DefaultTableModel(
authorData,new String[]{"Name"}){
@Override
public boolean isCellEditable(int row, int column) {
    //all cells false
    return false;
}
@Override
public Class getColumnClass(int columnIndex) {
    return String.class;
}
})
}

this one is how i retrieve the authors
private Object[][] getAuthors(int id) throws SQLException{
        sql="SELECT authorName FROM tbl_textbook as b,tbl_txauthor as a where a.bookID=b.bookID AND a.bookID="+id;
    rs=stm.executeQuery(sql);
    rs.next();
    Object authors[][] = new String[countAuthors(id)][1];
    if(rs.getRow()!=0)
         authors=new String[rs.getInt(1)][1];
    i=0;
    while(rs.next()){

        authors[i][1]=rs.getString(1);
        i++;
    }

    return authors;
}

I'm a noob so please help.thank you
Answer: try
   authors[i][0]=rs.getString(1);

java array are 0 based unlike resultset that are 1 based


Error class in Java

Question: I am trying to understand the Error class in Java.
I have a good understanding of the Exception class, but can't find examples of code for the Error class. I've tried searching the web and also the java.sun website, but I'm not finding anything useful to help me understand this better.
How do I use the Error class in programs and where do we have to use that?
Comment: what is your exact requirement.can you detail it more.
Comment: i want to know the use of Error class and where we have to use that
Answer: You don't use Error in your code.
An Error is a specific kind of Throwable, just as Exception is.

Throwable is the base class that defines everything that can be thrown.
Exception is the common case. It is about problems that occur during the execution of your program.

RuntimeException is a special case: it's unchecked (i.e. it need not be declared by a method and the compiler doesn't force you to catch it).

Error is the "rare" case: it signifies problems that are outside the control of the usual application: JVM errors, out of memory, problems verifying bytecode: these are things that you should not handle because if they occur things are already so bad that your code is unlikely to be able to handle it sanely.

You should not attempt to correct the situation that resulted in an Error. You might want to catch it in order to log it and then rethrow it (see the JavaDoc of ThreadDeath for an example on why you need to rethrow it (thanks to @krock for the heads-up)).
There is no other reason to throw any Error (i.e. don't create an Error on your own and throw it, if you think you want to do that, use an Exception or a RuntimeException instead).
Comment: btw I wasn't the downvoter, just adding my thoughts, +1 for a good summary of the exception hierarchy.
Comment: *...you could catch an Error...* if you catch an Error you should generally rethrow it (see javadoc for [ThreadDeath](http://download.oracle.com/javase/6/docs/api/java/lang/ThreadDeath.html) for one reason why)
Comment: @satheesh: while *application code* should not throw an `Error`, the JVM can (and will). Look at [`OutOfMemoryError`](http://download.oracle.com/javase/6/docs/api/java/lang/OutOfMemoryError.html). There's usually not much the application can do, if that happens. At best it can try to safe the ongoing work, but even that might fail (the JVM is out of memory after all!).
Comment: For those that use Eclipse, have you ever had it run out of memory? It essentially catches this, gives you the option of continuing or restarting. In the case of OutOfMemory your app might be able to free up enough to save critical work as a last ditch effort.
Comment: Thanks, krok, I rephrased the final bit to clarify the need to re-throw when an `Error` is caught.
Comment: Then what is the need of a class Error when it is not used and it throws abnormal exceptions ? And what is the need to throw that Error object ...any how if there is abnormal error the application going to be stopped
Answer: If you take a look at the Javadoc here there is a good explanation:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

Concerning the usage you also have this:

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.
Answer:
Error
Error a subclass of "Throwable" class is thrown by java runtime system and indicate some unrecoverable conditions during the execution of the programs
    Once thrown difficult to recover from it and the application get to halt.
   Eg..,java.lang.StackOverflowError and java.lang.OutofMemoryError

// An example code which throws StackOverflowError
public class ErrorDemo
   {
          public void method1()
            {
                   this.method2();
            }

          public void method2()
           {
                    this.method1();
           }

 public static void main(String sri[])
           {
                ErrorDemo k= new ErrorDemo();
                     k.method1();
            }
 }

In this code from main method we are calling method1 and from method1 a call was  made   to method2 and again from method2 we are calling method1 means we created a continous loop which doesn't goes to end and finally a critical error StackOverflowError is being thrown.

Error class in Java


Spam url_alias entries being created - how do I stop them?

Question: I'm using Drupal 6 and having trouble with url_alias spam.
Somehow spam entries are showing up in the url_alias table as aliases for valid content.
I thought an administrator or valid user would have to create these.  I don't understand how they're appearing for content that I created.
I appeared to have stopped spam registrations using a combination of Mollom, honey pot and spamicide.  I can't figure out how the url_aliases are appearing.
Can anyone give me a good place to try to start figuring this out?
Thanks,
Joe
Comment: Can you tell us exactly how one such spam entry in the `url_alias` table look like? Spam links are usually going to external pages, but a Drupal URL alias will *always* expand to an internal path. Doing what you say the spammers do, don't make sense from the perspective of the spammer.
Answer: Who have access to Administer ➔ Site building ➔ URL aliases depends on how you've set access to the permissions administer url aliases and create url aliases under  Administer ➔ User management ➔ Permissions.  If you've granted access to the Anonymous user role, everybody can do it.  If you've granted access to Authenticated user role, a rogue authenticated user can do it.
First, check out these permissions and make sure they are safe.  Leave them unchecked for all roles. Then, only the super admin (user #1) can create aliases using the GUI.
If these setting are secure, and you still get unwanted url_alias entries created, then some outsider has gained direct access to your database.  That's bad.
Finding the cause of database intrusion is not easy. Possible attack vectors are: A bad module that permits SQL injection, some means outside of Drupal (an inscure phpMyAdmin is the most common cause), or (in particular if you're on shared hosting) a host misconfiguration.
However, without having direct access to your site's and its log for forensics, it is impossible to know how an outsider has gotten into your database (if that is indeed the cause).


How to remove the default DEFINER when executing a CREATE TRIGGER on a table?

Question: I'm rolling out an update for some software, which include running a SQL script to create triggers.
In my .sql file syntax, I did not include any DEFINER clause, as I want my customer's production MySQL user (which they set up by themselves) to be able to execute these triggers when the program is running.
Thing is, tests showed that MySQL automatically creates a DEFINER for the TRIGGER, with 'CURRENT_USER'@'%'.
When you do the sensible thing, and use a (restricted) account for day-to-day data manipulation and another one for big updates (root ?), you end up trying to execute the TRIGGER with one or multiple users who have no permission to do it.
Is there a way to remove this "auto-add definer" feature ?
I tried entering DEFINER = '%'@'%' but this is not accepted.
Comment: Take a look at this one - http://stackoverflow.com/questions/9956839/phpmyadmin-export-view-without-database-name-or-algorithm
Answer: If you are on a *nix platform, the definer can be stripped out by either of the following command line scripts.
cat database.sql | sed -e "s/DEFINER=[^*]*\*/\*/" > database_nodefiner.sql
perl -pe 's/\sDEFINER=`[^`]+`@`[^`]+`//' < oldfile.sql > newfile.sql

In the event that your database.sql is very large, then instead of dumping it first and then removing the definer, remove the definer during the dump.
mysqldump database | sed -e "s/DEFINER=[^*]*\*/\*/" > database_nodefiner.sql


custom node status

Question: In admin/content there is the "status" filter which by default gives us:
any
published
not published
promoted
not promoted
sticky
not sticky

I can see that these map directly to the node table in the database:
mysql> select nid, status, promote, sticky from node;
+-----+--------+---------+--------+
| nid | status | promote | sticky |
+-----+--------+---------+--------+
|   1 |      0 |       0 |      0 |
+-----+--------+---------+--------+

Is there a way to add a 4th boolean column? For example important so in the filter I get important and not important and also in the Publishing options of node/1/edit I also get a checkbox "Important node".
I've seen the http://drupal.org/project/flag project but I want something simpler which will apply this information on the node table. Is it possible?
Comment: "apply this information on the node" definitely sounds like CCK, but the Flag module was created (and is heavily used) for situations just like the one you're describing.
Comment: Use CCK to add new field.
Comment: OK but is it possible to add this as a new column on the `node` table? Would this be a very "hacky" way to solve this?
Answer: Flag would probably be the most 'Drupal' way to do it without writing your own module, which incidentally would be the only way to modify the node table without a significant manual hack.  Although I'm pretty sure you wouldn't want to do that as it might affect the way that other parts of Drupal work.
Comment: @Countzero There's no need to hack core tables, you can update them in a structured way that Drupal will respect. See http://drupal.stackexchange.com/a/30381
Comment: I wouldn't say it's dangerous, just it is a bad habit. Perhaps I'm only a bit too sensitive about data integrity. It's more about good practice (as I intend it) than pure technical reasons.
Comment: +1 for Flag. You definitely DON'T WANT to hack core tables. If you really want to do your own code, creat another table and link it to the node table with a FK and/or code.
Comment: OK, you're right and I learned something. Still, I think it's better to avoid messing with core tables if you can avoid it.
Comment: @Countzero: Why? It just appends a column on installation and drops it on uninstall. How can this be dangerous?
Answer: I think the Custom Publishing Options module is exactly designed for your needs.

This module allows you to create custom publishing options for nodes. It allows you to add to the default options of Publish, Promote to Front Page, and Sticky. It also ingrates with views to allow you add as a field, sort and filter by, your custom options.
It now allows each of the different options to be shown only on selected node types, as well as integration with Rules/Actions, and permissions for each option type.
Comment: Module is good, just option to synch translations of nodes is missing. So it is not so useful if having i18n sites.

custom node status


Understanding Wishart Definition

Question: I'm trying to understand the definition of the wishart distribution. In wiki,
$X_{(i)}{=}(x_i^1,\dots,x_i^p)\sim N_p(0,V).$ What do they mean by this? Each component is drawn from a univariate $N(0,V)$? I was reading it as a multivariate, but then some lines later they write when $p=V=1$ we have a chi-squared distribution.
Any help would be appreciated.
Answer: Yes, those are $p$-dimensional vectors and $V$ is a $p \times p$-dimensional positive definite matrix.
The article's insistence on explaining the Wishart in terms of a correspondence to the chi-squared distribution is sort of strange to me, since the chi-squared is just a special case of the gamma, and the Wishart is more properly a multivariate generalization of the gamma.  You can see the correspondence pretty cleanly when you disregard normalizing constants and use a 'rate' parameterization rather than scale.
Consider $w \sim \text{gamma}(\alpha, \beta)$, which has the following density:
\begin{equation}
f(w) \propto w^{\alpha - 1} e^{-\beta w}
\end{equation}
Compare it to the corresponding density for $\mathbf{W} \sim \text{Wishart}(\alpha, \mathbf{B})$, where $\mathbf{W} \in \mathbb{R}^{p \times p}$, and $\mathbf{B} \in \mathbb{R}^{p \times p}$ is positive-definite:
\begin{equation*}
f(\mathbf{W}) \propto \det(\mathbf{W})^{\alpha - \frac{(p + 1)}{2}} e^{-\text{tr}(\mathbf{BW})}
\end{equation*}
If $p = 1$ then both $\mathbf{W}$ and $\mathbf{B}$ are scalars, so $\det(\mathbf{W}) = \mathbf{W}$ and $\text{tr}(\mathbf{BW}) = \mathbf{BW}$.  The result is
\begin{equation*}
f(\mathbf{W}) \propto \mathbf{W}^{\alpha - 1} e^{-\mathbf{BW}}
\end{equation*}
which is equivalent to the gamma density given previously.
Answer: I think that it is a multivariate, $V$ is the variance-covariance matrix for the multivariate normal distribution ($0$ describes a vector of $0$ I think).
If $p = 1$ then it is not a multivariate case anymore, hence you can get to a univariate chi-squared distribution.

Understanding Wishart Definition


SQL sub-select returns 2 columns - expected 1

Question: sqlite> SELECT *
   ...> FROM Studio
   ...> WHERE third_party_id NOT IN (
   ...> SELECT third_party_id,effeciency_rating
   ...> FROM Staff
   ...> WHERE Staff.third_party_id = Studio.third_party_id AND
   ...> Staff.effeciency_rating < 0.7
   ...> );

with the error message

sub-select returns 2 columns - expected 1

So I know why this happens, my subselct has thirdpartyid and effeciency rating while I only select thirdpartyid from Studio.
So my relation: Stuido employs staff
So now I want to select all studios that didnt employ a staff with effeciency rating under 0.7.
So my question is how do I select my staff based on effeciency rating and give my studio back?
Comment: remove `effeciency_rating` which in `NOT IN` select subquery
Comment: You should always specify the column(s) you want to return rather than using `*`
Comment: This is not a forum but a Q&A site. Please read the [tour](https://stackoverflow.com/tour) to see how it works.
Answer: You would just do:
SELECT st.*
FROM Studio st
WHERE st.third_party_id NOT IN (SELECT s.third_party_id
                                FROM Staff s
                                WHERE s.third_party_id = st.third_party_id AND s.effeciency_rating < 0.7
                               );

Note that I introduced table aliases and qualified all the column names so the query is unambiguous.  However, as written, the query doesn't really make sense.  I suspect that you want NOT EXISTS:
SELECT st.*
FROM Studio st
WHERE NOT EXISTS (SELECT s.third_party_id
                  FROM Staff s
                  WHERE s.third_party_id = st.third_party_id AND s.effeciency_rating < 0.7
                 );

In any case, I recommend NOT EXISTS over NOT IN because it handles NULL values more sensibly.
Answer: Your inner query has 2 columns defined
third_party_id,effeciency_rating
remove the effeciency_rating column from the inner select.
See example and tutorial
Answer: Change:
...> SELECT third_party_id,effeciency_rating

To:
...> SELECT third_party_id

Comment: As a side note, I believe you have misspelled efficiency :)


Order groups in grid layout

Question: When I create a grid view, I can create groups of elements. However I have no control over the order of these groups. I can sort on the grouping variable, but that is not what I want. I want to specify the order, not sort alphabetically. The default is the order the groups were created which suggests reordering the database rows might work as a kludge. Anyone know how to do this?
Comment: It is not clear what you are asking. What are the elements and what are you grouping on?
Answer: The module Draggableviews could be a solution here. It adds a table drag handler and a order field that is saved after you have rearranged the view. The same order field can then be used in another display if you want.

Order groups in grid layout


How to query an optional column value with a fallback in Slick 3.x

Question: I want to write a query in Slick that fetches a column if it is not null, or defaults to the value of another column if it is null. How can I do that without repeating calls to db.run?
Comment: Could you show an example of how would that look like? Does it mean that you have some nullable `first_col` and some non-nullable `second_col`, and during queries on `first_col` all null values should be replaced by the ones from `second_col`?
Comment: Yes that's exactly what I mean, thanks.
Comment: What version of Slick do you use? Is it Slick 2.x or Slick 3.x?
Comment: It's Slick 3.x, thanks.
Answer: Assuming your table definition looks something like this:
import slick.driver.PostgresDriver.api._ // Import your driver here

class EmployeesTable(tag: Tag) extends Table[(Option[Int], Int)](tag, "employees") {
  def firstCol = column[Option[Int]]("first_col") // This column is nullable
  def secondCol = column[Int]("second_col") // This column is non-nullable

  def * = (firstCol, secondCol)
}

Then your query might look like this:
val query = TableQuery[EmployeesTable].map(employee => employee.firstCol.ifNull(employee.secondCol))
val result: Future[Seq[Int]] = db.run(query.result)

This way every null value in first_col will be replaced by a value from second_col. This will be an equivalent of the following SQL query:
select coalesce("first_col", "second_col") from "employees"

Comment: This didn't actually solve my problem but it does answer the original question eloquently so I've accepted it thanks for the help.


Error 406 :Angular Wrong Accept header is sent

Question: Here is my code which is calling a rest endpoint which returns JSON data.
return this.http.patch(URL, httpOptions);

It's a path request with no request body.
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Accept': 'application/json'
})
};

though i have specified Accept header as 'application/json' in request. Text/plain is also sent for Accept.
Accept header from Browser.
Accept: application/json, text/plain, /
Is there anything I'm missing?
Answer: A patch should have a body. The third parameter is the options after the body. You have options as a second parameter in place of body which I suspect is causing the issue:
https://angular.io/api/http/Http#patch
Do you posssibly mean to use http.get?


Add a custom VBO action

Question: I want to add a custom VBO action.
It display in the actions list of the view, it should like a tree, like this:
-Add Role-
RoleA
RoleB
-Remove Role-
RoleA
RoleB
And When I select RoleA(-Remove Role-), check some users, click the submit.
The users checked should be removed RoleA.
How can I code a custom VBO action like this ?
Answer: You can create custom VBO action by implementing hook_action_info() hook. Here are some useful links which can help you achieve what you want:

Views Bulk Operations development guide (Drupal 7)

Programmatically adding and removing roles to users in Drupal
HOWTO assign a user to a role programatically

additionally, Examples module can help you to learn about Actions.

Add a custom VBO action


For a closed, regular space curve of length $\ell$, show that $\int_0^\ell\kappa(s)ds\geq 2\pi$, where $\kappa$ gives curvature

Question: Question:
How can one show that the following proposition is true (Only outline of the proof is needed)?
For every closed and regular space curve $c:[a,b] \to \mathbb R^3$ of total length $l$ one has the inequality
$$\int_0^l \kappa (s) ds \ge 2 \pi,$$
with equality if and only if the curve is a convex, simple plane curve$.^1$
Definitions:
A regular parametrized curve is a continuously differentiable immersion $c: I \to \mathbb R^n$, defined on a real interval $I \subseteq \mathbb R$. This means that $\dot{c}=\frac{dc}{dt}\neq0$ holds everywhere. The length of the curve $c$ ($I=[a,b]$) is $$\int_a^b\left \Vert \frac {dc}{dt} \right \Vert dt \,.$$ The function $\kappa:=\left \Vert c'' \right \Vert$ is called the curvature of $c\,.^2$
A (regular) curve $c:[a,b] \to \mathbb R^n$ is called closed, if there is a (regular) curve $\tilde{c}|_{[a,b]}=c$ and $\tilde{c}(t+b-a)=\tilde{c}(t)$ for all $t \in \mathbb R $, where in particular $c(a)=c(b)$ and $c'(a)=c'(b)$. A closed curve $c$ is said to be simply closed, if $c|_{[a,b]}$ is injective$.^3$
A simply closed plane curve is called convex, if the image set of the boundary is a convex subset $C \subset \mathbb R^2 \, .^4$

[1], [2], [3], [4] Wolfgang Kühnel, "Differential Geometry Curves-Surfaces-Manifolds", Second Edition, American Mathematical Society, 2006.
Comment: "This is a question in global differential geometry, and results in this field are usually proved by tricky methods", not only that this is not an attempt, but also that it is a complete misunderstanding: Indeed most of the global geometry is done using one trick: integration by part (or fundamental theorem of calculus in 1-d situation).
Comment: This is Fenchel's Theorem, and you can find it in most standard textbooks. It's in section 3 of chapter 1 of my own book, which you can download for free by clicking on the link in my profile.
Comment: @TedShifrin Thanks for your comment.
Answer: Given the parametrization c of your curve, let p be any point on the unit sphere. Consider the function $g(t)=p \cdot c(t)$. Since the interval $[a,b]$ is closed and bounded, and $g(t)$ is continuous, then it attains a maximum and minimum value  within the interval. It is possible to compute this value by differentiating $g(t)$. Now
\begin{equation}
g'(t)=p \cdot c'(t)
\end{equation}
Now the points $x \in \mathbb{S}^2$ such that $x \cdot p =0 $ belongs to the great circle of the sphere. The great circle belong to a plane perpendicular to the line connecting the point p to the certer of the sphere. Since $c'$ and the unit tangent vector $T$ are collinear, while p is an arbitrary point on the sphere, we conclude that the tangent indicatrix intersects every great circle on $\mathbb{S}^2$. Since the length of the tangent indicatrix is the total curvature, we have now to prove that the length of the tangent indicatrix is larger of equal to $2 \pi$. To do that you can use the Horn lemma.

Horn lemma
Given a regular curve c on the unit sphere, if c has length less than 2π then c is contained in a hemisphere.
Answer: In 3 dimensions it should be noted that the sign of the curvature of a smooth space curve is not necessarily well-defined.
To experiment with the total curvature of a space curve, it can be useful to imagine a simple closed polygon P in space — a sequence of line segments [a_0,a_1], [a_1,a_2], ..., [a_(n-1),a_0].
Then this polygon P can be approximated arbitrarily well by smooth curves whose curvature is concentrated in a small neighborhood of the vertices of P. In such a way that the integral of the (absolute) curvature is the sum of all the absolute values of the angles between two consecutive sides of the polygon.
Each is the absolute angle that the tangent of such a curve would turn when traversing that angle. I.e., the first angle would be cos^(-1) (D), where D is the dot product of
(a_1-a_0)/||a_1-a_0||
and
(a_2-a_1)/||a_2-a_1||.
Answer: If $c$ is unit speed, then $T(t)=c'(t)$ is a spherical curve in $\mathbb{S}^2$, which is a closed curve. If ${\rm image}\ (T)$ is in some open hemisphere $H$ s.t. $\partial H$ is a great circle which is orthogonal to some $U\in \mathbb{S}^2$, then $c$ goes to the direction $U$ or $-U$. In any case, $c$ can not return to a point $c(0)$.
Hence ${\rm Image} (T)$ can not be in any open hemisphere, which means that ${\rm length}\ (T)\geq 2\pi$ (cf. Spherical lemma).