How can I properly assert an updated type between chained array methods?

Question: I have an interface QueryParam
export default interface QueryParam {
  defaultValue?: boolean | number | string | string[];
  name: string;
  value?: boolean | number | string | string[];
}

When converting QueryParams into a query string I begin by filtering out any that are undefined or where value === defaultValue.
  queryParams
    .filter(({ defaultValue, name, value }) => {
      if (value === undefined) {
        return false;
      }

      if (value === defaultValue) {
        return false;
      }

      return true;
    });

Now I would like to chain a .map() call to convert each QueryParam to a string like so:
  queryParams
    .filter(({ defaultValue, name, value }) => {
      if (value === undefined) {
        return false;
      }

      if (value === defaultValue) {
        return false;
      }

      return true;
    })
    .map(({ name, value }) => {
      ...
    });

However, in the call to .map() TypeScript considers value to still possibly be undefined. I would doubt there is a way to properly narrow the type between chained calls like this (if there is I would love to know what it is). But when I try to assert the updated type myself I get an error.
...
  .map(({ name, value }: { name: string; value: boolean | number | string | string[] }) => {
    return '';
  });

Argument of type '({ name, value }: { name: string; value: boolean | number | string | string[]; }) => string' is not assignable to parameter of type '(value: QueryParam, index: number, array: QueryParam[]) => string'.
  Types of parameters '__0' and 'value' are incompatible.
    Type 'QueryParam' is not assignable to type '{ name: string; value: string | number | boolean | string[]; }'.
      Types of property 'value' are incompatible.
        Type 'string | number | boolean | string[] | undefined' is not assignable to type 'string | number | boolean | string[]'.
          Type 'undefined' is not assignable to type 'string | number | boolean | string[]'.

I would like to find a way to properly assert the new type, or better yet, properly narrow the type without explicit overrides. I also don't really understand the error message fully, so info on that would be helpful as well.
Comment: This isn't an answer to your question, but the `.filter()` call can be simplified to `.filter(({ defaultValue, value }) => value !== undefined && value !== defaultValue)`
Comment: You're probably looking for a type predicate when filtering: https://tsplay.dev/Navv6m
Comment: @pink This does appear to be what I was looking for, thank you!
Answer: You can add a type predicate to the return type of the filter callback:
queryParams
    .filter((param): param is QueryParam & { value: ParamValue } => {
        return param.value !== undefined && param.value !== param.defaultValue;
    })
    .map(({ name, value }) => {
        value.toString(); // okay
    });

Playground


TCPdump parsing sequence number using regular expressions

Question: I am creating a program to read a packet from TCPdump, and read the sequence number. I am using regular expressions, but my code isn't working.
public long getsequencenumber(String Packet){
    Pattern P = Pattern.compile("seq.\\d*");
    Matcher m = P.matcher(Packet);
    if(m.matches()){
        Pattern num = Pattern.compile("\\d*");
        return Long.getLong(num.matcher(m.group()).group());
    }
    return -1;
}

The following prints -1:
System.out.print(getsequencenumber("BlahBdds seq 1910428391283 ldskgj"));

Any suggestions? Thanks!
Answer: When using Matcher#matches, match the complete String otherwise the if statement expression will evaluate to false and the number will not be extracted returning -1 every time. Furthermore, the second Pattern can be eliminated completely by using a capturing group to extract the number from the input String.
public long getSequenceNumber(String packet){
    Matcher m = Pattern.compile(".*seq.(\\d+).*").matcher(packet);
    if (m.matches()) {
        return Long.parseLong(m.group(1));
    }

    return -1;
}

Answer: What you need is matcher.find() and Long.valueOf():
public class Main {
    public static void main(String[] args) {
        System.out.println(getsequencenumber("Bladds seq 1910428391283 ldskgj"));
    }

    public static long getsequencenumber(String Packet){
        Pattern P = Pattern.compile("seq.(\\d*)");
        Matcher m = P.matcher(Packet);
        if(m.find()){
            return Long.valueOf(m.group(1));
        }
        return -1;
    }
}

Output:
1910428391283

See demo here.


JS - Como fazer loop com base nos dados de um array?

Question: Boas, eu tenho o seguinte array JS no meu código:
var Boletins =
{
    id:1, items:
    [
        {
            "#": "1",
            "Data": "19 a 25 de Março de 2021",
            "Região": "região de Trás-Os-Montes e Alto Douro",
            "Niveis": "muito elevados",
            "PoleneArvore": "cipreste, pinheiro",
            "PoleneErva": "urtiga, gramíneas"
        },
    id:2, items:
        [
            {
                "#": "10",
                "Data": "26 de Março a 1 de Abril de 2021",
                "Região": "região de Trás-Os-Montes e Alto Douro",
                "Niveis": "muito elevados",
                "PoleneArvore": "plátano, cipreste, pinheiro, carvalhos"
            }]}

Gostaria de poder criar um Div em HTML para cada um dos id únicos, neste caso vai até ao id:14 mas estou a ter dúvidas e erros na criação do loop.
for (let num in Boletins.id){
    htmlText += '
';
    htmlText += '
 Boletim
';
    htmlText += '
ver mais...
';
    htmlText += '
';
}
$('body').append(htmlText);

Contudo, o meu código dá erro no loop e não me cria os divs para cada um dos id presentes no array. Agradeço a ajuda que me possam disponibilizar.
Answer: Essa estrutura que você mandou deveria ser um array de objetos e não é, se fosse um array de objetos seria algo mais ou menos assim que você deveria fazer:
Sua estrutura:
const Boletins = [
{
    id: 1,
    items: [{
            "#": "1",
            "Data": "19 a 25 de Março de 2021",
            "Região": "região de Trás-Os-Montes e Alto Douro",
            "Niveis": "muito elevados",
            "PoleneArvore": "cipreste, pinheiro",
            "PoleneErva": "urtiga, gramíneas"
 }]}, {
    id:2,
    items: [{
                "#": "10",
                "Data": "26 de Março a 1 de Abril de 2021",
                "Região": "região de Trás-Os-Montes e Alto Douro",
                "Niveis": "muito elevados",
                "PoleneArvore": "plátano, cipreste, pinheiro, carvalhos"
}]}];

Aí você pode fazer um map: Boletins.map(bol => bol.items) ou qualquer tipo laço que percorra esse array (for of, for, forEach, etc...).


This is a matter of numerical sequences, it involves Arithmetic Progression.

Question: Considering that the numerical sequence $a_n, n = 1, 2, 3, ...$ shown in table I is constructed by intercalating the terms of the three sequences presented in table II, judge the following items.
The terms $3n - 1, n = 1, 2, 3, ...$ of the sequence $a_n$ form a geometric progression of ratio 2.
Is it correct to say that $a_{28} < a_{291}$?
Comment: Could you explain me what does this statement means?
The terms 3n - 1, n = 1, 2, 3, ... of the sequence an form a geometric progression of ratio 2.
Comment: What have you done so far?
Comment: @CrystalWolftron I believe it refers to the sequence $a_{3n-1},\ n=1,2,\dots$
Comment: Neither $28$ nor $291$ are of the for $3n-1$ so neither of them are in the exponential sequence which outstrip the other sequences very fast.  $28$ is of the form $3n+1$ is it is geometric sequence which increases fasert than the arithmetic sequence, which is what terms of the form $3n$ are (which $291$ is) so $a_{28=3*9+1}=(9+1)^2=100$ does surpass $a_{291=3*97}= 97$.  But $a_{25}= 81$ *is* less than $a_{288}=96$. However $3*7-1=20$ puts $a_{20}$ in the exponentail sequence $a_{20}=2^7=128$ outstrips the other two.
Answer: Well $28 \equiv 1 \pmod 3$ so $a_{28}$ is in the first sequence and $28=3*9 + 1$ so it is the $9+1=10$ term so $a_{28}=10^2=100$.
And $291\equiv 3\pmod 3$ so $a_{291}$ is in the third sequence.  And $291 = 3*96 + 3$ so it is the $96+1=97$th term.  So  $a_{291}  = 97$.
So, no, $a_{28} > a_{291}$.
Note if $b_k = k^2$ and $c_k = 2^k$ and $d_k = k$ then
$a_{3m + n; n=1,2,3}=\begin{cases}b_{m+1}&n=1\\c_{m+1}&n=2;\\d_{m+1}&n=3\end{cases}$


uniform convergence of a sequence $Q_n = \sqrt{n}(1-\delta^2)^n$

Question: Let $Q_n = \sqrt{n}(1-\delta^2)^n$, where $0 < \delta < 1$, converges to $0$.
This is on p.160 of Rudin's Principle of Mathematical Analysis.

How to show that this is a convergent sequence?
Answer: Clearly $Q_n\geq 0$. It suffices to show that $\forall_{\epsilon>0}\exists_N \forall_{n>N}Q_n<\epsilon$.
\begin{equation}
\sqrt{n}(1-\delta^2)^n < \epsilon \\
n/\epsilon^2 < (1-\delta^2)^{-2n}
\end{equation}
We can find a candidate for $N$ as follows
\begin{equation}
(1-\delta^2)^{-2n}
= e^{-2\log(1-\delta^2)n}
= \sum_{k=0}^\infty \frac{[-2\log(1-\delta^2)]^k}{k!}n^k \\ >
1 + [-2\log(1-\delta^2)]n + \frac{[-2\log(1-\delta^2)]^2}{2}n^2
\end{equation}
Therefore we must just find $N$ such that $\forall_{n>N}$
\begin{equation}
1 + [-2\log(1-\delta^2)]n + \frac{[-2\log(1-\delta^2)]^2}{2}n^2 > n/\epsilon^2. \\
1 + \{[-2\log(1-\delta^2)]-1/\epsilon^2\}n + \frac{[-2\log(1-\delta^2)]^2}{2}n^2 > 0.
\end{equation}
The existence of such $N$ can be shown using properties of the quadratic function.


Vue router taking me to parent route mistakenly

Question: My Vue router normally works just fine, but when I'm on certain routes and want to navigate to one of the parent routes it instead takes me back to the root redirected route instead of the child route I want it to go to
For example, the route in question is account-creation. When I navigate there with $router.push('/account-creation') from most routes it works just fine. However, if I navigate there from any of the account details children routes (like overview), it instead takes me to /account and not /account-creation!
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('MainLayout.vue'),
    children: [
      { path: '/', redirect: '/account' },
      { path: 'account', component: () => import('AccountList.vue') },
      { path: 'account-creation', component: () => import('AccountCreation.vue') },
      {
        path: 'account/:accountId',
        component: () => import('AccountDetailsLayout.vue'),
        children: [
          { path: 'overview', component: () => import('AccountOverview.vue') },
          { path: 'settings', component: () => import('AccountSettings.vue') },
        ],
      }
    ]
  }
];

I have tried every manner of solution I could find online, including using fully qualified paths, re-ordering routes, using names routes, all to no avail
I'm pretty sure it's related to the redirect to /account in the root / path, but can't figure out how to maintain that functionality and fix the behavior
How can I ensure navigating to account-creation from account/{id}/overview correctly navigates to account-creation, instead of the redirect route at /account
Things I've tried

using named paths
using path: object to route to
re-ordering routes
full paths in routes such as /account/:accountId/overview
Comment: Your first childpath is very odd, it's now referring to the path `//` instead of `/`; an empty string path should be used instead as 'default child'. I also like putting a catchall route at the end `({path: '*', component: 404.vue})` for routes that can't be matched to avoid weird behavior or crashes. You could check your routing history in vue devtools (or console.log in a beforeEach) to gain better insight as to how your route is interpreted, and share that please, so we're not 'guessing it has to do with X' :)
Comment: Did you try using `$router.push({ path: 'account-creation' });`, My suspect is that it is trying to look for a path at the same level of the 'account' children (overview, settings), but because it is not there, it redirects to the the root route which redirects to the 'account' route. Another approach is to use named routes: https://router.vuejs.org/guide/essentials/named-routes.html
Comment: thanks @Diego but that doesn't change the behavior at all :-\ using `$router.push({ path: 'account-creation' });` or `/'account-creation'` doesn't work any differently than my original question
Comment: Do you really need nested routes? You have set your routes incorrectly as Excalibaard mentioned
Answer: It seems there are conflicts on your root routes (every path with "/" in front).
You could check the vue-router documentation for nested routes
Vue Nested Routes

const routes: RouteRecordRaw[] = [
    {
        path: '/',
        component: () => import('AccountList.vue'),
        alias: '/account'
    },
    {
        path: '/account-creation',
        component: () => import('AccountCreation.vue')
    },
    {
        path: '/account/:accountId',
        component: () => import('AccountDetailsLayout.vue'),
        children: [
            {
                path: 'overview',
                component: () => import('AccountOverview.vue')
            },
            {
                path: 'settings',
                component: () => import('AccountSettings.vue')
            }

    }
]

Something like this could work, but as you pointed out the redirect on "/" is a code smell since you load different components.
The MainLayout component will never be mounted with this code, instead you will be redirected to AccountList.
EDIT
I edited the original answer based on Excalibaard's comment. You probably should add <router-view> in your MainLayout.vue
P.S. /account path should be accounts as it renders a list
Comment: This could be fixed by putting the mainLayout around the `` component, which is probably the reason the accounts were in child routes in the first place. In the old situation, at path `/account`, the first (applevel) `` would render MainLayout.vue containing another `` which rendered AccountList. Your solution doesn't support this yet.
Answer: If you are passing id to the route correctly, then the issue would be that You have to have a child router-view tag in your AccountDetailsLayout.vue in order to display this route with url account/{id}/overview . Since this is the grandchild of the main layout.Just put the router-view tag in your file like this.

AccountDetailsLayout.vue
-----------------------

<template>
------
 <router-view></router-view>
 -----
</template>

Comment: The OP states "if I navigate there from any of the account details children routes (like `overview`)", so it's implied that the `overview` route is visible, which means `AccountDetailsLayout` already contains ``.


starting point for keyboard spread voicing

Question: What is the best way  to start learning open voicing (spread voicing) " Learning all nine chord types with all 4 formulas in 12 keys " is not for me ,as  being of a senior age, I don't have the inclination to spend so much time learning such a large amount of chords
Comment: Please say more about why you're not able to learn the various chords is all keys.
Comment: It would be helpful also to know what you've learned up to this point. For example, can you play all of the various chord types in close position in all keys?
Comment: What have you learned so far? Are you starting from zero, or do you have some knowledge of chords already?
Answer: A left-field answer from possibly the worst keyboard player on this stack…
After a while you kind of 'forget' what each note is & what job it's doing, you just no longer need to keep all this information consciously in your head, like you're spinning dinner plates on sticks at a carnival. It's a bit like driving - if you had to concentrate all the time about what gear you're in, what direction the steering is pointing, how hard & at exactly what moment you have to press the brake and clutch… you'd have a nervous breakdown & just stop in the middle of the road, shaking.
Until it all falls into place sub-consciously, you could start by using root & 5th in the left, make up the missing 'flavour' notes in the right; eventually progressing to root & any 7th you need, letting you start to squeeze the 5th & any flavour close together, or even at opposite ends of your span; reach out for that 5th to 6th at an octave…
The world is the mollusc of your choice after that.
Comment: In addition to fifths, which fit the hand well, I like roots and 7ths in the left hand, because the 7ths are easy to find, being one half or whole step below the octave.
Answer: Learn all the chords in close position first. Start with the triads - major and minor. Then move on to the 7ths - m7, ▵7, M7, m7♭5, diminished.
Learn them by note names, or if that's impossible, by where the notes are on the keyboard (as in E♭▵ has the black keys to the right of each set of 2 and 3, and the white keys between the 2 blacks and 1st between the 3 blacks). Note names are more useful, as there are so many different combinations of open voicings, I can't think of a better way.
After the 7ths, 9ths are simply one additional note, a 2nd above that 7th (basically).
Learn the note constitution for the more commonly used keys - C, G, F, B♭, E&flat. Work out your own order, from keys you play in most.
Comment: I know most chords maj.min. 7ths dim ,etc and a lot of inversions. Basically I can play most popular music but  only single melody right hand. Instead of spending time learning more left hand chords and inversions, it seems more useful to play spread voicing for better sound


Bernstein von Mises Theorem for Linear Regression

Question: I want to know what conditions are needed and how those conditions can be verified for Bernstein von Mises in linear regression setting with finite dimensions.
I have tried several textbooks but not have been able to find the exact example of linear regression with finite dimensions. I don't have strong statistical background so I have difficulty applying BvM directly to the example myself.
Can anyone recommend some references? Thank you.
Answer: There is a paper in the Annals of Statistics (2011).  You can find the paper "Bernstein von Mises Theorems for Gaussian Regression with increasing number of regressors" by Dominique Bontemps.  The paper deals with the asymptotic normality of the posterior distribution for Gaussian linear regression parameters as the number of regressors increases.


PHP from repository, upgrade to 5.5

Question: On my Debian VPS I have installed PHP 5.4 from debian wheezy repository. Now I would like to upgrade PHP to 5.5, but I would like to still be able to continue upgrades by apt-get. Is it good way to do this?
Answer: DotDeb provides packages for PHP 5.5 and 5.6 on Debian Wheezy.
Comment: Is it secure to take packages from them?

PHP from repository, upgrade to 5.5


Solve $\frac {2 \tan x}{1-\tan^2x} = \sin^22x$

Question: How would I solve this trigonometric equation?
$$\frac {2 \tan x}{1-\tan^2x} = \sin^22x$$
I got to this stage: $$\frac{\sin2x}{\cos2x} = \sin^22x$$
Is it a dead end?
Answer: Using $\tan (x+y)=\frac{\tan x+\tan y}{1-\tan x\tan y}$,
$$\frac {2 \tan x}{1-\tan^2x}=\tan 2x=\sin 2x\sec 2x$$
$$\sin 2x\sec 2x=\sin^22x$$
$$\sin 2x\big(\frac{1}{\cos 2x}-\sin 2x\big)=0$$
So either $\sin2x=0$ or $\frac{1}{\cos 2x}=\sin 2x$
You can solve first one easily.
For second one,
$$\sin 2x\cos 2x=1$$
$$\frac{1}{2}\sin 4x=1$$
$$\sin 4x=2$$
which is not possible because $-1\le \sin\theta\le 1$
So only the solutions of first equation satisfy the given equation.
Comment: $sec(x)=\frac{1}{cos(x)}$
Comment: Can you please explain me what is $\sec$ because I never learned it
Comment: Is there any way in the world to do this equation without $\sec$?
Comment: Please see the edited answer if you are facing difficulties
Comment: Why $\frac {2 \tan x}{1-\tan^2x}=\tan 2x$ is it identity?
Comment: You should know that $\tan (x+y)=\frac{\tan x+\tan y}{1-\tan x\tan y}$. Put x=y to get the relation.
Comment: Thanks, is good to know new things :)
Comment: Does this answer your question?
Comment: Thank you very much, solved it now :)
Answer: Try to rewrite it in the following way. $$0=\sin^2(2x)-\frac{\sin(2x)}{\cos(2x)}$$
$$0 = \sin(2x) \cdot \left[\sin(2x)-\frac{1}{\cos(2x)}\right]$$
$$0= \sin(2x) \cdot \frac{\sin(2x)\cdot \cos(2x)-1}{\cos(2x)}$$
Then use $\sin(2x) \cdot \cos(2x) = \frac{\sin(4x)}{2}$.
Comment: You can produce $\sin x$, $\cos x$, $\tan x$, $\csc x$, $\sec x$, $\cot x$ by typing \sin x, \cos x, \tan x, \csc x, \sec x, \cot x, respectively, in math mode.
Comment: Thank you, i always forget that :). Not used to latex notation that much :D.


Accessing min and max value within JSON array in JavaScript/HTML

Question: I have the following code that gets data from a database and plots a graph using HTML and the FusionCharts library. I'm just having some trouble with the graph formatting. I want the yAxisMin to be 10 values below the minimum value in the data array and the yAxisMax value to be 10 values above.
function createJSON(name, data){
    return(
        {
            "chart": {
                "caption": String(name),
                "subCaption": "15-Day Prices",
                "xAxisName": "Day",
                "yAxisName": "Price (USD)",
                "anchorRadius": "1",
                "showValues": "0",
                "borderThickness": "3",
                "yAxisMinValue": data.value.min() - 10,
                "yAxisMaxValue": data.value.max() + 10,
                "theme": "fint"
            },
            "data": data,
        }
    );
}

//I'm including this for context. This is the function that returns the data array
var getHistory = function(req,res,next){

    var data = [];
    History.findOne({"Symbol": String(req.params.sym)}, function(err, foundHistory){
        if(foundHistory){
            (foundHistory.Historical).forEach(function(day){
                data.push({
                    "label": day.Date,
                    "value": day.Close
                });
            });
            res.json(createJSON(foundHistory.Name, data));
            next();
        }
        else{
            next();
        }
    });
};

module.exports = getHistory;

Everything else works fine. I just need help with the two lines of code:
"yAxisMinValue": data.value.min() - 10,
"yAxisMaxValue": data.value.max() + 10,

How would I do this? This was my attempt but it does not compile.
Answer: How about this? Since your code sample is incomplete, I cannot test it myself.
function createJSON(name, data){
  var min = Number.MAX_SAFE_INTEGER;
  var max = Number.MIN_SAFE_INTEGER;
  for(var i = 0; i < data.length; i++) {
    if(data[i].value < min) min = data[i].value;
    if(data[i].value > max) max = data[i].value;
  }
  ...
      "yAxisMinValue": min - 10,
      "yAxisMaxValue": max + 10,
  ...

Comment: Still gives me an error but thank you for the help! I'll try to find the error
Comment: What is the desired output and actual output? 'max does not' says nothing. I updated the code a few times. Please check again.
Comment: Min value is 110 and the graph min-y-value is correctly adjusting to 100. The max value is 150 but the graph just displays 150 instead of 160.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/139661/discussion-between-sangbok-lee-and-ss1111).
Answer: Try something like that:
  "yAxisMinValue": getMinValue(data) - 10,
    "yAxisMaxValue": getMaxValue(data) + 10,

 function getMinValue(data)
     {
       var min = Number.MAX_VALUE;
        for (var key in data)
         {
           if(data[key].value < min)
            {
               min = data[key].value;
            }
         }
        return min;
     }

 function getMaxValue(data)
     {
       var max = Number.MIN_VALUE;
        for (var key in data)
         {
           if(data[key].value > max)
            {
               max = data[key].value;
            }
         }
        return max;
     }

Comment: Max has the same logic.
Comment: Idk what type is day.Close. If it isnt numeric, you have to check min in other way.
Comment: day.Close is a floating point number. I tried running this function and it returns `-9999 + or - 10`.
Comment: Obviously, no max calculation here.
Comment: I tried this out and it works! Only thing is, the max value + 10 is returning just the max value and I can't seem to find the error
Comment: This way, to get min and max takes two loops, which can be done in just one loop.
Comment: You can have two different datas.
Answer: For 1-Dimensional Array of Numbers:
JavaScript's Math.max and Math.min will find the maximum or minimum of their arguments respectively, so, using an apply call, we can apply the array of numbers to these functions.
var values = [ 1, 2, 3, 4, 5 ]
Math.max.apply(null, values) // 5
Math.min.apply(null, values) // 1

For Anything Else:
If you want the index of the maximum or are comparing non-numeric values, a custom iterator is needed.
function getMax (values)
  var maxIndex = -1
  var max = Number.MIN_VALUE // use Number.MAX_VALUE for min

  for (var i = 0; i < values.length; i++) {
    if (value[i] > max) { // do your "greater than" comparison here
      maxIndex = i
      max = value[i]
    }
  }

  // return what it is you need, max or maxIndex
  return max
end

Comment: Does it matter that my array is 2 dimensional? I don't think this would work in that case
Comment: In that case, no. You would have to iterate over the array in question, storing the index (or the value itself) of the max/min. I will edit the answer to have this option as well.
Comment: This way too, to get min and max takes two loops, which can be done in just one loop.


lighttpd - redirect everything to https

Question: I have tried to use the example from this wiki page -
$HTTP["scheme"] == "http" {
    # capture vhost name with regex conditiona -> %0 in redirect pattern
    # must be the most inner block to the redirect rule
    $HTTP["host"] =~ ".*" {
        url.redirect = (".*" => "https://%0$0")
    }
}

But when I enter this url -
http://www.domain.co.il/index.php?shop=amazon

I got redirected to
https://index.php/index.php?shop=amazon

What is the problem?
Comment: The example on the wiki page is fine; the question is how you tried to use it - maybe show us a larger part of your config.
Answer: Everything works fine after removing this -
url.rewrite-once = ( "^/min/([a-z]=.*)" => "/min/index.php?$1",
        "^(.*)\.(jpg|gif|woff|tff|png|js|css|html|htm|txt)(.*)$" => "$0",
        "^/question2answer/(.+)$" => "/question2answer/index.php?qa-rewrite=$1",
       "^/$" => "/index.php"
     )

Comment: But is there a way to do so with addition redirecting to "www." if there is no "www." in host? May be I need to ask a new question?
Answer: This might not be the most elegant way, but it worked for us. Explicitly catches a regex match. (Note: maybe it should be "https://%1$1")
$SERVER["socket"] == ":80" {
    $HTTP["host"] =~ "^(.*)$" {
        url.redirect = ( "^/(.*)" => "https://%1/$1" )
    }
}

Comment: .* matches by default the complete string (greedy match), and so %0 and $0 are perfectly fine. $SERVER also adds a socket bind, which usually isn't wanted - the scheme matching is the right way.

lighttpd - redirect everything to https


Why is public properties of Class visible but not it's public methods in MVVM?

Question: I have a WPF window in a project in the same solution as a WCF project. In the WCF project I have a public Class with public properties and public methods.
public class TemporaryExam
{
    public Exam Exam { get; set; }
    public List<Question> Questions { get; set; }
    public List<PossibleAnswer> PossibleAnswers { get; set; }

    public void AddQuestion(Question question)
    {
        Questions.Add(question);
    }

    public void AddPossibleAnswer(PossibleAnswer possibleAnswer)
    {
        PossibleAnswers.Add(possibleAnswer);
    }
}

In the window codebehind I can assign values to the properties but get an error saying that TemporaryExam does not contain definition for AddQuestion(question).
TemporaryExam temporaryExam = new TemporaryExam();
Exam exam = new Exam { Id = Guid.NewGuid(), Title = "Exam3" };
Question question = new Question
{
    Id = Guid.NewGuid(),
    ExamQuestion = "Vad heter du?",
    ExamId_Id = exam.Id
};
PossibleAnswer possibleAnswer = new PossibleAnswer
{
    Id = Guid.NewGuid(),
    PossibleAnswer1 = "Bamse",
    QuestionId_Id = question.Id
};

temporaryExam.AddQuestion(question);

How come the properties are visible but not the methods?
Edit:
This generates no erros:
temporaryExam.Exam = exam;

Comment: Sounds like the WCF project isn't up-to-date. Make sure it's building properly and the reference to it in the WPF project is referencing the actual build and not a stale copy.
Comment: @Clemens tried this temporaryExam.Exam = exam; and it works but the methods are still not accessible :/
Comment: @Cameron I published the WCF project again and updated the service reference in the WPF project but still gets the same error. The TemporaryExam Class is a seperate file in the WCF project does that matter?
Comment: If you're writing business logic code (e.g., creating a TemporaryExam) in your codebehind you're doing something wrong.
Answer: Try removinig typed arguments (Question) from the method as you may need to define the custom types to expose from WCF projects.


Como substituir uma determinada string dentro de outra string em JavaScript?

Question: Como posso substituir somente uma determinada parte de uma string? Exemplo:
var linha_nova = "EU TENHO UM CACHORRO";

Quero substituir somente a palavra "UM" por outra. Como devo proceder?
Também preciso fazer a substituição pela posição conhecida da palavra a ser substituída. Por exemplo , sei que o "UM" está na décima posição.
Answer: A forma simples é através da função replace() de tipos string. Documentação em inglês.

var linha_nova = "EU TENHO UM CACHORRO";
var linha = linha_nova.replace("UM", "MEDO DE");
console.log(linha);

Veja funcionando no CodePen. Também coloquei no GitHub para referência futura.
Desta forma a variável linha_nova permanecerá inalterada e a variável linha conterá "EU TENHO MEDO DE CACHORRO". Se precisar que linha_nova seja alterada, você deve guardar o resultado nela e não em linha.
Você precisa ter uma certa noção de qual é o conteúdo senão pode ter resultados indesejados. Pode substituir apenas uma parte de uma palavra, por exemplo: "HUMBERTO" pode virar "HMEDO DEBERTO". Pode ter problemas também se tiver a substring aparecendo várias vezes.
Mas se quiser resolver situações mais complexas isto pode não ser o mais adequado. A função replace permite sintaxe de expressões regulares conforme demostrado na resposta do mgigsonbr.
Se você sabe a posição e o tamanho da parte da string que deseja trocar, então use:
var linha = linha_nova.substr(0,9) + "MEDO DE" + linha_nova.substr(11, linha_nova.length - 11);

Answer: Substituindo posições específicas
Para substituir apenas uma posição ou intervalo fixo, basta usar substring. Primeiro pegue o pedaço do início até a posição inicial que quer substituir, depois o pedaço que começa no final do trecho até o final da string:
var linha_nova = "EU TENHO UM CACHORRO";
                //0123456789abcdef
var resultado = linha_nova.substring(0,9) +
                "FOO" +
                linha_nova.substring(11, linha_nova.length);

A função substr também serve, mas ela recebe não o início e o final desejado, mas sim o início e o número de caracteres desejado.
Substituindo palavras específicas
A função replace permite substituir uma substring por outra. Ela também permite que você passe uma expressão regular, e para cada casamento (match) da mesma, substituí-la por outra string ou pelo resultado de uma função. Se quiser substituir somente a primeira ocorrência, use a chamada com string; se quiser todas, use uma regex com a flag g:
var str = "um cachorro, um gato, um rato";

var uma = str.replace("um", "o"); // o cachorro, um gato, um rato
var alt = str.replace(/um/, "o"); // o cachorro, um gato, um rato

var todas = str.replace(/um/g, "o"); // o cachorro, o gato, o rato

var captura = str.replace(/(um)/g, "xx$1xx"); // xxumxx cachorro, xxumxx gato, xxumxx rato

var funcao = str.replace(/\w+/g, function(match) {
    return Math.random() < 0.5 ? match : match.toUpperCase();
}); // UM cachorro, UM GATO, um rato

Note que essa chamada cria uma nova string. Em JavaScript as strings são imutáveis, de modo que não há nenhum meio de se alterar uma string pré-existente sem criar uma nova.
Exemplos no jsFiddle.
Comment: @user7605 Sim, creio que é a melhor maneira. Tipo `str.substring(0,10) + "x" + str.substring(11,str.length)`. Note apenas que `substring` pede o início e o fim, enquanto `substr` pede o início e o número de caracteres.
Comment: se por exemplo eu quiser substituir por posição ao invés da palavra como seria ? Exemplo, quero substituir uma letra na posição 38. Usaria o substr mesmo ?
Answer: Você também poderia estar fazendo:
var frase = "Eu tenho um cachorro(s)";
var novaFrase = frase.replace(frase.substring(9, 11), "dois");

alert(novaFrase); // Eu tenho dois cachorro(s)

Ou utilizando expressões regulares:
var frase = "Eu tenho um cachorro(s)";
var novaFrase = frase.replace(/(.{9}).{2}/,"$1dois")

alert(novaFrase); // Eu tenho dois cachorro(s)

Answer: var linha_nova = "EU TENHO UM CACHORRO";
alert(linha_nova.replace("UM", "CARA DE"));

Comment: Sou o autor dessa resposta e duas pessoas deram downvote. Fico curioso por que fizeram isso.


Separate numeric characters within a column in R

Question: in r I have a column that shows age ranges like this:
Age <- c(1524, 2534, 3544, 4554, 5564, 65)

So, as in ages from 15 to 24, 15-34 ... and older than 65 years
I want the ages in my column to be separated by a "-". And the last age to say 65<". And look like:
Age <- c(15-24, 25-34, 35-44, 45-54, 55-64, 65<)

Thanks
Answer: We can use sub to capture the first two characters ((..)) from the start (^) followed by the next two characters, insert the - between the backreferences of the captured group in replacement.  Then use ifelse to paste the element that doesn't have a - with <
Age <- sub("^(..)(..)$", "\\1-\\2", Age)
ifelse(grepl("-", Age), Age, paste0(Age, "<"))
#[1] "15-24" "25-34" "35-44" "45-54" "55-64" "65<"

Or may do this in a single step with substr and sub

Extract the first two characters - substr(Age, 1, 2)
Extract the next two - substr(Age, 3, 4)
Then, paste them together with a - in between
For those elements having only two characters, the second substr call returns "", thus we have - at the end of the string
Replace the - at the end ($ - regex metacharacter for end of string) with <

sub("-$", "<", paste0(substr(Age, 1, 2), "-", substr(Age, 3, 4)))
[1] "15-24" "25-34" "35-44" "45-54" "55-64" "65<"

Answer: Another way of doing this is:

Select the first two numbers of all elements in Age except the last one (65).

Paste the first two with '-' and the last two.

Append '65<' at the end.

library(tidyverse)
Age <- c(1524, 2534, 3544, 4554, 5564, 65)

str_sub(Age[-length(Age)], 1, 2) %>%
  str_c('-', str_sub(Age[-length(Age)], -2, -1)) %>%
  c(str_c(Age[length(Age)], '<'))
#> [1] "15-24" "25-34" "35-44" "45-54" "55-64" "65<"

Created on 2021-07-04 by the reprex package (v2.0.0)


Weak equivalences in $\text{Top}$

Question: Weak equivalences in $\text{Top}$ are the ones for which is
$$\pi_n(f,x)$$ a bijection or more strictly group isomorphism ?
See the definition $2.4.3.$ in the snippet below.
I understand that
$\pi_0(X,x)$ is a set but $\pi_n(X,x)$ for $n\geq 1$ is a group.
Answer: Well, for $n>0$, $\pi_n(f,x)$ is always a homomorphism, so it is an isomorphism iff it is a bijection.  For $n=0$, $\pi_0(X,x)$ has only the structure of a pointed set, not a group, so to say that $\pi_0(f,x)$ is an isomorphism would just be that it is an isomorphism of pointed sets, which just means it is a bijection which preserves the basepoint.  So, if you like, you can just interpret "isomorphism" to always mean "bijection" in this definition.
Actually, though, the definition is wrong: when $X$ is empty, the definition would say that any map $f:X\to Y$ is a weak equivalence vacuously (since there are no choices of $x\in X$).  The correct definition is:

Let $f:X\to Y$ be a map in $\mathbf{Top}$.  Then $f$ is a weak equivalence if:

$\pi_0(f):\pi_0(X)\to\pi_0(Y)$ is a bijection, and

$\pi_n(f,x):\pi_n(X,x)\to\pi_n(Y,f(x))$ is an isomorphism for all $x\in X$ and $n\geq 1.$

Here $\pi_0(X)$ denotes the set of path-components of $X$ without any choice of basepoint, so the first condition is non-vacuous even if $X$ is empty.
Comment: Why there is some $x$ in $X$ in your second $\bullet$ if $X=\emptyset$? Why is it also non-vacuous ?
Comment: The second condition is vacuous if $X$ is empty.  But when $X$ is empty, the first condition can only hold if $Y$ is also empty.
Comment: I do not follow where is the difference between the vacuousness of the first and of the second $\bullet$.
Comment: The second condition is stated "for all $x\in X$" and the first one is not.
Comment: So why it is necessary for the first $\bullet$ to omit for all $x\in X$ and in the second $\bullet$ not.
Comment: Also in the first $\bullet$ we do not know that $\pi_0(f)$ preserves the basepoint if $X\neq \emptyset$.
Comment: The whole point is that the first condition does not involve any basepoint, since we are taking $\pi_0(X)$ without any basepoint.

Weak equivalences in $\text{Top}$


Using delegate gives EXC_BAD_ACCESS (code=1, address=0x2774….)

Question: I am totally new to iOS programming and I am trying to make a word game in which an alphabet tile is dragged and dropped to a target. I have adopted the code from www.raywenderlich.com/33806/how-to-make-a-letterword-game-with-uikit-part-2 .The problem is when I use the GameLogic class as a delegate to to match whether the alphabet dragged matches the target or not, it gives me EXC_BAD_ACCESS (code=1, address=0x277… …). In GameLogic.m, even though the _targets and _tiles arrays are initialized within the dealRandomScrabble method, the error occurs when the protocol: (void)tileView:(TileView *)tileView didDragToPoint:(CGPoint)pt is called. In this method, tv and _targets surprisingly refer to null! Could anyone please look into my code and tell me what I have missed? The link to the code in my GoogleDrive is :
https://drive.google.com/file/d/0BzWvv9PVuvDKLWtJcldRbGVRNUk/edit?usp=sharing
Thank you in advance.
Comment: The code runs fine in the tutorial below, but when I use it, it doesn't. Help really needed on this!

www.raywenderlich.com/33806/how-to-make-a-letterword-game-with-uikit-part-2
Answer: Try replacing
<code>_targets = [NSMutableArray arrayWithCapacity:scrab2Len];
</code>
with
<code>_targets = [NSMutableArray arrayWithCapacity:scrab2Len] retain];
</code>
And make sure that u release this object once you are done
Comment: Wow Shanti, thanks for the prompt reply. Now _targets holds the alphabets, but the targetView holds no letter and gives bad memory access again in the if statement that follows:
// Check if target was found
    if (targetView != nil) {

        if ([targetView.letter isEqualToString:tileView.letter]){

            NSLog(@"Success! You should place the tile here!");

            NSLog(@"Check if the player has completed the phrase");
        } else{
            NSLog(@"Failure. Let the player know this tile doesn't match.");
        }
    }
Comment: Could you kindly run the project I shared to get a better understanding of my problem. I truly appreciate your help!
Answer: in this method
-(void)dealRandomScrabble
// Initialize target list
instead of this line
<code> _targets = [NSMutableArray arrayWithCapacity:scrab2Len];
</code>
use below line.
<code>_targets =[[NSMutableArray alloc] initWithCapacity:scrab2Len];
</code>
by doing so, _targets doesnt point to null in -(void)tileView:(TileView *)tileView didDragToPoint:(CGPoint)pt method(protocol method)
Comment: ps: i'm using ARC. high time u did it too
Comment: I tried this way too. The  problem is that letter in _targets should hold an alphabet as a string, but does not. Also, targetView should hold all the letters in the target, but does not. :(
Comment: using arc should hav been a decision made before u begin your project. Just a caution: u may face unseen challenges if you convert code to arc midway. u should read more about arc and mrc


Is it a truly random sample?

Question: Any hints on how to solve this problem?

A sample  of 400 items is taken from a normal population whose mean
  as well as variance is 4. If the sample mean is 4.5, can the sample
  be regarded as a truly random sample?
Comment: Please improve the title of your question, so it will be meaningful to people who browse lists of questions here.
Comment: @Floris (1) The population variance is known, not estimated, so a t-test would be unsuitable even if this was a testing situation. Those are for when the standard deviation is estimated. $\quad$ (2) In any case, the question is *not* answered by hypothesis tests of any kind. $\quad$ Your first comment is not helpful.
Comment: Hint - use the t test. You know the mean and standard deviation, as well as the number of degrees of freedom. Compute the t statistic and decide if the p value is low enough to reject the null hypothesis.
Comment: Boral, that is a reasonable approach. Note that it would not use a Student t-test, though, because you do not know the sample variance. It would involve the (simpler) z-test, for which you use the known population variance. Mathematically that is equivalent to the test @Harvey Motulsky suggested in his answer.  (There is no practical difference between the t-test and the z-test with this sample of 400 items. We should nevertheless care about the distinction because it is more important to understand the logic of the procedures than to get some kind of "right" answer.)
Comment: The Diehard tests are irrelevant to these particular data. However, one of the Diehard tests evaluates whether the mean of a sequence deviates from its expectation by more than would be explained by random variation. That's what you are doing here.  Thus, your test--although simple and by no means an entire battery of tests--could be viewed from this perspective as being a partial test of randomness. This helps us interpret @Glen_b's assertion (2), which I believe was intended to mean that no hypothesis tests can demonstrate randomness--but some can demonstrate *lack* of randomness.
Comment: Is this for a class assignment? If so, please add the [tag:self-study] tag & read its wiki.
Comment: Further hint - the standard error of the mean of a sample is $\sigma / \sqrt{N}$. So your sample mean is 5 standard errors from the population mean. How likely is that for a random sample?
Comment: @Glen_b I was thinking whether this can be proceeded by testing. Suppose we test H0 : mu = 4 vs. H1 : mu not= 4. Now we find the confidence interval for mu.  If the C.I. does not contain 4 then I may conclude that the sample is not random.
But will this conclusion right ?
Comment: @boral The question you asked in your post is "is it a truly random sample?". The question addressed by hypothesis tests or CIs in your comment is somewhat different - it answers a question about consistency of the sample with the distribution you'd get with random sampling from the population distribution. Failure to reject that doesn't imply 'truly random sampling' - you can have nonrandom sampling that is nevertheless not rejected (e.g. some very systematic sampling might be highly representative - by design). But Harvey pretty much covers that issue (what tests/CIs tell us) in his answer.
Comment: @Glen_b You are right. Failure to reject does not imply truely random sample. I think this question cannot be answered with the help of statistics, as Harvey has already said.

But I wonder is there any method or way not necessarily statistical which answers this type of questions ?
Comment: Actually, it is standard practice to test pseudorandom number generators (or any purported random number generator) by applying a large battery of hypothesis tests. See Knuth's *The Art of Computer Programming* Section 3.3 or look at the [Diehard tests](http://en.wikipedia.org/wiki/Diehard_tests), for instance. In these applications, although it is usually known exactly how the sample is created, hypothesis tests are used to detect deviations from various behaviors expected of random samples. That seems like a useful framework in which to view the present question.
Comment: @whuber But in order to apply these battery of tests I need to know the sample values isn't it ? But I know only sample mean and not the sample values. So I think I cannot apply Diehard tests. Am I correct ?
Comment: @whuber that was indeed the intent
Comment: @whuber Can you please say in details how to do the test you are speaking of. I don't know much about Diehard tests.
Comment: Sikkim Manipal Assignment Question?? I have the Answer.
Answer: Statistical calculations can answer this question:  IF you collected many random samples, in what fraction would the mean be as far (or further) from the population mean as you observed? If the answer is tiny, you might suspect that the sample was not random.
But statistical calculations cannot answer the question: Was this a random sample? The only way to know that is to find out how the sampling was done.
Answer: A Monte Carlo solution (in Python), along the lines of @Harvey's response:
<code>import numpy as np
# 10,0000 random samples from you population
samples = [np.random.normal(loc=4, scale=4, size=400) for i in range(100000)]
# Mean of each sample
means = np.array([np.mean(sample) for sample in samples])
# How many of these means are greater than 4.5?
tested = means > 4.5
np.mean(tested)

Out[11]: 0.0064000000000000003
</code>
So out of 10,0000 samples, only 0.64%, or 640, had a mean greater than 4.5. Therefore, the probability of getting such a high mean from a random sample is $p = .0064$.

Caveat: I could be wrong. Discussion welcome.
Answer: Assuming that the sample variance is also $4$ (since I believe we need to the sample variance to solve this, please correct me if I'm wrong), the standard error of the sample mean would be $2/\sqrt{400}=0.1$. Since the population mean is $4$, using a t-test we get $t=(4.5-4)/0.1=5$, which is well within standard ranges of rejection values of the null hypothesis (that the sample mean is equal to the population mean).

Is it a truly random sample?


How can I show a field on click?

Question: In node.html.twig, I want to show a field when I click on it, as what the Field Value Loader (Show field on click) module does, but this module doesn't have releases for Drupal 8.
How can I do this?
Comment: after you click show, do you need to be able to hide?
Comment: For example my number is 1xxxxxx and I want that when I click on it show 1234567 .
Comment: yes, but after that do you want the ability to hide? or you don't need that?
Comment: No I don't need that .
Answer: node.html.twig

{{ content.field_something.value }}

Show

custom.js
(function ($) {

$('.field-something').hide();
$('.show').show();

$('.show').click(function(){
    $('.field-something').fadeIn(2000);
    $('.show').hide();
});

}(jQuery));

Your Theme's style.css
.field-something { float: left; padding-right: 5px; }
.show { color: blue; cursor: pointer; display: none; }

Example DEMO
Comment: In my source page number was show . How can I hide number in my page source until "show" not click ?
Comment: by default jQuery is disabled in D8, did you enable it?
Comment: In page my number is hide and when I click on "show" my number show . But when I watch my source page my nubmer is show . For more security I want hide on source page too .
Comment: Then you would have to load it using AJAX
Comment: How ? Can you help me ?
Comment: @SiMoNe just wondering, is that number a credit card number? or ???
Comment: That's users phone number . I want that robot spammers can't access that .
Comment: ah.. ok.. good idea, but that's a totally different question, I suggest you make a new one "How to load a user field value using AJAX"
Comment: http://drupal.stackexchange.com/questions/202653/how-to-load-a-user-field-value-using-ajax
Answer: var notificationList = false;
$('.show').click(function(){
    if(notificationList) {
       notificationList = false;
       $('.field-something').hide();
    } else {
       notificationList = true;
       $('.field-something').show();
    }
});

Comment: Can you explain a little your code?
Comment: Yes, By default, my window is not opened, so when I click on dropdown my variable notificationList is still false, accordingly the condition does not work and goes to else, after that my variable notificationList becomes true, and already the next click the condition is fulfilled and notificationList is set false , and the dropdown is hidden. Accordingly when I click my dropdown is hiding and showing.

How can I show a field on click?


How can I create a mapping for two types in ElasticSearch?

Question: I would like to index user IDs and tag IDs.
I send a PUT request to https://ip//elasticsearch/myIndex
{
  "mappings" : {
    "users" : {
      "properties" : {
        "id" : {"type": "keyword" }
      }
    },
    "tags" : {
      "properties" : {
        "id" : {"type": "keyword" }
      }
    }
  }
}

However, I receive this response:
{
    "error": {
        "root_cause": [
            {
                "type": "illegal_argument_exception",
                "reason": "Rejecting mapping update to [myIndex] as the final mapping would have more than 1 type: [users, tags]"
            }
        ],
        "type": "illegal_argument_exception",
        "reason": "Rejecting mapping update to [myIndex] as the final mapping would have more than 1 type: [users, tags]"
    },
    "status": 400
}

How can I solve this error?
Answer: From Elastic 6.x you cannot have more than 1 mapping type. Use a single mapping type. Instead use custom type field. See this link and also this link.
Answer: As stated by @ben5556, you can only have one type per index in elasticsearch 6+. However, you can mimic multiple types per index by including your own "type" field.

{
  "mappings" : {
    "ids" : {
      "properties" : {
        "id" : {"type": "keyword" }
        "type": {"type": "keyword" }
      }
    }
  }
}

Then when you index a document, you include the "type":

{
    "type": "user",
    "id": "12345"
}

This will allow you to filter by type when querying the index (using a termsQuery). Which is all elasticsearch was really doing behind the scenes for you anyways back when it supported multiple types.


Difference between Jstack and gcore when generating Core Dumps?

Question: We all know that Core Dumps are an essential diagnostic tools for analysing various processes in Unix . I know both jstack  and gcore  are both used for generating Javacore files or Core Dumps but I have a doubt that Gcore is mainly used for Processes and Jstack is used for threads .
As from an Operating System perspective Process and Threads though interrelated (Process comprises of Threads only) they are relatively different from each other w.r.t memory/speed/execution . So is that gcore  will diagnose the process and jstack will analyse the threads in that process ???
Answer: GCore act at OS level and you got a dump of native code that is currently running. From a java point of view, it is not really understandable.
JStack get you the stack trace at VM level (the java stack) of all thread your application have. You can find from that what is the real java code executed at a point.
Clearly, GCore is almost never used (too low level, native code...). Only really strange issue with native library or stuff like that will perhaps need this kind of tool.
There is also jmap that can generate a hprof file which is the heap data from you VM. A tool like 'Memory Analyser Tool' can open the hprof, and you can drill down on what was going on (on memory side).
If your VM crash because of a OutOfMemory, you can also set parameter to get the hprof when the event occurs. It helps to understand why (too many users, A DB query that fetch too much data...)
Last thing is the fact that you can add a debug option when your start your VM, so that you can connect to it, and put debug on running process. It can help if you have some strange issue that you are not able to reproduce in your local environment.
Comment: I assume from the above that gcore is useful for Core Dump and Jstack is for Thread Dump . A difference between the two can be found in the link .  https://middlewarebyashok.wordpress.com/2016/03/19/heap-dump-and-threaddump-and-core-dump-explanations/


Android finish parent Activity

Question: I have 3 different activities in a TabGroupActivity. Let's say A - Parent, B - Child 1, C - Child 2.
A --- starts --> B
B --- starts --> C
and I have an alert dialog in C which shows some message. I want to go back to activity A when I press Ok button on dialog.
But the problem is that I can open activity C from other activities too and I want to go back to their parent activities too. So I need to make something which will work no matter which activity opens C. I've tries with this one but didn't work :
Intent intent = new Intent(Synchronization.this,Synchronization.this.getParent().getClass());

but it didn't help me. Any suggestions?
Answer: You just have to make use of two Activity methods viz. startActivityForResult() and onActivityResult()
Example : http://www.vogella.de/articles/AndroidIntent/article.html#explicitintents
Here goes the logic :
In ActivityB
Start ActivityC by using startActivityForResult(activityCIntent,INT_CODE);
In ActivityC
Now check if Dialog's OK Button is pressed, if yes then set the result using setResult(RESULT_OK,intent); and then call finish();
Then control will be redirected to ActivityB's onActivityResult() method.
Now inside onActivityMethod() check whether result_code==RESULT_OK and requestCode = INT_CODE. If yes then simply call finish();
Comment: `startActivityForResult()` is used to start any other Explicit Intent and receive the results from the `Intent` that it started. `onActivityResult()` is responsible for getting the data from the started Explicit `Intent`.
Comment: what is the difference between both the methods?
Answer: In the Activity B start the C Activity as startActivityForResult() so when you finish the C activity it will back to the B with result. As the result you may pass flag with the intent object.
Now when you finish the C activity with ok button then set the result as RESULT_OK into the setResult() if you need to pass the data back to the B activity you may set the data into the Intent add this intent with the setResult() method and then finish the C Activity.
Now in B check the requestcode is from the C then finish this Activity. As you start this C Activity you can also start the B Activity for the A Activity.
And you need to override onActivityResult() in B activity and if you start the B Activity as for result then also you need to define also into A Activity

Android finish parent Activity


Non-trivial examples of Borel measures on $\mathbb{R}$

Question: Let $\mathcal {B}$ be the $\sigma$-algebra generated by the set of open subsets of $\mathbb{R}$. A Borel measure $\nu$ on $\mathbb{R}$ is a measure on $\mathcal {B}$ such that $\nu(K) \lt \infty$ for every compact subset $K$.
The only Borel measures I know are essentially as follows.
1) Let $f$ be a non-negative $\mathcal {B}$-measurable function such that $\int_K f d\mu \lt \infty$ for every compact subset $K$ where $\mu$ is the Lebesgue measure. We write $\nu(M) = \int_M f d\mu$ for $M\in \mathcal B$.
Then $\nu$ is a Borel measure.
2) Let $E$ be a countable subset of $\mathbb R$. Let $f: E \rightarrow \mathbb R$ be a non-negative function such that $\sum_{x\in K\cap E} f(x) \lt \infty$ for every compact subset $K$.
We write $\nu(M) = \sum_{x \in M\cap E} f(x)$ for $M\in \mathcal B$.
Then $\nu$ is a Borel measure.

I would like to know other non-trivial examples of Borel measures on $\mathbb R$.
Answer: Let $C$ be a cantor set. Let $f:C \to [0,1]$ be a Borel isomorphism. We put $\lambda(X)=\mu(f(X \cap C))$ for each $ X \in B(R)$. Then $\lambda$ is other non-trivial example(singular, following William Curtis remark)  of Borel measure on $R$.


Is my understanding of extreme value theorem correct?

Question: The extreme value theorem says a continuous function achieves its maximum and minimum on a compact domain.
Consider $f: (0,1)\rightarrow \mathbb{R}$ with $f(x)=x$. I impose the standard topology on the codoamin. I can choose a trivial topology ($\left\{\varnothing, (0,1)\right\}$) on the domain to make it a compact set. However, now $f$ is not continuous because the preimage of $(0.4,0.6)$, which is an open set in $\mathbb{R}$, is not open in the domain.
In sum, whether a function achieves its maximum/minimum should not depend on the topology of the domain/codomain, but the topology does affect whether one can apply the extreme value theorem. Is my understanding correct?
Answer: Yes, this is entirely correct. To use a different example illustrating the same point, we can use an example like $f:[0,1]\to\Bbb R$ given by
$$
f(x)=\cases{1& if $x=0$\\0& otherwise}
$$
Using standard topologies everywhere, we have a compact domain, but a non-continuous function, so you cannot apply the theorem. Yet the function clearly attains both its maximum and its minimum.
You could use a function with the same formula but with all of $\Bbb R$ as its domain instead. This would give you a non-compact domain in addition to a non-continuous function, making it extra clear that the theorem cannot be applied. But not at all changing the fact that the function does attain both its minimum and its maximum.


"Successful projects share the same 5 keys qualities. In each quality our project achieves over average score". What can we conclude about this?

Question: I'm not sure if this is a statistical problem, but I suppose it's a frequent problem involving using statistics, so I ask here anyway. Hope it's on-topic.
From the book Smart Pricing: How Google, Priceline, and Leading Businesses Use Pricing Innovation for Profitability:

Although music is a very risky business, we found that Radiohead's In Rainbows campaign shares the same five key qualities as any successful "pay as you wish" pricing program:

A product with a low marginal cost
A fair-minded customer
A product that can be sold credibly at a wide range of prices
A strong relationship between buyer and seller
A very competitive marketplace

In each quality, we assess our project has a higher than average score like this:

Quality no.
Score (over 10)

1
6

2
7

3
8

4
7

5
7

There is no measurement on each quality. We just reason with what we have and rate our confidence. Basically we just "feel the number".
What can we conclude from this? What techniques we can do to confirm or deny any assumption we have? And if we think "our project is more likely to success than fail", do we have any fallacy?
Related: What stops the pay-what-you-want pricing strategy from being more popular? on Economics SE
Comment: Right now, I don't see a *statistical* question here.  If you say what data you have, then ... maybe?  It would also need ways to measure the five characteristics, and an operationalzation of success.   Maybe someone who has read the book could fill some of that in?
Comment: That's why I say "I'm not sure if this is a statistical problem, but I suppose it's a frequent problem involving using statistics". To explain more on why I decide to ask here, at first I thought I had felt in to the [illusory correlation](https://en.wikipedia.org/wiki/Illusory_correlation "Illusory correlation - Wikipedia"). Then I read more about the famous "correlation does not imply causation", and decide that I need help from folks with strong statistics background. Is this line of thinking reasonable?
Answer:
do we have any fallacy?

I think you've made a mistake in thinking about conditional probability.
$
P(Success\vert Traits)
$ is what you want to know. You have $P(Traits\vert Success)=1$. However, flipping the conditioning leads to a different probability. You are not (nearly) assured of success by having those traits. You have to look at how many times those traits exist yet success is not achieved.
Every Olympian is a great athlete, but not every great athlete is an Olympian. Similarly, every success story has those five traits, but does every instance of having those traits lead to success?
Comment: @Ooker That's what predictive modeling is all about! You have to figure out what factors influence success probability and model that success probability somehow, such as with a logistic regression.
Comment: Yes, conditional probability is the term I'm looking for. As for the assessment of how well our project achieves the rate, what is the term of that? What is the relation between the scores, the probability of the success of the project, and $P(Success)$ in the sample space?
Comment: I see. Assuming the factors have equal influence (each one accounts for 20%), then how will the modeling be?
Comment: @Ooker Then you have the model as $P(Success)=\sum_{j=1}^5 0.2 x_j$ for the $x_j$ indicators of whether characteristic $j$ is present, but then you're not doing any machine learning or regression modeling. You're not learning from the data. You're just assuming that each factor has that influence, and I'll venture a guess that, even if every successful case has those five factors, not every time those five factors are observed is there success.


Cannot compile C++17 in Debian Linux

Question: I have the following code, that I can compile in Windows MinGW.
<code>#include <future>
#include <iostream>
#include <string>
int main(){
    auto futureLambda= std::async([](const std::string& s ){return "Hello C++11 from " + s + ".";},"lambda function\n");
    std::cout << futureLambda.get() << std::endl;
}
</code>
When I try to run it in Linux (gcc version 8.3.0 (Debian 8.3.0-6)) using
<code> g++ -std=c++1z main.cpp
</code>
or
<code> g++ -std=c++17 main.cpp
</code>
I get:
<code>/usr/bin/ld: /tmp/cc4vI5fr.o: in function std::thread::thread<std::__future_base::_Async_state_impl<std::thread::_Invoker<std::tuple<main::{lambda(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)#1}, char const*> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::_Async_state_impl(std::tuple<main::{lambda(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)#1}, char const*>&&)::{lambda()#1}, , void>(std::__future_base::_Async_state_impl<std::thread::_Invoker<std::tuple<main::{lambda(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)#1}, char const*> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::_Async_state_impl(std::tuple<main::{lambda(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)#1}, char const*>&&)::{lambda()#1}&&)':
main.cpp:(.text+0x1c72): undefined reference to 'pthread_create'
collect2: error: ld returned 1 exit status
</code>
What am I doing wrong?
Comment: Use -pthread to you gcc compile option
Comment: Thanks, did do a google search, but could not find this. Will try harder next time before asking.
Answer: Using std::thread requires linking to the pthread library on any POSIX system (including Linux). I think with GCC this is just '-pthread' as an argument rather than '-lpthread' as with other libraries.

Cannot compile C++17 in Debian Linux


Why isn't this a c flat?

Question:
I am always wondering why the second c isn't flat? There is no signs before it?
I know it is supposed to be played as natural, without natural signature?
This question was roughly answered by my previous answerers.
Original question: Why isn't the second whole note's accidental natural?
Comment: If you know it's supposed to be play as natural, then you already have the answer to your question.
Comment: See my extra comments to your other question.
Answer: There is no Cb in the key sig. In fact, Cb rarely appears in a key sig.Since there is a bar line preceding the C, any accidentals would be cancelled.So it couldn't be a C#.There is no reason at all why it should be a Cb.(Often called B, often incorrectly...) Therefore, it is played as a simple C natural, the white one on a piano.
Comment: C flat is also a white one on a piano ;-)
Comment: Depending on where you are, B might be the correct one and Bb considered anglo-american weirdness
Comment: @ojs - not following the comment.
Answer: I would advise you take some time to learn how to read sheet music.  Teoria has a set of beginner tutorials that will really help you to understand how music notation works, and how to understand what all the symbols and notes mean. That said, on to the question.
Key Signatures
In the key signature(the 2 b signs on the left) you have a Bb and an Eb.  this means that every B and E noted will actually be Bb and Eb respectively.
Accidentals
That's it for key signatures, that applies across all bars.  However, you also have accidentals which only take affect for the bar which they occur on. the sign on that note in the first bar is a natural sign.  it means ignore all sharpening and flattening that is being applied to this note for the rest of this bar.
As I mentioned before, accidentals only apply to the bar they are on.  that's why you have a Bb in bar 2 and not a B natural.
In bar 3, the C is sharpened to a C# by the # sign.  as I said before, all accidentals only take effect to the end of the bar, so it will not sharpen the C in the next bar.
Why the C is natural
Okay, now on to the bar with the C in it.  As I said at the start, the key signature affects all B and E notes, so the C note will not be affected.  The # sign from the bar before stopped taking effect before this bar, so there are no alterations to be made to C notes appearing on this bar.  this means that the note marked on bar 4 is an unsharpened, unflattened C, also called C natural.
I've been as thorough as I can, I hope this helps clear up any concerns :)
Answer: The key (Bb Major/G minor) has a signature of two flats (Bb and Eb). So, all notes except these two will be natural unless they are modified by an accidental (sharp, flat, or natural). When a note is modified by an accidental, all following notes of the same pitch in that measure will be modified by the same unless they have another accidental.
So, the C# only applies to that measure. The next measure starts off with the basic key signature, so that C is unmodified and hence a C natural.
Answer: The second C is C natural because there is nothing to indicate that it's anything else!    C isn't mentioned in the key signature.  The ♯ in the preceding bar only lasts as long as the next barline.  So it's C natural.  (C FLAT?  Where did THAT idea come from?)
Having said that, it would be normal practice to add cautionary accidentals, thus:
Comment: Some editors also place the courtesy accidentals in parentheses, in hopes that the reader will recognize that the accidental within is not necessary. (I'm sure you knew that, but I thought it worth mentioning in the comments at least)

Why isn't this a c flat?


Extract Build Identifier from Crash Report?

Question: Technical Q&A QA1765 : How to Match a Crash Report to a Build explains how to "Find the Build Identifier in a Crash Report" using grep.
$ grep -A=1 "Binary Images:" Example.crash
Binary Images:
   0xb6000 - 0xb7fff +Example armv7 <270a9b9d7a333a4a9f1aaf8186f81394> /var/mobile/Applications/28D4F177-D312-4D3B-A76C-C2ACB4CB7DAD/Example.app/Example

But, what's the best way to extract just the build identifier: 270a9b9d7a333a4a9f1aaf8186f81394?
Answer: The Technical Q&A that you linked to states:

The first line in the "Binary Images:" section of a crash report includes the build identifier, inside <>.

So, I would go with something like:
grep -A 1 "Binary Images:" Example.crash | sed -n 's/.*<\([a-z0-9]\{32\}\)>.*/\1/p'

Comment: What kind of shenanigans is this, answering your own question within less than a minute? Is this one of these "I wanted to post and answer a reference question that might help somebody else" kind of deals?
Comment: Sure. I figured out an answer to the question as I was asking it. Note: It's not "my own question." I don't "own" this question. It's just a question I had. There's a subtle but important difference, as [Eckhart Tolle](http://www.eckharttolle.com) explains in his books. :) Others may also have the same question. May *this* answer (Notice, it's not *my* answer.) serve them.


what is epsilon/k in epsilon greedy algorithm

Question: As it was told it would choose the arm having highest emperical mean with probability 1-epsilon how did epsilon/k add to it (and also epsilon/k for random probability selection)in the equation written for probability in the page no:6 of the paperAlgorithms for multi armed bandits.What does that mean epsilon/k writing there in the equation
paper of "algorithms for multi armed bandit problems"
Answer: We have:

$k$ different arms/"actions" to select
A probability of $\epsilon$ to select an arm uniformly at random
A probability of $1 - \epsilon$ to straight up select the "best" arm according to our current value estimates (this is the arm corresponding to $i = \arg \max_{j = 1, \dots, K} \hat{\mu}_j(t)$).

The last point above tells you already where the "$1 - \epsilon$" term comes from. However, note that, when we decide to select an arm uniformly at random (which happens with probability $\epsilon$, the "best arm" again also gets another chance to get played. With probability $\epsilon$, each of the $k$ arms gets an equal probability to get played, which must then be $1 / k$.
So, in total, the "best arm" gets a probability of $1 - \epsilon + \epsilon / k$ to get played ($1 - \epsilon$ probability to get selected directly, and $\epsilon \times 1/k = \epsilon/k$ additional probability to get selected at random). Each of the remaining arms only has any chance of getting selected at all if we decide to explore instead of exploit with probability $\epsilon$, and in that event only gets a probability of $1/k$ to get randomly selected instead of any other arm, for a total probability of $\epsilon \times 1/k = \epsilon/k$.


how to set select box value by id in grails

Question: I have 3 select box. No 1 is for division, No 2 is for district and No 3 is for city. Now when I load them on ajax call using remoteFunction it works fine. But When I want to update a value I want that for a entry the division,district and city will be selected in selecbox so that the user can change it if necessary. It works well but then district select box loads all district without following the divisionId and city loads all cities without following the districtId. I have no idea how to do it. Is there any way to load district by the divisionId !? Can anyone please help me on this please. Here are my domain and view below >>>
here ary my domain with division, district and city >>>
    class Committee {
    Long id
    Division division
    District district
    City city
    String committeeName
}

here is my update action from where i am passing value to view >>>
def updateCommittee(){
    Committee committee = Committee.get(Long.parseLong(params.committeeId))
    [committee: committee]
}

here is my view where I am setting value in select box >>>
division select box :
<g:select class="form-control"
      name="divisionId"
      id="divisionId"
      from="${committee.division?.list()}"
      value="${committee.division?.id}"
      optionKey="id"
      optionValue="name"
      width="130"
      required=""
      onchange="loadDistrict(this.value)"/>

district select box :
<g:select class="form-control"
      name="districtId"
      id="districtId"
      from="${committee.district?.list()}"
      value="${committee.district?.id}"
      optionKey="id"
      optionValue="name"
      width="130"
      onchange="loadCities(this.value)"
      required=""/>

Answer: I have solved the issue. Just a little bit of change in the district select box with attribute from. Here it is below >>>
<g:select class="form-control"
      name="districtId"
      id="districtId"
      from="${District.findAllByDivision(committee.division)}"
      value="${committee.district?.id}"
      optionKey="id"
      optionValue="name"
      width="130"
      onchange="loadUpazila(this.value)"
      required=""/>


Cucumber - Is it possible to share a table between Scenarios?

Question: Does anyone know its its possible to define a table once in a .feature file & then access it from multiple scenarios? I'm not chaining scenarios but many of them do need to pass tables with the same data to their step definitions - also for this reason examples won't really do what I need here.
Thanks!
Answer: One possible solution is to tag all your scenarious where you need a table:
@given_have_table
Scenario: test
  Then I am happy

Then bind Before hook to this tag and call step that declares your table from within Before hook definition:
Before("@given_have_table") do
  steps Q%{
  Given I have the following table:
    | a | b |
    | 1 | 2 |
  }
end

Alternative approach is to construct required table in tagged Before hook without calling step:
Before("@given_have_table") do
  @tbl = { :a => 1, :b => 2 }
end


Call for answer until correct is given? Java Eclipse

Question: I am basically playing around with eclipse to retain what I learned in my intro to Java class.  I am about to enroll in advanced programming and I have a beginner's question...
I created this little program below because I was having a hard time understanding methods.  Now that I have the general concept down, I have a new question.  I have a do while statement below and it works if you enter the right answer to the simple addition problem.  If you enter the wrong answer, it will ask you to try the problem again (as I want it to).  If you enter the wrong answer again, the program stops.  I want it to prompt the user to enter the answer until they're correct.  How do I do this?
import java.util.Scanner; //needed for input

public class PracticeMethod {
    public static void main(String[] args) {
        // Create a Scanner

        System.out.println(");
        System.out.println();
        makesPerfect();
        String anotherRun = "yes";

        Scanner input = new Scanner(System.in);

    }

    static void makesPerfect() {
        Scanner input = new Scanner(System.in);
        String anotherRun;
        do {

            System.out.print(" Math");
            int x = (int) (Math.random() * 10) + 1;
            int y = (int) (Math.random() * 10) + 1;

            System.out.print(" What is " + x + "+" + y + "? ");
            double answer = 0.0;
            answer = input.nextDouble();
            if (answer == x + y) {
                System.out.println(" Yes, you are correct.");

            }
            if (answer != x + y) {
                System.out.print(" No, that is not correct. ");
                System.out.println();
                System.out.print(" Why dont you try again? ");
                System.out.println();
                System.out.println();
                System.out.print(" What is " + x + "+" + y + "? ");
                answer = input.nextDouble();
            }
            System.out.println();

            System.out.print("Enter yes if you want to run again: ");
            anotherRun = input.next();
            input.nextLine(); // causes skipping issue to fix
            System.out.print("\n\n\n");
        } while (anotherRun.equalsIgnoreCase("yes"));
    }
}

Answer: Make your if statement checking if the answer is correct a while loop. That way you'll just keep asking for the correct answer until you get it.
while(answer != x + y) {
    System.out.print(" No, that is not correct. ");
    System.out.println();
    System.out.print(" Why dont you try again? ");
    System.out.println();
    System.out.println();
    System.out.print(" What is " + x + "+" + y + "? ");
    answer = input.nextDouble();
}

Also kudos for using StackOverflow correctly, and for making an effort to learn! One day maybe you'll be answering questions for me.
Comment: Thank you! @ William Morrison


display newly added field value of account settings

Question: I added a new field(First name) in Account settings under Configuration & its machine name is 'field_first_name'
I am trying to load this value in home page like this
<?php print $user->field_first_name ?>

But the above code is not working. Please help. I debug $user and found that this value isn't there. What should I do to show the value of the newly added field in home page.
I've added screenshot.
Comment: You seems to first need to debug the `$user`, to do that: `dpm($user);` (if you have devel module installed), otherwise `echo ''; print_r($user);`,  than you can check what is the exact name of field first name in the user object.
Answer: You should use field_get_items:
global $user;

$user_contaning_field = user_load($user->uid);

// Check if we're dealing with an authenticated user
if ($user->uid) {

  // Get field value from $user
  $field_first_name = field_get_items('user', $user_contaning_field, 'field_first_name');

  foreach ($field_first_name as $key => $value) {
    print field_view_value('user', $user_containing_field, 'field_first_name', $field_first_name[$key]);
  }
}

Comment: And better, use [field_view_value](https://api.drupal.org/api/drupal/modules!field!field.module/function/field_view_value/7) to get the value.
Comment: I am getting error message "Notice: Undefined variable: field_first_name in include() (line 31 of C:\xampp2\htdocs\Journal\themes\admin\templates\includes\admintoolbar.php)."
Comment: @SureshAlagar please try with updated answer
Comment: the reason it was not showing you field is $user used as arguments for "field_get_items" does not contain the field information.you to load the user so to have the field inside the user entity.
Comment: Thanks, arpitr. You have solved my problem. Thanks again.
Comment: Made a small edit incorporating [`field_view_value`](https://api.drupal.org/api/drupal/modules!field!field.module/function/field_view_value/7) as suggested by @ЕлинЙ.
Answer: Small edit with @Beebee asnwer, since it seems he is not logged in so adding it as separate answer
global $user;

 // load the user entity so to pick the field from.
$user_contaning_field = user_load($user->uid);

// Check if we're dealing with an authenticated user
if($user->uid) {

  // Get field value;
  $field_first_name = field_get_items('user', $user_contaning_field, 'field_first_name');
  if(isset($field_first_name[0]['value']))
    print $field_first_name[0]['value'];
}

Answer: Try this for starters
<?php
    global $user;
    if ($user->uid) { // if registered...
      //get field value and print it
    }

Comment: I am getting an error message "Undefined property: stdClass::$field_first_name"
Comment: yeah its actually not the real code you need, is a start point, try to debug the $user object..., field_get_items below seems great
Comment: Hello. Code-only answers are rarely usable. If the code works, they don't tell what was the problem and why it works. If it does not, it's even worse as they provide neither reasoning nor solution.


Escolhas do usuário em Tkinter

Question: Olá. Estou a tentar criar um programa de interfaçe gráfica usando Tkinter(aprendi há pouco tempo) e queria que o usuário, ao escrever na caixa de entrada de texto e ao carregar no botão  ele imprimisse algo. Se escrever B maiúsculo imprime "a iniciar a bios" e se não escrever algo imprime "a iniciar o SO".
Código:
# -*- coding: cp1252 -*-
from Tkinter import *

#função de arranque da VM:
def arranque():
    root = Tk()
    root.minsize(950, 700)
    root.wm_iconbitmap('virtual-pc-1338544131.ico')
    root.title("Computador virtual PowerBIT v1.0")
    root.configure(background='black')
    machine = Label(root, text="Bem vindo à máquina virtual. Prima B para aceder ao BIOS ou ENTER para inciar o SO", fg="white", bg="black").grid(row=0)
    e1 = Entry(root, bg = "white", fg = "black" )
    e1.grid(row=0, column=1)
    botao_de_arranque = Button(root, text="Iniciar", width=6).grid(row = 1, column = 1, )
    root.mainloop()
arranque()

Comment: Vou te dar uma dica, amigo. Usa [easygui](http://easygui.sourceforge.net/).
Answer: O widget Button fornece um callback que permite fazer algo quando o usuário clicar no botão.
Veja um exemplo:
from Tkinter import *

def callback():
    print "O usuario clicou no botao"

b = Button(text="Clique aqui", command=callback)
b.pack()

mainloop()

No código apresentado por você isso poderia ser implementado da seguinte forma:
# -*- coding: cp1252 -*-
from Tkinter import *

def btn_arranque(texto):
    # Fazer alguma coisa aqui ao clicar no botão
    if texto == 'B':
        # Fazer alguma coisa aqui caso o edit ter o texto 'B'
    else:
        # Fazer algo aqui caso o texto do edit não for 'B'

def arranque():
    root = Tk()
    root.minsize(950, 700)
    root.wm_iconbitmap('virtual-pc-1338544131.ico')
    root.title("Computador virtual PowerBIT v1.0")
    root.configure(background='black')

    machine = Label(root, text="Bem vindo à máquina virtual. Prima B para aceder ao BIOS ou ENTER para inciar o SO", fg="white", bg="black").grid(row=0)
    e1 = Entry(root, bg="white", fg="black" )
    e1.grid(row=0, column=1)
    botao_de_arranque = Button(root, text="Iniciar", command= lambda: btn_arranque(e1.get()), width=6).grid(row=3, column=1,)
    root.mainloop()

arranque()

Escolhas do usuário em Tkinter


Helm install spark-operator tries to download a version that does not exist and cannot be force to use the correct one

Question: I am trying to install ANY working version of spark-operator https://console.cloud.google.com/gcr/images/spark-operator/GLOBAL/spark-operator?tag=v1beta2-1.3.1-3.1.1
on my local kubernetes.
However, spark pod is stuck on ImagePullBackOff trying to download a version that does not exist.
Commands:
helm repo add spark-operator https://googlecloudplatform.github.io/spark-on-k8s-operator
helm install v1beta2-1.2.1-3.0.0 spark-operator/spark-operator --namespace spark-operator6 --create-namespace
kubectl get pods -n spark-operator6
NAME                                                  READY   STATUS             RESTARTS   AGE
v1beta2-1.2.1-3.0.0-spark-operator-67577fd4d4-m9zmw   0/1     ImagePullBackOff   0          6s
kubectl describe pod v1beta2-1.2.1-3.0.0-spark-operator-67577fd4d4-m9zmw
Image:         gcr.io/spark-operator/spark-operator:v1beta2-1.3.1-3.1.1 - a different one!
Failed to pull image "gcr.io/spark-operator/spark-operator:v1beta2-1.3.1-3.1.1": rpc error: code = Unknown desc = Error response from daemon: manifest for gcr.io/spark-operator/spark-operator:v1beta2-1.3.1-3.1.1 not found: manifest unknown: Failed to fetch "v1beta2-1.3.1-3.1.1" from request "/v2/spark-operator/spark-operator/manifests/v1beta2-1.3.1-3.1.1"
Now this just seems like an incorrect version. Tried to override it via helm install flag --operatorVersion, but that is completely ignored.
Took a look at its template via helm template v1beta2-1.2.1-3.0.0 spark-operator/spark-operator --namespace spark-operator6 --set operatorVersion=v1beta2-1.2.1-3.0.0 > template.yaml and all the app.kubernetes.io/instance are on correct version, but ALL app.kubernetes.io/version were showing the non-existing v1beta2-1.3.1-3.1.1. Corrected it and tried to install with the correct values via
helm install -f template.yaml v1beta2-1.2.1-3.0.0 spark-operator/spark-operator --namespace spark-operator6
but this was completely ignored again.
I feel like I am missing something very basic here, helm install cannot possibly be that broken. Any help is much appreciated, thanks.
Answer: Try this one
helm upgrade -i my-release spark-operator/spark-operator --namespace spark-operator --set image.tag=v1beta2-1.3.2-3.1.1 --set image.repository=ghcr.io/googlecloudplatform/spark-operator
the key thing here is the image.tag and image.repository.
I am assuming you have a namespace for spark-operator. Please adjust namespace according to your requirements.
Comment: thanks, setting the image repo helped
Comment: Thanks a lot, @baris-cekic! That helped! I figured the `image.tag` part from their docs, but I would never guess the `ghcr.io` registry!


How do I create a dynamic link for a block?

Question: I have two dynamic links that I want to put in a block, e.g. http://domain.com/series/naruto/addreview ("series" is the content type, and "naruto" is the node title), http://domain.com/node/add/album/1 ("1" is the node ID).
I want to change the URL depending on what node is being viewed. How can I do it?
Answer: You can get the node id from the url, since all nodes are displayed at node/[nid]. So if you in your block do
$nid = arg(1);
$node = node_load($nid);

You will get the node which has the title and the nid that you can use in your links. You would need to check that the block is on a node page as well by doing:
if (arg(0) == 'node')

Answer: Since Drupal 6, you can use menu_get_object() that, with the default arguments, will return you the node object associated with the URL being visualized. This means that if the URL of the page being show is example.com/user/1, then the function will return FALSE; if the URL is example.com/node/1, example.com/node/1/edit, then it will return the node object from which you can get the information you need.
$links = array();

if ($node = menu_get_object()) {
  $links[] = url($node->type . '/' . $node->title . '/addreview');
  $links[] = url('add/album/' . $node->nid);
}

I took the assumption that the URLs you reported were URLs for the site where Drupal is running; in this case, url() is the function that generated URL for the Drupal site for which the code is running.
If you want to generate the  tags, then you should use l(). In this case, the code changes as follow:
$links = array();

if ($node = menu_get_object()) {
  $links[] = l(t('Add review'), $node->type . '/' . $node->title . '/addreview');
  $links[] = l(t('Add album'), 'add/album/' . $node->nid);
}

The code I reported is just an example; your code should do what you need to do with the value returned from the function.
Comment: I'm not a coder. I just copied and pasted that code into a block and set input filter to PHP and it doesn't display anything
Comment: @Ruriko Which code? What is the URL of the page from where you executed that code? The code I wrote doesn't output anything; it just example code that shows which functions to call, and which parameters to pass to the functions. As in the question you didn't say how you would use that code, I reported just the code to dynamically get the links.


linear regression using other norms

Question: Let us consider the linear regression model in finite dimensions given by $Y = X \beta + \epsilon$ where $Y \in \mathbb{R}^n, X \in \mathbb{R}^{n \times m}, \beta \in \mathbb{R}^m$, and $ \epsilon \in \mathbb{R}^n$ is the Gaussian noise. I know that to compute the loss function, using the $\ell^2$ or $\ell^p$ error for finite-dimensional spaces is used to measure the misfit.
I am wondering if other norms from functional analysis can be used for linear regression such as the sobolev norms or negative sobolev norms adapted to the finite-dimensional setting.
Is there any literature on this topic? Would it be too overkill to use other types of norms instead of the $\ell^2$ norm for the misfit?
Comments appreciated!
Comment: This question strikes me as needing some additional information or assumptions.  The Sobolev norms involve derivatives.  What do you hope the analog of a derivative would be in a finite dimensional space?
Comment: At the top of my head, the derivatives can be discretized using finite differences. Does this help? I'm primarily seeking references and intuition.
Comment: Such discretization would appear to introduce nothing new.  You seem to be in pursuit of a question rather than having any particular question to ask.
Comment: This question came about because I was curious how various norms on the misfit are sensitive to the noise $\epsilon$ for linear regression. Do you have any references on this? I have not encountered this while reading elements of statistical learning.
Comment: Perhaps the mention of Sobolev norms has distracted from the main point of using norms that aren't $l^p$ norms (perhaps even metrics that don't come from norms).
Comment: Birkes and Dodge have a book titled *Alternative Methods of Regression* which should have some leads. Also, Lugosi, *Mean estimation and regression under heavy-tailed distributions—a survey* uses alternative methods as well. https://arxiv.org/abs/1906.04280
Comment: The $L^2$ norm is canonical because minimizing your objective with respect to this norm represents an orthogonal projection into the subspace spanned by $X$.
Comment: @YashaswiMohanty Yet minimizing other norms can lead to useful estimators.
Comment: @Dave of course: the conditional expectation is not the only useful function of the joint distribution. It has some nice properties though, as Hilbert spaces are generally nicer than Banach spaces in general.
Answer: Minimizing a norm other than $\ell^2$ is, in some sense, just some other extremum estimator. The OLS estimator is an extremum estimator because the estimated parameters are the points giving the minimum of $\vert\vert y - \hat y\vert\vert_2$. If you want to have the objective function of some other extremum estimator to be some other norm $\vert\vert y - \hat y\vert\vert_{\text{other}}$, go for it.
$$
\hat\beta_{\text{ols}} = \underset{\hat\beta}{\arg\min}\{
\vert\vert
y - X\beta
\vert\vert_2
\}\\
\hat\beta_{\text{other}} = \underset{\hat\beta}{\arg\min}\{
\vert\vert
y - X\beta
\vert\vert_{\text{other}}
\}
$$
For instance, minimizing the $\ell^1$ norm leads to quantile-regression at the median. Depending on the situation, this can give a better estimate of the mean than minimizing the $\ell^2$ norm gives. Consequently, more than just $\ell^2$ minimization is useful. Getting away from $\ell^p$ norms, minimizing a weighted norm corresponds to weighted least squares, and a similar idea should apply for generalized least squares, so it is not just $\ell^p$ norms whose minimizations find use in statistics.
Regarding Sobolev norms in particular, I do not see a way for that to make sense, since a Sobolev norm involves derivatives of the function in the function space.

linear regression using other norms


Nginx - if pattern 404 - go to

Question: I have list of urls like:
domain.com/some-url-key-with-possible-id-after-it-99999.html

I need to try that URL, and IF it returns 404, redirect to:
domain.com/some-url-key-with-possible-id-after-it.html

Is that possible?
location ~ /([a-zA-Z0-9\-]+)-([0-9]+).html$ {
## IF ABOVE IS 404
    return       301 http://domain.com/$1.html;
## ENDIF
}

I found something like this:
server {
        listen             12440;
        root       /some/path/here/nginx/html/noahc/;
        server_name    www.domain.net, domain.net;
        port_in_redirect off;

        location /{
            error_page 404 =  @foobar;
        }

        location @foobar {
            rewrite  .*  / permanent;
        }
 }

But it doesn't satisfy me, because I need to redirect to url with variable from request pattern. It could be ok, if I'll be able to pass ([a-zA-Z0-9-]+)-([0-9]+) to it as an argument.
Comment: why do you want to use a variable for url? what ar you requesting with the variable ?
Comment: The result of: ([a-zA-Z0-9-]+)-([0-9]+)
Comment: this are pattern, but what do you want to do with them ?
Comment: look here http://serverfault.com/a/569683
Comment: do you mean missing file or a cgi-subrequest.
Comment: @Blueblazer172
redirect to:     return       301 http://domain.com/$1.html;
where variable $1 is the result of pattern match ([a-zA-Z0-9-]+)-([0-9]+).
Answer: So you have a URI and you would like to rewrite it if the static file does not exist. Use try_files to test for file existence.
root /path/to/docroot;

location ~ ^(/[a-zA-Z0-9-]+)-[0-9]+\.html$ {
    try_files $uri @rewrite;
}

location @rewrite {
    return 301 $1.html;
}

You can use return 301 or rewrite ... last in the named location, depending on how visible you want the rewrite to be.
See this document for help with nginx directives.
Comment: is it that simple? Let me check! :)
Comment: It's not working as intended - It redirects every time, not only if request is 404.
Comment: You mean `try_files $uri` cannot find your file? Have you set `root` correctly, and have you looked at your logfiles?

Nginx - if pattern 404 - go to


How to use multiple text fields in widget "image" in content type

Question: I'm new in Drupal and I'm working on a website built in Drupal. I want to use multiple text fields like title, medium, photo credits with image widget in content type. I have attached two screen-shots to make clear what I really want to do.

Please help to find out the way to do this. I'll be thankful to you.
Answer: You can take a look on Image Field Caption module.
Adds an extra text area for captions on image fields.
Similar to the alt and title text fields available with an image field, the caption text area can be used to enter text or html descriptions of an image.
Media module also work for you.
Comment: but I need to add 3 or more fields. Is it possible with Media module?


Is there a way to not use global variables in my code?

Question: I am relatively new to Python so please bear with the inefficiency of my code. This is one of my first Tkinter applications and it is quite a simple one. It is a code guessing game where the user tries to guess a randomly generated 4 digit code. The code currently prints the randomly generated number so that it is easier to see if the code is working. But is there a way to not use global variables in this code. Also, it would be helpful if I was told how to make my code efficient. Thanks in advance. Code:
<code>import random
import tkinter as tk

number_of_tries = 0

def tries():
    global number_of_tries
    number_of_tries += 1
    comment.configure(state="normal")
    comment.delete(0, "end")
    comment.insert(0, "Not quite! Keep trying!")
    comment.configure(state="disabled")
    if str(guess) == str(random_number):
        comment.configure(state="normal")
        comment.delete(0, "end")
        comment.insert(0, "You guessed it in " + str(number_of_tries) + " tries!")
        comment.configure(state="disabled")
        guess_entry.configure(state="disabled")
        go.configure(state="disabled")

def character_check():
    global guess
    guess = guess_entry.get()
    if len(guess) != 4:
        comment.configure(state="normal")
        comment.delete(0, "end")
        comment.insert(0, "Guess must be 4 digits! ")
        comment.configure(state="disabled")
    else:
        for char in guess:
            if char.isalpha():
                comment.configure(state="normal")
                comment.delete(0, "end")
                comment.insert(0, "Guess must only include integers! ")
                comment.configure(state="disabled")
            else:
                digit_check()

def digit_check():
    global guess
    guess = guess_entry.get()

    for i in range(0, 4):
        if str(guess)[i] == str(random_number)[i]:
            digits[i] = str(guess)[i]
            digit_display.configure(state="normal")
            digit_display.delete(0, "end")
            digit_display.insert(0, digits)
            digit_display.configure(state="disabled")
        elif str(guess)[i] != str(random_number)[i]:
            digits[i] = "?"
            digit_display.configure(state="normal")
            digit_display.delete(0, "end")
            digit_display.insert(0, digits)
            digit_display.configure(state="disabled")

def initialise():
    global number_of_tries, digits
    global random_number
    digits = ["?"] * 4
    random_number = random.randrange(1000, 9999)
    number_of_tries = 0
    digit_display.configure(state="normal")
    comment.configure(state="normal")

    digit_display.delete(0, "end")
    digit_display.insert(0, digits)
    comment.delete(0, "end")
    comment.insert(0, "Good luck!")

    digit_display.configure(state="disabled")
    comment.configure(state="disabled")
    guess_entry.configure(state="normal")
    go.configure(state="normal")
    print(random_number)

screen = tk.Tk()
screen.geometry("400x400")
screen.title("Code Crunchers")

heading = tk.Label(text="Welcome to Code Crunchers!", font="Montserrat 15")
heading.place(relx=0.5, rely=0.1, anchor="center")

instruction_1 = tk.Label(text="Enter your guess below: ", font="Montserrat 10")
instruction_1.place(relx=0.5, rely=0.2, anchor="center")

guess_entry = tk.Entry(screen, width=4)
guess_entry.place(relx=0.5, rely=0.25, anchor="center")

go = tk.Button(text="Go", font="Montserrat 10", command=lambda: [character_check(), tries()])
go.place(relx=0.6, rely=0.27, anchor="center")

instruction_2 = tk.Label(text="Digits correct: ", font="Montserrat 10")
instruction_2.place(relx=0.5, rely=0.35, anchor="center")

digit_display = tk.Entry(screen, width=10)
digit_display.place(relx=0.5, rely=0.4, anchor="center")

comment = tk.Entry(screen, width=40)
comment.place(relx=0.5, rely=0.45, anchor="center")

restart = tk.Button(text="Restart", font="Montserrat 10", command=lambda: initialise())
restart.place(relx=0.5, rely=0.55, anchor="center")

initialise()

screen.mainloop()
</code>
Comment: Put the code inside a class, then you can use instance variables instead of global variables.
Answer: What I would do is simply display the number of tries to the user and then read from that object to see the amount of tries. If you do not want to display it to the user you can always hide it so it does not display. If you do not want to have it on your GUI at all you should then pass this variable around as arguments in your functions.