text:
Q: Trying to understand AngularJs animation transitions with keyframes I'm new in Angular and I don't have many experience with css3 (i'm a backend dev!)
I'm trying to understand how angular manage custom transitions with css3 keyframes.
I got this:
In my markup:

...

in my controller:
$scope.test = false;
// ... doing some things that takes more than 3-4 seconds
$scope.test = true;

and in my CSS:
#welcome-container.ng-hide {
    animation:1s mycustomkeyframe;
    -webkit-animation:1s mycustomkeyframe;
}

@keyframes mycustomkeyframe {
    from { opacity: 1; }
    to { opacity: 0; }
}

@-webkit-keyframes mycustomkeyframe {
    from { opacity: 1; }
    to { opacity: 0; }
}

I got this example running with ng-hide-add and ng-hide-active classes but I'm really lost with keyframes. My code hide the div but it doesn't do any animation!! I want to use keyframes to do jquery-like elastic easing transitions (without jquery :P)
Anybody can help me please?

A: Never used angular before, but from the CSS standpoint you don't have a class ng-hide on your div.

Here is a bunch of text blah

JsFiddle

A: AngularJS and CSS3 are 2 totally different things
Angular can be used to attach a CSS class to the container
and after that .. based on that new CSS class . you can trigger animation start from CSS
$scope.my_css_clas = 'demo_classs'

classes in Angular are attached with ng-class

A: I think it's not possible to animate with keyframes the ng-hide directive in the current version.
You must use another class to animate and then when animation is over do the hide action or use another ng-directive like ng-leave.


text:
Q: Question about the proof that $(D(f),\mathcal{O}_{\operatorname{Spec}A}|_{D(f)})\cong (\operatorname{Spec}A_f,\mathcal{O}_{\operatorname{Spec}A_f})$ I am trying to prove/understand why $(D(f),\mathcal{O}_{\operatorname{Spec}A}|_{D(f)})\cong (\operatorname{Spec}A_f,\mathcal{O}_{\operatorname{Spec}A_f})$. This problem appears in Vakil's algebraic geometry notes as problem 4.3.B.
I know that since $D(f)=\{P\in\operatorname{Spec}A\mid f\not\in P\}$, we can identify $D(f)$ and $\operatorname{Spec}A_f$. So let $\pi:D(f)\rightarrow \operatorname{Spec}A$ be the natural map.
I'd now like to show that $\mathcal{O}_{\operatorname{Spec}A_f}\rightarrow \pi^*\mathcal{O}_{\operatorname{Spec}A}|_{D(f)}$ is an isomorphism of sheaves. The hint given is to notice that distinguished open sets of $\operatorname{Spec}A_f$ are already distinguished open sets in $\operatorname{Spec}A$.
If we consider $D(g/f^n)=\{P\in\operatorname{Spec}A_f\mid g/f^n\not\in P\}$, then how can we think of this as a distinguished open set in $\operatorname{Spec}A$? It doesn't make sense to ask if $g/f^n$ is not in a prime ideal of $A$. Is really saying that the corresponding prime ideal of $A$ doesn't contain $g$?
Further, I know that $\mathcal{O}_{\operatorname{Spec}A_f}(D(g/1))$ is the localization of $A_f$  is the localization of $A_f$ at all elements that do not vanish outside of $V(g/1)$. That is, the localization of $A_f$ at $\{a/f^n\in A_f\mid D(g/1)\subset D(g/f^n)\}$.
And how do we describe $\mathcal{O}_{\operatorname{Spec}A}|_{D(f)}(D(g))$?
How can I go about finish this problem/seeing the isomorphism?

A: There's a lot of confusion in your post: as is, your proposed morphism of sheaves does not make any sense. The map you consider should not be the embedding $\pi \colon D(f) \to \mathrm{Spec}(A)$, but rather the embedding $\mathrm{Spec}(\alpha) \colon \mathrm{Spec}(A_{f}) \to \mathrm{Spec}(A)$ induced by the canonical localization map $\alpha \colon A \to A_{f}$. As you note, $\pi := \mathrm{Spec}(\alpha)$ is an open embedding whose image is $D(f)$, so we may view it as an isomorphism of topological spaces $\mathrm{Spec}(A_{f}) \to D(f)$.
Moving to sheaves, let me recall what the sheaf $\mathcal{O}_{\mathrm{Spec}(A)}|_{D(f)}$ is. For any open set $U \subset D(f)$, $U$ is likewise an open set of $\mathrm{Spec}(A)$, and by definition we have $\mathcal{O}_{\mathrm{Spec}(A)}|_{D(f)}(U) = \mathcal{O}_{\mathrm{Spec}(A)}(U)$. The key, then, is understanding which distinguished opens of $\mathrm{Spec}(A)$ are contained in $D(f)$ - more on this shortly. Moreover, the map $\pi$ comes with an associated morphism of sheaves $\mathcal{O}_{\mathrm{Spec}(A)} \to \pi_{\ast}\mathcal{O}_{\mathrm{Spec}(A_{f})}$, which on global sections is $\alpha$ and on distiniguished opens is the (induced) localization map. The corresponding morphism of sheaves $\mathcal{O}_{\mathrm{Spec}(A)}|_{D(f)} \to \pi_{\ast}\mathcal{O}_{\mathrm{Spec}(A_{f})}$ is induced by $\mathcal{O}_{\mathrm{Spec}(A)} \to \pi_{\ast}\mathcal{O}_{\mathrm{Spec}(A_{f})}$ in the obvious way; on global sections, it is the identity map $A_{f} \to A_{f}$, since $\mathcal{O}_{\mathrm{Spec}(A)}|_{D(f)}(D(f)) = \mathcal{O}_{\mathrm{Spec}(A)}(D(f)) = A_{f}$, and $\pi^{-1}(D(f)) = \mathrm{Spec}(A_{f})$.
All that remains is to understand why $\mathcal{O}_{\mathrm{Spec}(A)}|_{D(f)} \to \pi_{\ast}\mathcal{O}_{\mathrm{Spec}(A_{f})}$ is an isomorphism of sheaves on $D(f)$. It suffices to check this on a basis for the topology on $D(f)$, which is given by the distinguished opens of $\mathrm{Spec}(A)$ contained in $D(f)$. With the above details settled, here is a guide to the approach, which I leave to you.
(1) First, show that we have a containment of distinguished opens $D(g) \subset D(f)$ if and only if $f$ is a unit of $A_{g}$. (This is exercise 3.5F of Vakil - very much worth doing, if you haven't done so yet.)
(2) Next, show that $\pi^{-1}(D(g)) = D(\alpha(g)) = D(g/1)$ for any $g \in A$. (There is nothing special about $\pi$ here, to be clear: for any morphism of rings $u \colon A \to B$ and any $g \in A$, one has $\mathrm{Spec}(u)^{-1}(D(g)) = D(u(g))$.)
(3) Finally, we put things together. Let $D(g)$ be a distinguished open of $\mathrm{Spec}(A)$ which is contained in $D(f)$, which by (1) ensures that $f$ is a unit in $A_{g}$. We have
$$\pi_{\ast}\mathcal{O}_{\mathrm{Spec}(A_{f})}(D(g)) = \mathcal{O}_{\mathrm{Spec}(A_{f})}(D(\pi(g))) = (A_{f})_{g/1}$$
and
$$\mathcal{O}_{\mathrm{Spec}(A)}|_{D(f)}(D(g)) = \mathcal{O}_{\mathrm{Spec}(A)}(D(g)) = A_{g}$$.
The map $A_{g} \to (A_{f})_{g/1}$ is the universal map induced by $\alpha \colon A \to A_{f}$. Your task is to show that this map $A_{g} \to (A_{f})_{g/1}$ is an isomorphism, which I leave to you. (I would use the universal property of localization to get a map $(A_{f})_{g/1} \to A_{g}$. You will use that $f$ is invertible in $A_{g}$ to get a map $A_{f} \to A_{g}$ first.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding counter based on values Python DataFrame I have the following DataFrame df1
  Id      Date                Code
   1       10/20/2018      325
   1       10/20/2018      325
   1       10/20/2028      405

I would like to add a counter based on all three variables so that I can join this with other DataFrame
Desired output
 Id      Date                Code     Counter
   1       10/20/2018      325         1
   1       10/20/2018      325         2
   1       10/20/2028      405         1

I tried the following
 df1.groupby(['id','Date','Code']).size()

It's not giving me the desired output. Appreciate your help

A: Does this get you what you want? cumcount gives the cumulative count within the group for each row.
 df['cumcount'] = df.groupby(['Id','Date','Code']).cumcount()


text:
Q: Two-way ANOVA main effect and interaction query I have a MINITAB printout I was hoping someone could help me with.  My question is- from the table below how do I distinguish between a main effect and an interaction?
Study: Three drug treatments are compared at three sites. The treatments consist of two dosages (low and high dose) of an experimental drug and a control drug. The results were analysed by two-way ANOVA with interaction. The ANOVA is shown below (formatting improved).
Analysis of Variance for response

Source       DF         SS         MS       F      P
site          2     21.301     10.651    0.47  0.656
dose          2    185.404     92.702    4.09  0.108
site*dose     4     90.654     22.663    7.05  0.000
Error        63    202.574      3.215
Total        71    499.933

A: site*dose is the interaction effect, site and dose are the main effects. Since the interaction effect is significant at a 5% level (p-value < 0.05). Thus, you need to test the simple effects in the next step.


text:
Q: Counterexample of semisimple modules I'm studying semisimple modules and I found a result in Anderson-Fuller (Proposition 9.4) which says that if
$$ 0 \to N \to M \to M/N \to 0$$
is an exact sequence of modules and $M$ is semisimple, then $N$ and $M/N$ are semisimple. I'm guessing the converse is not true (otherwise I guess it would have been stated in the text) and I'm looking for a counterexample for that, but I don't know were to look. Can anyone give me some guidance? Please DO NOT post a counterexample.

A: Hint:
Look at submodules of $R=\Bbb Z/4\Bbb Z$ as a module over $R$.

A: Found it! In $\mathbb{Z}$-Mod, take $p$ prime, then:
$$0 \to \mathbb{Z}_p \to \mathbb{Z}_{p^2} \to \mathbb{Z}_{p^2}/\mathbb{Z}_p \cong \mathbb{Z}_p \to 0$$
and $\mathbb{Z}_{p^2}$ is not semisimple since $\mathbb{Z}_p$ is not a direct summand (that would imply $\gcd(p, p) = 1$, which is false).
Suppose $\mathbb{Z}_{p^2} $ is semisimple, then the above sequence splits and we have
$$ \mathbb{Z}_{p^2} \cong \mathbb{Z}_{p} \oplus \mathbb{Z}_{p}$$
and this is true if and only if $\gcd(p,p)=1$ and $p^2 = p \cdot p$, which is false.


text:
Q: Java: Restrict the mouse movement to vertical Is there a way to restrict the mouse movement to vertical? I am currently developing a program when user dragging mouse pointer to the left or right in specific rectangle shape cursor can't move but up and down movements should work.

A: you can try like this,f is reference to a Jframe but here the X co-ordinate is fixed.
final Robot r=new Robot();
f.addMouseMotionListener(new MouseMotionListener(){
        @Override
        public void mouseDragged(MouseEvent e) {
        }

        @Override
        public void mouseMoved(MouseEvent e) {

              r.mouseMove(20, e.getY());
        }
    });


text:
Q: Difference between Descretization and Fitted value iteration in Reinforcement Learning I'm studying reinforcement learning from Prof. Andrew Ng's lecture notes. Here I came across fitted value iteration algorithm for continuous state MDP. It's mentioned that in this algorithm, we are approximating the value function $V(s)$, over a finite number of states ($s^{(1)}, s^{(2)}... s^{(m)}$) using supervised learning algorithm like linear regression.
Why we need to sample a finite set of states from continuous states? If we are sampling the continuous states, doesn't it mean descretization of states?
Also what is the intuition behind the sampling of states and then using supervised learning algorithm to get value function? Why can't we simply use following equation for Value function $V(s)$?
$$V(s) = R(s) + {\gamma}\max_{a}\int_{s'}P_{sa}(s')V(s')ds'$$

A: Because you usually don't have access to $P_{sa}$, and even if you did the resulting equation hardly seems tractable.

A: If the state space is high-dimensional, then as explained earlier in the notes, it is not possible to estimate the value function at every discretized state due to the curse of dimensionality.
What we instead do is assume that the value function is given by a linear function of the (kernelized) state: $V(s) = \theta^T \phi(s)$, and then estimate $\theta$ using linear regression from a few state samples.


text:
Q: Reading numeric data from delimited files When reading delimited files on SAS, one can set the length of character variables by using length statement. However, one cannot do that with plain numbers, (no commas, no dollar signs, standard data etc.). The only way to set the length of such statements inherently from what I could think of is by using a commaw. informat. Is this plausible, is there a length statement if we wanted to read just plain numbers?
I was also wondering, if I have a piece of data "$105.93", I can read it as dollar3.2. But reading it as dollar12.2 doesn't seem to make a difference. Why?
Thank you.

A: Variable length and format width are independent things
The LENGTH is how many bytes SAS uses to store the data in the dataset. Since SAS uses 64 bit floating point numbers the length of a numeric variable must be between 3 and 8 bytes. (You can actually store numbers in as few as 2 bytes on IBM mainframes since they used a different floating point representation.)  The WIDTH used by a format or informat is how many characters it takes to print the value as text.  So if you are reading or writing a string like $1,205.93 you will need to use 9 characters. But since it is a number you will want to store it with 8 bytes.  So the LENGTH is 8 even if the format width is longer than that.
List mode input ignores informat widths
The second confusion is that when you are using list mode INPUT (rather than formatted mode) then SAS will ignore the width specified on any informat that you might have attached to a particular variable. Instead it will apply the informat to all of the next word that it sees before the next delimiter.  You could consider that it adjusts the informat width to match the width of the data.  So if ran a program like this:
data want ;
  input id cost ;
  informat cost comma1. ;
cards;
1 $103.93
;

COST will get set properly because the width of 1 specified in the informat statement is ignored.  Note that the same thing applies when using the : modifier to allow the informat specification to be inserted into the INPUT statement without causing SAS to switch from list mode to formatted mode.
Misuse of the decimal part of an informat specification
On a FORMAT the decimal specification tells SAS how many digits to the right of the decimal place to print. But when you add a decimal specification on an INFORMAT you are telling SAS where to place the decimal point when the input string does not have one.  Basically you are telling SAS what power of 10 to use to divide any integer values that it sees.  So unless you are positive that your input stream intentionally eliminated the periods between the ones and tenths places you should never specify any decimal value for a INFORMAT.  So you wouldn't want to use the DOLLAR12.2 informat.  (Note also that there is no difference between the DOLLAR. and COMMA. informats. Both remove commas and dollar signs before trying to translate the string into a number.)

A:
When reading delimited files on SAS, one can set the length of character variables by using length statement. However, one cannot do that with plain numbers, (no commas, no dollar signs, standard data etc.).

You can specify the length of numeric variable, but length corresponds to the number of bytes a variable can store. For numeric, a byte stores more than a single digit.
http://support.sas.com/documentation/cdl/en/hostwin/69955/HTML/default/viewer.htm#n04ccixfia6l2pn1f8szvttqg3hm.htm
Here's an example that shows how it's saved.
data have;
    infile cards dlm=';';
    length V1 V2 8 V3 4;
    informat V1 dollar3.2 V2 best12. V3 dollar8.2;
    format v1 dollar12.2 v2 8. v3 dollar8.2;
    input v1 v2 v3;
    datalines4;
$12.22; 24; $1342
$145.22; 25; $13.42
$45.01; 22; $100.1
;;;;
run;

proc contents data=have;
run;


text:
Q: Kedro documentation does not show up all functions after compiling kedro build-docs I tried documenting my project using kedro build-docs command.
.
├── docs
└── src
    ├── setup.py
    ├── tests
    ├── <project>
    │   ├── __init__.py
    │   ├── __main__.py
    │   ├── __pycache__
    │   ├── a
    │   ├── hooks.py
    │   ├── pipeline_registry.py
    │   ├── pipelines
    │   │   └── pipeline.py
    │   ├── settings.py
    │   ├── b
    │   └── c
    |_

a, b and c are different modules inside project and I am trying to document using sphinx. I compiled kedro build-docs command in terminal and it generates .rst files inside the docs directory and creates docs/build/**/index.html file. Upon opening this I find all my modules listed as hyperlink, and upon going inside a module, I find not all functions were documented.
For example if I have 3 functions listed inside module a , the html shows up only 2 and rest are not shown up on html page.
Need help to show up all functions doc strings.


text:
Q: Storing a list in mysql that can be reordered To describe an NFS mount in a Database I have the following tables (simplified):
NFS_Export: id (PK), name, path
NICs: id (PK), name
NFS_Export_NIC_priorities: id (PK), nfs_export_id (FK), nic_id (FK)

My problem is that the NICs used for an NFS export are a list where the order gives the priority and the user must be able to change that order.
Currently I order the NICs by the NFS_Export_NIC_priorities id. The lower the id the higher the priority. But that means to resort the order I have to swap two or more entries which sounds like a bad idea.
Is there a better way to store a list where the order matters and is changable?


text:
Q: Nested iterators access I have a question about iterators.The question is:" How can I access ( if it's a nested iterator ) the element in row, that is higher or below.Here's an example what I mean:
for( auto i = graphMatrix.begin();i != graphMatrix.end();i++ )
{
    for( auto j = i->begin();j != i->end();j++ )
    {
        if( *j == 'O' )
        {
          // here we must analyze an element which is a row higher or lower
        }
    }
}

Next thing is what I wanted to do ( but it's with vector ):
 for( int i = graphMatrix.size();i < graphMatrix.size();i++ )
{
    for( int j = graphMatrix.size();j < graphMatrix.size();j++ )
    {
        if( graphMatrix[i][j] == 'O' )
        {
           graphMatrix[j][i] == 'X';
        }
    }
}

I know that vector has fast size function, but to generalize the code, in my mind, it's better to use iterators ( as my mentor said ).So how can I do the same stuff with iterators as with vectors?

A: Since iterators are non-numeric, they are not well-suited to this problem.
You can write complex, confusing and possibly costly code with std::distance and std::advance, performing "pointer arithmetic" on your iterators... or you can stick with your numeric loop counters approach, which is precisely what I'd do. Especially seeing as you're using vectors, which have constant-time (and, let's face it, immediate) access to arbitrary elements in arbitrary positions.
If you're wondering why, in this case, iterators are suddenly not the "better" mechanism for iteration that you've been taught they are: it's because one must use the correct tool for the job, and no technology is the correct tool for all jobs.

A: to get the position of you vector from the iterator with std::distance:
for( auto i = graphMatrix.begin();i != graphMatrix.end();i++ )
{
    for( auto j = i->begin();j != i->end();j++ )
    {
        int x = std::distance(graphMatrix.begin(),i);
        int y = std::distance(i->begin(),j);

        graphMatrix[x][y] = 'x';

    }
}


text:
Q: WindowsUI Composition OriginateException in CreateEffectFactory I'm getting a lot of exceptions thrown in my app from the Win2d libraries, I'm trying to apply a blur to a background of an element on the load event.
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        var visual = ElementCompositionPreview.GetElementVisual(this);
        this.backgroundContainer.Size = new Vector2((float)this.backgroundGrid.ActualWidth, (float)this.backgroundGrid.ActualHeight);

        // Create background color
        this.backgroundColorSprite = visual.Compositor.CreateSpriteVisual();
        this.backgroundColorSprite.Size = this.backgroundContainer.Size;
        var darkColor = App.DynamicThemeing.BaseThirtyColor.GetValueOrDefault(Colors.Transparent);
        darkColor.A = 215;
        this.backgroundColorSprite.Brush = visual.Compositor.CreateColorBrush(darkColor);
        this.backgroundContainer.Children.InsertAtBottom(this.backgroundColorSprite);

        // Create the blur effect to be used.
        var blurEffect = new GaussianBlurEffect
        {
            Name = "Blur",
            BlurAmount = 10.0f,
            BorderMode = EffectBorderMode.Hard,
            Optimization = EffectOptimization.Balanced,
            Source = new CompositionEffectSourceParameter("source")
        };
        var effectFactory = visual.Compositor.CreateEffectFactory(blurEffect, new[] { "Blur.BlurAmount" });
        var effectBrush = effectFactory.CreateBrush();
        effectBrush.SetSourceParameter("source", visual.Compositor.CreateBackdropBrush());
        this.backgroundBlurSprite = visual.Compositor.CreateSpriteVisual();
        this.backgroundBlurSprite.Brush = effectBrush;
        this.backgroundBlurSprite.Size = this.backgroundContainer.Size;
        this.backgroundContainer.Children.InsertAtBottom(this.backgroundBlurSprite);
    }

Stack trace:
https://1drv.ms/t/s!Ag5-nrX1qf58s6ZrQtwxHXl50oMulQ


text:
Q: Getting value from a nested xml with attributes using minidom and etree I have the following xml data:
<response>
   <status>ok</status>
   <message>Done</message>
   <local-data>
      <name>
         <attribute key="first">John</attribute>
         <attribute key="middle">Maverick</attribute>
         <attribute key="last">Doe</attribute>
      <name>
   </local-data>
</response>

How would one extract the value of "first" or "middle" from the xml using minidom and any other methods?

A: This code should help
dom1 = parseString(xml_text)
elements = dom1.getElementsByTagName("attribute")
for element in elements:
    if element.getAttribute('key') == "first":
        print(element.firstChild.nodeValue)


text:
Q: Replacing vector with array or static vector for a better approach My application runs particular number of processes(different executables) using createprocess(windows api) in parallel(using threads). User can refresh / close my application at any time. As of now, I am pushing the process handles into vector and whenever close request received, I am iterating the vector and terminating(using GetExitCodeProcess and TerminateProcess APIs) and closing(using CloseHandle API) the process handles. Also I am closing the handle of the process when it is completed. The problem with current model is, whenever process completed handle will be closed and when close request received again I will try to close it using vector(handle is not updated). To solve this, I have to update/remove the handle in/from the vector. To do this, need to maintain index.
Since I know the number of process, I want to create a static vector and update it rather than pushing a local object to a vector. Can someone suggest a best approach.
Below is the sample code.
//member object
std::vector<PROCESS_INFORMATION> mProcessHandles;

//this is a thread and will be called multiple times with different executable names in the application
void method(std::string executable)
{
    STARTUPINFO startInfo{};
    PROCESS_INFORMATION procInfo{};
    bool ret  = CreateProcess(NULL, executable, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &startInfo, &procInfo);
    mProcessInfo.push_back(procInfo);
    if(ret)
    {
        WaitForSingleObject(procInfo.hProcess, INFINITE);
        CloseHandle(procInfo.hProcess);
        procInfo.hProcess = NULL;
        CloseHandle(procInfo.hThread);
        procInfo.hThread = NULL;
    }
    return;
}

//this will be called when application close requested
void forceKill()
{
    for (auto &processHandlesIt : mProcessHandles)
    {
        DWORD errorcode = 0;
        GetExitCodeProcess(processHandlesIt.hProcess, &errorcode);
        if (errorcode == STILL_ACTIVE)
        {
            TerminateProcess(processHandlesIt.hProcess, errorcode);
        }
        CloseHandle(processHandlesIt.hProcess);
        processHandlesIt.hProcess = NULL;
        CloseHandle(processHandlesIt.hThread);
        processHandlesIt.hThread = NULL;
    }
}

A: You should not use handles (in GetExitCodeProcess for example) after they are closed.
I would simply not close those process handles in the threads, and just leave them for the forceKill or other clean-up function to close.
Also, since you are not using procInfo.hThread, you could close it right after CreateProcess returns.
I guess you are not using any other members of the procInfo, so you could only store the process' handles in your vector.


text:
Q: Mechanism of Adversarial Multi-Armed Bandit Problem? I am studying the Bandit Algorithms book by Tor Lattimore and Csaba Szepesv´ari and I have studied the adversarial bandit problem. However, I don't understand what is the mechanism of adversarial bandit problem. The book says that regret of deterministic policies is linear because, in adversarial bandits, we assume that we will our policy to adversary and he will choose the reward based on our policy. Therefore, the regret would be linear. In this setting, does it mean that we would say that for example, we will always play arm 2 or just we play a deterministic policy? I would be thankful if someone can explain the mechanism of the adversarial bandit and also its contextual form.
Moreover, I am wondering why the regret for the contextual bandit is defined as follows:
$$R_{n}= \mathbf{E} \left[ \sum_{c \in C} \max_{i \in [K]} \sum_{t \in [n]: \: c_t=c} (x_{it}-X_t) \right]$$
Does it mean that the same contextual information should be applied for all periods?
I thought that regret should be defined as follows:
$$
R_n= \mathbf{E} \left[ \max_{i \in [k]} \sum_{t \in [n]} \max_{c_t \in C} (x_{it}-X_{t})
\right]
$$

A: In an adversarial bandit setting, it is assumed that the reward distributions are fixed in advance by an adversary and are kept fixed during the interaction. This means that for the same action, you could have completely different rewards for different rounds (so it's not deterministic to reply to your question).
The assumption on the linearity of the reward is not necessary for the adversarial setting and, in principle, one could choose another parametrization for the reward.


text:
Q: How can I add a script launcher to the top bar? I have a Ruby script, which starts a server and opens a browser. It runs without any problems when called from terminal, but when I try to add a launcher to the top bar of the classic GNOME desktop, with the properties set as in the picture below, and click on it, the program does not run.
How can I add a launcher to the tap bar?

A: Shouldn't the generic Command to run a script/executable be language-interpreter path_to_application instead of path_to_application?
I'm not familiar with ruby, but I suppose it would give ruby path_to_application in your case.


text:
Q: Freeradius and external script authentication with CHAP / MS-CHAP I am using Freeradius to authenticate users via an external script as shown here, that returns Accept or Reject when passed a username and password pair.
authorize{
    update control {
        Auth-Type := `/usr/bin/php -f /etc/raddb/yourscript.php '%{User-Name}' '%{User-Password}' '%{Client-IP-Address}'`
    }

This works properly as expected when the client is using PAP. The password is sent in %{User-Password}.
However when using CHAP or MS-CHAP it does not work, as %{User-Password} remains empty.
How can I get the plaintext password to send to my script? Alternatively, is there any other way to support CHAP/MS-CHAP?

A: The %{CHAP-Password} field contains a hash of the password and the challenge, which is some magic number.
The %{CHAP-Challenge} field contains the challenge used in that session.
While you can't get the plain-text password from this in a straightforward realtime way, if you have the plaintext password you can hash it with the CHAP-Challenge as shown here using md5. This should then be equal to your CHAP-Password value.


text:
Q: Having pages after specifying post_type post I want to loop through all posts in category 4,but why is there still pages in the result after specifying post_type post?
$homeNeWs = new WP_Query(array(
       'post_type' => 'post',
       'posts_per_page' => 6,
       'cat' => 4
));
while ($homeNeWs->have_posts()) : $homeNeWs->the_post();

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php
endwhile;

wp_reset_postdata();
?>

I did add a function to make pages have categories and tags,base on http://spicemailer.com/wordpress/add-categories-tags-pages-wordpress/
function taxo_for_page() {
  register_taxonomy_for_object_type('post_tag', 'page');
  register_taxonomy_for_object_type('category', 'page');
}

add_action('init', 'taxo_for_page');

if (! is_admin()) {
add_action('pre_get_posts', 'cat_n_tag_archives');
}

function cat_n_tag_archives($wp_query) {
  $ary_one = array('post', 'page');
  if ($wp_query->get('category_name') || $wp_query->get('cat'))
    $wp_query->set('post_type', $ary_one);
  if ($wp_query->get('tag'))
    $wp_query->set( 'post_type', $ary_one );
}

Do i need to add more thing for the code above?

A: Your cat_n_tag_archives() function is adding pages to all category and tag results indiscriminately. What you probably want (and I am guessing a little) is to restrict that filter to the main query only:
function cat_n_tag_archives($wp_query) {
  if (!$wp_query->is_main_query()) return; // This bit checks for the main query
  $ary_one = array('post', 'page');
  if ($wp_query->get('category_name') || $wp_query->get('cat'))
    $wp_query->set('post_type', $ary_one);
  if ($wp_query->get('tag'))
    $wp_query->set( 'post_type', $ary_one );
}


text:
Q: How to target Clientapp file if its outside currentdirectory ASP.NET CORE WEB API ANGULAR 8 How do I make my webApi run my client app if the folder is outside the webapi folder ?
/repos/project/webApplication is the main folder , inside it has two more.
The webapi vs project /repos/project/webApplication/webApplication
The client app /repos/project/webApplication/clientApp
My code now :
app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "/clientApp";

            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });


text:
Q: Getting data out of Marketing Cloud We've set up a method of updating data in Marketing Cloud (keeping it as up to date as possible via transfers every 15 mins). I want to start getting the Data View stuff out with the same kind of frequency - any ideas?
It looks like the dataextract activities can only be run every hour (and with a rolling 1 day time span meaning a bunch of duplication) has anyone found or can anyone think of a better solution?

A: 3 options:

*

*setup 4 automations to run data extract activities and scheduled them to run hourly at 15 minute intervals.

*consider retrieving data via API and using external service to schedule requests (e.g. every 15 minutes).

*trigger automation externally - following is example of how to make request https://github.com/mattcam/Salesforce-Marketing-Cloud-Developer-Edition-Recipes/blob/master/starting-an-automation.md


text:
Q: i am using ajax but it show method not support i check but method is same in ajax and in route I am trying this but it show me this
The POST method is not supported for this route. Supported methods: GET, HEAD.
Route
'''
Route::get('/','EmployeeController@index');
Route::post('employee.store','EmployeeController@store')->name('employee.store');

'''
Ajax
'''
$(document).ready(function(){
$('#insert_form').on('submit',function(e){
event.preventDefault();
$.ajax
({
type:"POST",
url:"{{route('employee.store')}}",
data:new FormData(this),
dataType: 'json',
success: function(data)
{
alert();
window.location.reload();
}
});
});
})

'''
blade
'''
<form action="" id="insert_form" method="post">
@csrf

<input type="text" class="form-control" placeholder="Name" name="name">

<input type="email" class="form-control" name="email" placeholder="Email Address">

</form>

'''

A: Pls modify your POST route:
// Routes should not contains dots.
Route::post('/employees','EmployeeController@store')->name('employee.store');


text:
Q: Binding viewmodel to view has usercontrol with own viewmodel I have a UserControl 'UserControlA' with ViewModel 'ViewModelA'.
'UserControlA' has 'UserControlB', and 'UserControlB' has 'ViewModelB'.
When I bind a DependencyProperty in 'UserControlA' with 'ViewModelA' property,
there is none of setter fired.
Belows are code,
ViewA.xaml
<UserControl
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:vm="clr-namespace:MyTest.ViewModel
         xmlns:custom="clr-namespace:MyTest.Views
         x:Name="userControl" x:Class="MyTest.Views.UserControlA"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="500">

<UserControl.DataContext>
    <vm:UserViewModel x:Name="uvModel"/>
</UserControl.DataContext>
<Grid>
<custom:UserControlB></custom:UserControlB>

ViewA.cs
public partial class UserView : UserControl, IUserView
{
    static DependencyProperty UserTypeProperty = DependencyProperty.Register("UserType", typeof(UserType), typeof(UserView), new PropertyMetadata(UserType.None));
    public UserType UserType { get { return (UserType)GetValue(UserTypeProperty); } set { SetValue(UserTypeProperty, value); } }
    public ViewA()
    {
        InitializeComponent();

        Binding typeBinding = new Binding();
        typeBinding.Source = this.DataContext;
        typeBinding.Path = new PropertyPath("User.UserType");
        typeBinding.Mode = BindingMode.OneWayToSource;
        this.SetBinding(UserTypeProperty, typeBinding);
    }

ViewModelA.cs
public class ViewModelA : ViewModelBase
{

    User user = new User();
    public User User
    {
        get { return this.user; }
        set
        {
            this.user = value;
            RaisePropertyChanged(() => User);
        }
    }

Please help me out from this problem.

A: The line
typeBinding.Source = this.DataContext;

is redundant, because the DataContext is implicitly used as source object of the Binding.
However, during the execution of the UserControl's constructor the DataContext property is not yet set (i.e. it is null), so you are effectively setting the Binding's Source property to null. Just remove that line, or write
SetBinding(UserTypeProperty, new Binding
{
    Path = new PropertyPath("User.UserType"),
    Mode = BindingMode.OneWayToSource
});


text:
Q: With DBeaver, MariaDB Optimizer Trace a result irrelevant to the concerned query With a non-root user on 10.5.18-MariaDB, we are trying to get the optimizer trace about the SQL query select * from eav_value ev; however, the result seems to be irrelevant, saying something about select database() AS DATABASE():
{
  "steps": [
    {
      "join_preparation": {
        "select_id": 1,
        "steps": [
          {
            "expanded_query": "select database() AS `DATABASE()`"
          }
        ]
      }
    },
    {
      "join_optimization": {
        "select_id": 1,
        "steps": []
      }
    },
    {
      "join_execution": {
        "select_id": 1,
        "steps": []
      }
    }
  ]
}

We also tried to get the optimizer traces for other queries but got the same result as above, regardless of the query.
If change to use the CLI connection, the system behaviour is OK. We prefer the GUI tools, e.g. DBeaver, though.
We are learning how to use the optimizer trace, so we wonder if we missed anything.
The commands used in the test:
select @@version
;
show create table INFORMATION_SCHEMA.OPTIMIZER_TRACE
;
set session OPTIMIZER_TRACE = "enabled=on"
;
select * from eav_value ev
;
select * from information_schema.OPTIMIZER_TRACE
;
set session OPTIMIZER_TRACE = "enabled=off"
;

A: DBeaver uses MariaDB Connector/J. It looks like this driver disconnects after completing the query.
Therefore, when getting for the optimizer trace, it is not the same session as the query before. The optimizer trace depends on the session.
We are still open to suggestions about how to keep DBeaver hold on to the same session and not to disconnect after each query.


text:
Q: AWK to replace HTML tag with another and keep text I am looking for a way to replace a HTML tag with another, but keep the text.
I have a big HTML file, which contains:
fork

I want to replace  tag with  tag:
fork

Tool doesn't really matter, but I am looking for a CLI way to do it.
I am not looking for a HTML processor, because input is a text file with some HTML code in it (not a clean/valid HTML) and I am manually working with the output (copy, modify, use later in its final place). I just want to save some time with the replace.

A: Consider using Python and a tool like BeautifulSoup to handle HTML. Trying to parse HTML with other tools like sed or awk can lead to terrible places.
As an example:
from bs4 import BeautifulSoup
soup = BeautifulSoup('
fork')
for spanele in soup.findAll('span'):
    spanele.name = 'p'
html_string = str(soup)
print(html_string);

That's lightweight and pretty simple and the html is handled properly with a library that is specifically built to parse it.

A: Don't use AWK for processing HTML files. If you can turn your HTML file into an XHTML file, you can use xsltproc for an XML transformation as follows:
trans.xsl file:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" indent="yes" encoding="utf-8"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="span[@class='desc e-font-family-cond']">
    <xsl:apply-templates/>
  </xsl:template>

</xsl:stylesheet>

CLI command for invoking xsltproc, which has to be installed, obviously:
xsltproc trans.xsl file.html

The standard output of this command is the corrected HTML file as you want to have it.

A: Using sed:
sed 's,<\(\/\)\?span\(\s\)\?,<\1strong\2,g'
$ echo 'fork' | sed 's,<\(\/\)\?span\(\s\)\?,<\1strong\2,g'
fork

A: I would use GNU sed for this task following way, let file.txt content be
fork

then
sed -e 's/]*>//g' -e 's/<\/span>/<\/strong>/g' file.txt

output
fork

Explanation: firstly replace span starting using , secondly replace span closing using .


text:
Q: does Netbeans Create "equals" method correctlly? When creating an entity from Database, Netbeans creates equals method:
    public boolean equals(Object object){
       if(!(object instanceof Department)){
          return false;
       }
       Department other = (Department) object;
       return !(
                 (this.id == null && other.id != null) ||
                 (this.id != null && !this.id.equals(other.id))
               );
    }

And return statement according to:
~((A ∧ ~C) ∨  (~A ∧  ~B)) → (~A ∨ C) ∧  (A ∨ B) → (C ∨ B)
Equals to:
(other.id == null) || (this.id.equals(other.id))

1. Is this correct or should i change it to:
(this.id != null) && (this.id.equals(other.id))

2. Should i use a number like 10, instead of auto increment id in hashCode method ?
3. should a Natural Id or business id be immutable completely or can be changed. i mean, should i define a setter method for it?

A: [UPDATE] Netbeans created the method correctly, as you can see it uses ! in the comparison, that is why he uses OR and !equals inside:
return !(
         (this.id == null && other.id != null) ||
         (this.id != null && !this.id.equals(other.id))
       );

So, following the implementation for Objects.equals (since 1.7) this would be preferable:
(this.id != null) && (this.id.equals(other.id))

And instead of this code for equals and hashCode, you could have:
import java.util.Objects;

@Override
public boolean equals(Object object) {
    if (this == object) return true;
    if (object == null || getClass() != object.getClass()) return false;
    Department department = (Department) object;
    return Objects.equals(id, department.id);
}

@Override
public int hashCode() {
    return Objects.hash(id);
}

Here it is the implementation that Objects.hash calls in the end:
public static int hashCode(Object a[]) {
    if (a == null)
        return 0;

    int result = 1;

    for (Object element : a)
        result = 31 * result + (element == null ? 0 : element.hashCode());

    return result;
}

*About the hashCode method, it is good to use the same fields as you use in the equals.
Here, try to use fields that identify the entity as one, for example:

*

*the field name it is unique, then use the name.

*the field name and number are unique, then use both.

*Once the object was created, you shouldn't have a setter for your Id field. You can have a constructor where you receive it instead to use in unit tests but not a setter. Immutable objects are a good approach to follow, but if you can't, at least the field that identifies the instance shouldn't change.
Hope I could help.


text:
Q: connect to rethinkdb running in docker kitematic I'm trying to set up a local rethinkdb on a docker container using kitematic. However, the connection always times out (RqlDriverError: Handshake timedout). Is there additional setup that I need to do to? Any other advice is appreciated!
Rethinkdb container is running on the following ports:
(Docker port --> Mac port)
8080  --> 192.168.99.100:49155
28015 --> 192.168.99.100:49153
29015 --> 192.168.99.100:49154

Here's my setup:
r.connect({
  host: '192.168.99.100'
, port: 49155
, timeout: 10
}, function dbConnect (err, conn) {
  if (err) {
    throw err
  }
  else {
    console.log('ahoy!')
  }
})

A: The problem is that your client driver version is different from your server driver version. You have to update both


text:
Q: Issue with table spacing I've set-up a table that populates based on a stored procedure that runs.  The width of the div that the table is contained in is 96% of the page.  The width of the table is 100%.  The problem that I'm having is when I have two-three items populate the table there is a massive space in-between the items.  I specify the space in the table, but that isn't working.  I'm also having issues with the font being black.  I took all the CSS out that pertained to  hyperlinks, but it's still not displaying the correct font color.  Any suggestions?
 Dim con5 As New SqlConnection
    Dim cmd5 As New SqlCommand
    Dim index As Integer = 0
    Dim dt1 As New DataSet

    con5.ConnectionString = ConfigurationSettings.AppSettings("ConnectionString")
    con5.Open()
    cmd5.Connection = con5
    cmd5.CommandType = CommandType.StoredProcedure

    cmd5.CommandText = "ProductBreakdown"

    cmd5.Parameters.Add(New SqlParameter("ProductID", SqlDbType.Int)).Value = Session("Product")
    cmd5.Parameters.Add(New SqlParameter("DesignName", SqlDbType.VarChar, 50)).Value = Request.QueryString("o")

    Dim da1 As SqlDataAdapter = New SqlDataAdapter(cmd5)
    da1.Fill(dt1)

    Dim table1 As New HtmlTable

    Dim numells As Integer = 6

    dv = New DataView(dt1.Tables(0))
    Dim tablestring = ""
    Dim strTable As New StringBuilder()
    Dim rowIsOpen As Boolean = False
    Dim itmCounter As Integer = 0
    strTable.Append("
 ")

    For Each dr As DataRowView In dv

        Dim crossover As String = dr("CrossoverID").ToString()
        Dim picid As String = dr("Description").ToString()
        Dim picdescrip As String = dr("DesignColor").ToString().ToUpper()
        Dim collectionname As String = dr("CollectionDescription").ToString().ToUpper()
        Dim designinfo As String = dr("DesignName").ToString()
        Session("Collection") = dr("CollectionDescription").ToString()
        'collectionname.ToUpper()
        ' For every 5 items create a new row.
        If itmCounter Mod 4 = 0 Then
            ' Since we want new row, first close any open row
            If rowIsOpen Then strTable.Append("
")

            ' Start a new row and mark row as open so we can keep track
            strTable.Append("
")
            rowIsOpen = True
        End If

        strTable.Append("")
        strTable.Append("

")
        strTable.Append("<color=Black>" & collectionname & "
")
        strTable.Append(picdescrip & "	")

        itmCounter += 1

    Next
    ' Next

    ' Make sure we close any open rows
    If rowIsOpen Then strTable.Append("
")

    If strTable.Length > 0 Then
        product.InnerHtml = "
" & _
            strTable.ToString() & _
            "
"
    End If

A: Tables have a specific role in HTML but you may want to use DIVs in this circumstance.  DIVs will automatically float and reposition themselves based on the width of the browser.
Here is a example in jsFiddle
HTML

The preferred developer response

    ...

Other emotions

...

CSS
.table {
    margin-left: 50px;
    margin-right: 50px;
}
.banner {
    padding: 10px;
    margin-top: 20px;
    clear: both;
    background-color: #336699;
    color: white;
    font-weight: bold;
}
.cell {
    width:   150px;
    float: left;
}

Your code may look like this
Dim con5 As New SqlConnection
Dim cmd5 As New SqlCommand
Dim index As Integer = 0
Dim dt1 As New DataSet

con5.ConnectionString = ConfigurationSettings.AppSettings("ConnectionString")
con5.Open()
cmd5.Connection = con5
cmd5.CommandType = CommandType.StoredProcedure
cmd5.CommandText = "ProductBreakdown"
cmd5.Parameters.Add(New SqlParameter("ProductID", SqlDbType.Int)).Value = Session("Product")
cmd5.Parameters.Add(New SqlParameter("DesignName", SqlDbType.VarChar, 50)).Value = Request.QueryString("o")

Dim da1 As SqlDataAdapter = New SqlDataAdapter(cmd5)
da1.Fill(dt1)

dv = New DataView(dt1.Tables(0))

Dim strTable As New StringBuilder()
Dim itmCounter As Integer = 0
strTable.Append("
 ")

For Each dr As DataRowView In dv

    Dim crossover As String = dr("CrossoverID").ToString()
    Dim picid As String = dr("Description").ToString()
    Dim picdescrip As String = dr("DesignColor").ToString().ToUpper()
    Dim collectionname As String = dr("CollectionDescription").ToString().ToUpper()
    Dim designinfo As String = dr("DesignName").ToString()
    Session("Collection") = dr("CollectionDescription").ToString()

    strTable.Append("
")
    strTable.Append("

")
    strTable.Append("<color=Black>" & collectionname & "
")
    strTable.Append(picdescrip & "
")

    itmCounter += 1

Next
strTable.Append("
")
product.InnerHtml = strTable.ToString()

Same great taste but fewer calories


text:
Q: R: Create RasterLayer object from a dataframe with long & lat & altitude values I have a data.frame list with 3 columns (Col 1: Long, col 2: Lat, col 3: Altitude) and 1095 rows. I want to change this data.frame to the RasterLayer formula. What should I do next? Anything which help will be greatly appreciate!!
It is a grid cell (1 * 1 degree,Long & Lat) of China with elevation values, Thank you for your time and help!
Tao Liang

A: You can probably use rasterFromXYZ
Example data
library(raster)
r <- raster(nrow=5, ncol=5, xmn=0, xmx=10, ymn=0, ymx=10, crs="")
set.seed(1)
values(r) <- sample(1:25)
r[r < 15] <- NA
xyz <- rasterToPoints(r)

Solution
rst <- rasterFromXYZ(xyz)

Or with terra
library(terra)
x <- rast(xyz, type="xyz")


text:
Q: Mapkit Point Arrow Indicator in iOS Map I use MapKit to view the map and put the annotations. I need an arrow which will point from blue dot to selected annotation with specified coordinates. When blue dot moving as user moving, the arrow will rotating and still pointing to the selected annotation in degree. It is not road navigation (like using MKPolyline) but just an arrow pointing to selected point.
Looks like I know how to share this image for more clear explanation:


text:
Q: Arel and ransack, custom ransacker for sorting on average ratings I am new to both ransack and arel, and not having luck with getting this to work.
I am trying to make custom ransacker on Tehnician model so I can sort by average rating on technicians index table. I am using ransack sort_link.
I have this relationship
class Technician
  has_many :ratings, as: :rateable
end

and
class Rating
  belongs_to :rateable, polymorphic: true
  validates :value, numericality: { in: 1..5, allow_nil: true }
end

I need to sort by average of technician.ratings value attribute
This was my best try, and it does not work. I am getting PG::CardinalityViolation: ERROR:  more than one row returned by a subquery used as an expression
ransacker :average_rating do
  Technician.arel_table.project(Rating.arel_table[:value].average)
                       .join(Rating.arel_table)
                       .on(Rating.arel_table[:rateable_id]
                       .eq(Technician.arel_table[:id]))
                       .group(Technician.arel_table[:id])
end

As a temporary solution I added scopes on model
scope :sort_by_ratings_asc,  -> { left_outer_joins(:ratings).group('id').order('AVG(ratings.value)')}
scope :sort_by_ratings_desc, -> { left_outer_joins(:ratings).group('id').order('AVG(ratings.value) desc')}

Using :ratings as attribute.
It works, but there is another issue, records without ratings are sorted as first. Not sure how to use COALESCE there.
Thanks in advance. Minor explanation would be awesome.


text:
Q: TeXStudio: redefined newcommand variant has bad error highlighting I would like to use the following command in my LaTeX code
\newcommand{\newsym}[2]{\newcommand{#1}{\ensuremath{#2}}}

so that I can easily define new symbols that I often use in my equations, such as:
\newsym{\kTq}{\frac{k_BT}{q}}.

The intent being to reduce the amount of typing necessary to define new symbols and to enhance readability of the code.
The problem now is twofold:

*

*TeXstudio dosn't realize my \newsym defines a new command and complains that the first argument (\kTq) is an uncrecognized command.

*It also doesn't realize the second argument is eventually enclosed in an \ensuremath environment and complains math command outside math environment
As a result I have my \newsym definitions cluttered with bad-syntax highlighting, impeding the readability, which was the entire half of the purpose of defining \newsum in the first place.
Can I solve this dilemma by somehow adjusting the way TeXstudio does the error highlighting in this particular case? I don't wan't to disable the highlighting altogether; they are otherwise useful.
Or is there a smarter alternative to my definition of \newsym that avoids this problem?

A: How to create a custom .cwl-file for TXS:

*

*Open any ASCII-Text editor of your choice, e.g. vi, Notepad++. Alternatively: use TXS.

*Create and save a new text file with the file extension .cwl. If created for a package, the .cwl-file needs to be named in compliance to the package name.

*Add all commands you created as follows:
#<author> <date>
\<command>{<arguments>}
\begin{<environmentname>}
\end{<environmentname>}

*Save and copy or move your .cwl-file to the settings directory of TXS. For Windows 7 it is in %AppData%\texstudio\completion\user.

*Restart TXS, if necessary and goto Options -> Configure TeXstudio -> Completion. Check box of your .cwl-file.
# indicates comment line unless used within
classification or with keywords. For more information refer to TXS manual section 4.13 or TXS FAQ .
Example:
example.cwl
#naphaneal/2016-07-01
\begin{my-code}
\end{my-code}


text:
Q: AngularJS pretty-url not working on page refresh if base href is set to other than '/' I am new to AngularJS. I am currently facing problem in writing pretty urls for my views.I have set $locationProvider.html5Mode(true); to remove # from the urls displayed in the address bar. However,upon doing so I am unable to reroute to desired views.
I keep getting the error Cannot GET /login
I get the home page /login when the app is launched first time , but when I refresh the page I get the same error.
Here the main page of application (index.html)
<!doctype html>
<head>
<meta charset="utf-8">
<title>F-1 Feeder</title>
<meta name="viewport" content="width=device-width">
<!-- build:css styles/vendor.css -->
<!-- bower:css -->
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<!-- endbower -->
<!-- endbuild -->
<!-- build:css({.tmp,app}) styles/main.css -->
<link rel="stylesheet" href="styles/main.css">
<base href="/login"/>
<!-- endbuild -->
</head>
<body ng-app="F1FeederApp" class="col-md-8">

<ng-view></ng-view>

<!-- build:js scripts/vendor.js -->
<!-- bower:js -->
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/es5-shim/es5-shim.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/json3/lib/json3.min.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<!-- endbower -->
<script src="bower_components/angular-mocks/angular-mocks.js"></script>
<!-- endbuild -->

<!-- build:js({.tmp,app}) scripts/scripts.js -->
<script src="scripts/app.js"></script>
<script src="scripts/loginHttpBackend.js"></script>
<script src="scripts/services.js"></script>
<script src="scripts/controllers/driver.js"></script>
<script src="scripts/controllers/drivers.js"></script>
<script src="scripts/controllers/login.js"></script>
<!-- endbuild -->

My app.js file(where rerouting takes place) looks like this
angular.module('F1FeederApp.controllers', []);

angular.module('F1FeederApp',
    [ 'F1FeederApp.services', 'F1FeederApp.controllers', 'ngRoute' ])
    .config([ '$routeProvider','$locationProvider',     function($routeProvider,$locationProvider,$location) {
            console.log('---------------inside config----------------');
        console.log($routeProvider);
        $routeProvider.when("/login", {
            templateUrl : "views/login.html",
            controller : "loginController"
        }).when("/drivers", {
            templateUrl : "views/drivers.html",
            controller : "driversController"
        }).when("/drivers/:id", {
            templateUrl : "views/driver.html",
            controller : "driverController"
        }).otherwise({
            redirectTo : "/login"
        });
        $locationProvider.html5Mode(true);

    } ]);

I also made following important observation

*

*If I set the base href on index.html to point to the root as <base href='/'>
and perform rerouting as
$routeProvider.when("/", {
        templateUrl : "views/login.html",
        controller : "loginController"
    }).when("/drivers", {
        templateUrl : "views/drivers.html",
        controller : "driversController"
    }).when("/drivers/:id", {
        templateUrl : "views/driver.html",
        controller : "driverController"
    }).otherwise({
        redirectTo : "/"
    });

my app works fine here.But I want '/login' to be my default page. Kindly guide me on where I am going wrong or is it an issue with AngularJS itself.

A: Other than enabling html5Mode on, you also need to update your server-side to redirect all the request like /login or /home etc to a single entry-point, like an index.html.

Server side
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)

Search for "Server side" on this documentation page:
angular $location docs


text:
Q: Android audio recording not working on button click I'm trying to make a simple application that will record an audio file and store it in local storage but for some reason my code isn't working! I'm wondering if there is a problem with my code! Please help to find the mistake!
public class demo extends Activity implements OnClickListener {

    private static final String LOG_TAG = "AudioRecordTest";

    private static String mFileName = null;

    private MediaRecorder mRecorder = null;

    private MediaPlayer mPlayer = null;

    boolean mStartPlaying, mStartRecording;

    Button RecordButton, PlayButton;

    private void onRecord(boolean start) {
        if (start) {
            startRecording();
        } else {
            stopRecording();
        }
    }

    private void onPlay(boolean start) {
        if (start) {
            startPlaying();
        } else {
            stopPlaying();
        }
    }

    private void startPlaying() {
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(mFileName);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    }

    private void stopPlaying() {
        mPlayer.release();
        mPlayer = null;
    }

    private void startRecording() {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }

        mRecorder.start();
    }

    private void stopRecording() {
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;
    }

    public demo() {
        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
        mFileName += "my_Record";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);

        mStartRecording = true;
        mStartPlaying = true;

        RecordButton = (Button) findViewById(R.id.btRecord);
        RecordButton.setOnClickListener(this);
        PlayButton = (Button) findViewById(R.id.btPlay);
        PlayButton.setOnClickListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }

        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

        switch (arg0.getId()) {

        case R.id.btRecord: {

            onRecord(mStartRecording);
            if (mStartRecording) {
                RecordButton.setText("Stop recording");
            } else {
                RecordButton.setText("Start recording");
            }
            mStartRecording = !mStartRecording;
            break;
        }
        case R.id.btPlay: {

            onPlay(mStartPlaying);
            if (mStartPlaying) {
                PlayButton.setText("Stop playing");
            } else {
                PlayButton.setText("Start playing");
            }
            mStartPlaying = !mStartPlaying;
            break;
        }
        }
    }
}

LogCat output:
11-28 13:57:01.562: E/AndroidRuntime(2237): FATAL EXCEPTION: main
11-28 13:57:01.562: E/AndroidRuntime(2237): Process: com.example.drishtikon, PID: 2237
11-28 13:57:01.562: E/AndroidRuntime(2237): java.lang.IllegalStateException
11-28 13:57:01.562: E/AndroidRuntime(2237):     at android.media.MediaRecorder.start(Native Method)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at com.example.drishtikon.demo.startRecording(demo.java:78)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at com.example.drishtikon.demo.onRecord(demo.java:35)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at com.example.drishtikon.demo.onClick(demo.java:129)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at android.view.View.performClick(View.java:4424)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at android.view.View$PerformClick.run(View.java:18383)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at android.os.Handler.handleCallback(Handler.java:733)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at android.os.Handler.dispatchMessage(Handler.java:95)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at android.os.Looper.loop(Looper.java:137)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at android.app.ActivityThread.main(ActivityThread.java:4998)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at java.lang.reflect.Method.invokeNative(Native Method)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at java.lang.reflect.Method.invoke(Method.java:515)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
11-28 13:57:01.562: E/AndroidRuntime(2237):     at dalvik.system.NativeStart.main(Native Method)

A: It's the filepath (mFileName);
Correct your demo() method. This is how it should look like:
public demo() {
        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
        mFileName += "/my_Record";
    }

You need to add a slash (/) between the directory path and the filename, of course. Also try adding a file extension, like "/my_Record.3gp" if you use the OutputFormat.THREE_GPP.


text:
Q: Finding the $p$-value from Bernoulli hypothesis test So I'm told that $X_i \sim Bern(p)$, $Y = \sum_{i=1}^N X_i$ and $H_0: p \geq 0.5$ vs $H_1: p < 0.5$ with $\alpha = 0.05$.
I have to find the $p$-value at $n=30$ and $y=5$.
I'm not sure if this correct, but I figured the $p$-value was simply:
$$P(Y \leq 5) = \sum_{i=1}^5 \binom{30}{y}(0.5)^y (0.5)^{30-y}$$
which works out to be $0.00016$.
If this is correct, then why have I been given $\alpha$?

A: The p-value you calculated is correct. $\alpha=5\%$ is given to compare the p-value you found with it.
As $p_{value}<\alpha$ you reject $H_0$


text:
Q: Connect to wifi while hosting AP on another iface I have two wireless interfaces. wlan1 and wlan0. And I want to host some Access Point on wlan1 (airbase-ng and isc-dhcp-server) and redirect packets from access point interface(at0) to wlan0 which should be connected to some WiFi.Here's my dhcp.conf
ddns-update-style none;
authoritative;
subnet 10.0.0.0 netmask 255.255.255.0{
range 10.0.0.100 10.0.0.254;
option domain-name-servers 8.8.8.8;
option broadcast-address 10.0.0.255;
option routers 10.0.0.1;
default-lease-time 600;
max-lease-time 7200;
}

I've already used such config to redirect packets with iptables to eth0 but now I need to do it with wlan0. Any ideas? I already tried wpa_supplicant but it seems that it doesn't work.
I'm running Debian 8 x64. PC is Asus s300ca and wlan1 is TP-Link TL-WN722N
Original post is here: stackowerflow

A: The interface on which hostapd is listening is in monitor mode, which makes it impossible to route the packets out of it directly. In fact, what you normally do is to put this interface into a bridge with the eth0 interface.
When you do not use an eth interface, you can still create a bridge with a virtual interface, say tap0, instead of eth0.
    ip tuntap add tap0 mode tap user root
    ip link set tap0 up
    ip link add br0 type bridge
    ip link set tap0 master br0

Now you can use the instruction interface=br0 inside hostapd.conf. Next step, we use br0 as the interface on which dhcp listens for requests. And lastly, you must both enable IPv4 packet forwarding to allow packets collected by hostapd to be routed thru wlan0, and use MASQUERADE:
    iptables -t nat -A POSTROUTING  -o wlan0 -j MASQUERADE


text:
Q: Rewrite Rules - Differentiate between Angular #! and Angular without #! How do I write Rewrite Rules in IIS to handle these scenarios:
Folder Structure:
[AngularApp1]
  -- app.js
  -- appController.js
  -- index.html
[AngularSecondApp]
  -- app.js
  -- appController.js
  -- index.html
[DomainSubApp]
  -- app.js
  -- appController.js
  -- index.html
favicon.ico
gulpfile.js
web.config

AngularApp1 is NOT HTML5 configured, and is using the DEFAULT #! prefix.  So pages typically look like: https://(www.)?mywebsite.com/#!/state...
AngularSecondApp IS configured in HTML5 mode, and uses NO '' hashPrefix.  So pages typically look like: https://(www.)?mywebsite.com/state...
DomainSubApp is NOT HTML5 configured, and is using the DEFAULT #! prefix.  Pages typically look like: https://domainsubapp.mywebsite.com/#!/state...
Routing

The server should be using AngularSecondApp/index.html if:

*

*the subdomain is '' or 'www' AND...

*The URI? is: ^/\w+/?.*$ -- But not Files

...

The server should be using DomainSubApp/index.html if:

*

*the subdomain is DomainSubApp

...

Otherwise, the server should be using AngularApp1/index.html INCLUDING:

*

*the subdomain is '' or 'www' AND...

*The URI? is: ^/(#!/.*)?$ -- But not Files

My Personal Confusion
I realize you need to take FILES into consideration.  For example, http://mywebsite.com/favicon.ico or http://mywebsite.com/someFile.ext or http://mywebsite.com/scripts/scriptFile.js.  So some of my attempts failed because my Patterns were too generic.  Therefore, requests for files were ALSO rewritten/redirected.
Do I need to do anything to ensure the Angular Routing Persists?  So, if I go to http://mywebsite.com/route/param1/param2, that should be rewritten/redirected to http://mywebsite.com/AngularSecondApp/index.html  Where does route/param1/param2 go?
What I HAD:
I say "Had" because I previously required a Sub-Folder in the URL named AngularSecondApp, such as: https://(www.)?mywebsite.com/AngularSecondApp/state....  This made things easier.  But the brass wants me to get rid of that subfolder in the URL, hence this trouble.
So this is what I had:
    <clear />
    /*https forced redirect is here... irrelevant*/

    <rule name="AngularSecondApp rewrite" stopProcessing="true">
      <match url="^AngularSecondApp/.*$" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="/AngularSecondApp/index.html" />
    </rule>

    <rule name="AngularApp1 redirect">
      <conditions>
        <add input="{REQUEST_URI}" pattern="^(/AngularApp1)?/index\.html$" ignoreCase="true" />
      </conditions>
      <action type="Redirect" url="/" />
    </rule>

    <rule name="AngularApp1 rewrite">
      <conditions>
        <add input="{REQUEST_URI}" pattern="^/$" />
      </conditions>
      <action type="Rewrite" url="/AngularApp1/index.html" />
    </rule>

A: As an artifact of a day long past, the Rewrites I "HAD" included a Redirect in case people directly visited an index.html page.  Also, I was under the impression that any Rewrite you took action to (So rewriting / to index.html) had to have a Redirect.  That was incorrect.
Therefore, after GeorgeAWG's comment, I ended up ditching the Redirects and only doing Rewrites.  This simplified my life, and could possibly simply everybody's life.
    <rule name="AngularSecondApp rewrite">
      <conditions>
        <add input="{REQUEST_URI}" pattern="^(/\w+)+/?$" />
      </conditions>
      <action type="Rewrite" url="/AngularSecondApp/index.html" />
    </rule>

    <rule name="AngularApp1 rewrite">
      <conditions>
        <add input="{REQUEST_URI}" pattern="^/$" />
      </conditions>
      <action type="Rewrite" url="/AngularApp1/index.html" />
    </rule>

So if the Request URI begins with word characters, it will rewrite to the second app.
I'm not sure how the AngularApp1 is working... because it works for root /, but it also works for /#!/route...  But it doesn't throw off files like /scripts/lol.js.  So my answer solves the problem, but is missing some understanding.


text:
Q: linux kernel panic unable to handle kernel NULL pointer dereference at I'm facing issues with some kernel panic but I don't have any idea how to find which soft is exacly causing this issue. I'm trying to compile some soft on remote host using distcc software but my machines which are compiling are going down because of this issue.
Could you point me where shoud I start looking? What could cause this issue? Which tools should I use?
Here is kernel panic output:
[591792.656853] IP: [<          (null)>]           (null)
[591792.658710] PGD 800000032ca05067 PUD 327bc6067 PMD 0
[591792.660439] Oops: 0010 [#1] SMP
[591792.661562] Modules linked in: fuse nfsv3 nfs_acl rpcsec_gss_krb5 auth_rpcgss nfsv4 dns_resolver nfs lockd grace fscache nls_utf8 isofs sunrpc dm_mirror dm_region_hash dm_log dm_mod sb_edac iosf_mbi kvm_intel ppdev kvm irqbypass crc32_pclmul ghash_clmulni_intel aesni_intel lrw gf128mul glue_helper ablk_helper cryptd cirrus ttm joydev drm_kms_helper sg virtio_balloon syscopyarea sysfillrect sysimgblt fb_sys_fops drm parport_pc parport drm_panel_orientation_quirks pcspkr i2c_piix4 ip_tables xfs libcrc32c sr_mod cdrom virtio_blk virtio_net ata_generic pata_acpi crct10dif_pclmul crct10dif_common crc32c_intel serio_raw floppy ata_piix libata virtio_pci virtio_ring virtio
[591792.682098] CPU: 2 PID: 25548 Comm: cc1plus Not tainted 3.10.0-957.el7.x86_64 #1
[591792.684495] Hardware name: Red Hat OpenStack Compute, BIOS 1.11.0-2.el7 04/01/2014
[591792.686923] task: ffff8ebb65ea1040 ti: ffff8ebb6b250000 task.ti: ffff8ebb6b250000
[591792.689315] RIP: 0010:[<0000000000000000>]  [<          (null)>]           (null)
[591792.691729] RSP: 0018:ffff8ebb6b253da0  EFLAGS: 00010246
[591792.693438] RAX: 0000000000000000 RBX: ffff8ebb6b253e40 RCX: ffff8ebb6b253fd8
[591792.695716] RDX: ffff8ebb38098840 RSI: ffff8ebb6b253e40 RDI: ffff8ebb38098840
[591792.697992] RBP: ffff8ebb6b253e30 R08: 0000000000000100 R09: 0000000000000001
[591792.700271] R10: ffff8ebb7fd1f080 R11: ffffd7da0beb9380 R12: ffff8eb8417af000
[591792.702547] R13: ffff8eb875d1b000 R14: ffff8ebb6b253f24 R15: 0000000000000000
[591792.704821] FS:  0000000000000000(0000) GS:ffff8ebb7fd00000(0063) knlGS:00000000f7524740
[591792.707397] CS:  0010 DS: 002b ES: 002b CR0: 0000000080050033
[591792.709242] CR2: 0000000000000000 CR3: 000000032eb0a000 CR4: 00000000003607e0
[591792.711519] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
[591792.713814] DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
[591792.716100] Call Trace:
[591792.716927]  [<ffffffff9165270b>] ? path_openat+0x3eb/0x640
[591792.718727]  [<ffffffff91653dfd>] do_filp_open+0x4d/0xb0
[591792.720451]  [<ffffffff91661504>] ? __alloc_fd+0xc4/0x170
[591792.722267]  [<ffffffff9163ff27>] do_sys_open+0x137/0x240
[591792.724017]  [<ffffffff916a1fab>] compat_SyS_open+0x1b/0x20
[591792.725820]  [<ffffffff91b78bb0>] sysenter_dispatch+0xd/0x2b
[591792.727648] Code:  Bad RIP value.
[591792.728795] RIP  [<          (null)>]           (null)
[591792.730486]  RSP <ffff8ebb6b253da0>
[591792.731625] CR2: 0000000000000000
[591792.734935] ---[ end trace ccfdca9d4733e7a5 ]---
[591792.736450] Kernel panic - not syncing: Fatal exception
[591792.738708] Kernel Offset: 0x10400000 from 0xffffffff81000000 (relocation range: 0xffffffff80000000-0xffffffffbfffffff)

A: It is quite difficult to tell what went wrong with this just piece of log you have pasted.
It seems like oops lead into kernel panic!.
Well,with helping you to find the real cause,I can help you with material to look into for further dissection of panic/crash.
link 1: analysing kernel panics
link 2 : oops
Hope it helps you! :)


text:
Q: MahApps Metro - Applying transition to tab control In MahApps Metro source code, the sample solution includes a Visual Studio style demo application.

I need to combine the Visual Studio style with AnimatedSingleRowTabControl.
I have modified the XAML:
<Style x:Key="VsTabControl" TargetType="{x:Type TabControl}">

To:
<Style x:Key="VsTabControl" TargetType="{x:Type AnimatedSingleRowTabControl}">

After the modification the transition worked as expected, but the Visual studio style was gone.
Can anyone help me to achieve this?

A: If you have the source of MahApps, you should navigate in the MahApps.Metro project to Styles/VS/TabControl.xaml.
To add the animations to this TabControl, modify the source like this:

*

*Open MahApps.Metro/Styles/VS/TabControl.xaml

*Add the following things to the first ResourceDictionary:

*

*xmlns:Behaviours="clr-namespace:MahApps.Metro.Behaviours"

*xmlns:Controls="clr-namespace:MahApps.Metro.Controls"

*Scroll down until you see <Setter Property="Template">

*Add <Setter Property="Controls:TabControlHelper.Transition" Value="Left" /> above the Template

*Replace the Template with the Template already written in the MetroAnimatedTabControl and remove all the background properties. Also change TargetType from Controls:MetroAnimatedTabControl to just a regular TabControl
The full source of the VS/TabControl.xaml can be found here: http://pastebin.com/Ssbxg41a


text:
Q: Why can I not access the value of this pointer. Objective c I want to access YGNodeRef node in the parameters of the RCTMeasure function. This is from the yoga files in react-native, RCTShadowText.m
static YGSize RCTMeasure(YGNodeRef node, float width, YGMeasureMode
widthMode, float height, YGMeasureMode heightMode)
{
  RCTShadowText *shadowText = (__bridge RCTShadowText *)
  YGNodeGetContext(node);
  NSTextStorage *textStorage = [shadowText buildTextStorageForWidth:width
  widthMode:widthMode];
  [shadowText calculateTextFrame:textStorage];
  NSLayoutManager *layoutManager = textStorage.layoutManagers.firstObject;
  NSTextContainer *textContainer = layoutManager.textContainers.firstObject;
  CGSize computedSize = [layoutManager
  usedRectForTextContainer:textContainer].size;

  YGSize result;
  result.width = RCTCeilPixelValue(computedSize.width);
  if (shadowText->_effectiveLetterSpacing < 0) {
     result.width -= shadowText->_effectiveLetterSpacing;
  }
  result.height = RCTCeilPixelValue(computedSize.height);
  return result;
 }

YGNodeRef is delcared in another class called Yoga.h.
typedef struct YGNode *YGNodeRef;

I can see the values of YGNodeRef node in the debugger, but I can not figure out how to access it's elements in code. The contents look like this:
(YGNodeRef) 0x150094a00
    > style (YGStyle)
    > layout (YGLayout)
    lineIndex = (uint32_t) 0
    > parent = (YGNodeRef) 0x15009e200
        ..... etc .....
    > context

I want access to the 'context' child to check if it is null or not, some help would be much appreciated. Or if you simply know the reasoning of why the context would be null that will also help me :)
I am new to Objective C, so my logic may be flawed.


text:
Q: Overloading, variadic functions and bool type Following program compiles fine and works as expected. Its output is:

1
  2

#include <stdio.h>

class Foo
{
public:
  void Bar(const char* b, ...) { printf("1\n"); };
  void Bar(int a, const char* b, ...) { printf("2\n"); };
};

int main()
{
  Foo foo1;
  foo1.Bar("Test", "xx", 1, 2);
  foo1.Bar(1, "xx", "xx", 2, 2);
}

Now if I change the int parameter of the second Bar function into bool and foo1.Bar(1, "xx", "xx", 2, 2); into foo1.Bar(true, "xx", "xx", 2, 2);, then the following line won't compile and I get the error: 'Foo::Bar': 2 overloads have similar conversions:
  foo1.Bar("Test", "xx", 1, 2);

The whole program that doesn't compile:
#include <stdio.h>

class Foo
{
public:
  void Bar(const char* b, ...) { printf("1\n"); };
  void Bar(bool a, const char* b, ...) { printf("2\n"); };
};

int main()
{
  Foo foo1;
  foo1.Bar("Test", "xx", 1, 2);  // error: 'Foo::Bar': 2 overloads have similar conversions
  foo1.Bar(true, "xx", "xx", 2, 2);
}

I don't understand why there is an ambiguity in the second case.
EDIT
But if pointers implicitly convert to bool, why does following compile ?
#include <stdio.h>

class Foo
{
public:
  void Bar(const char* b) { printf("1\n"); };
  void Bar(bool a) { printf("2\n"); };
};

int main()
{
  Foo foo1;
  foo1.Bar("Test");
  foo1.Bar(true);
}

A: This is fine:
#include <stdio.h>

class Foo
{
public:
  void Bar(const char* b, ...) { printf("1\n"); };
  void Bar(bool a, ...) { printf("2\n"); };
};

int main()
{
  Foo foo;
  foo.Bar("Test");
}

This is not fine:
#include <stdio.h>

class Foo
{
public:
  void Bar(const char* b, ...) { printf("1\n"); };
  void Bar(bool a, char another, ...) { printf("2\n"); };
};

int main()
{
  Foo foo;
  foo.Bar("Test", 'c');  // Ambiguous!
}

In the first case, the first version of Bar() is clearly better. But in the second case, it is not so clear anymore because, while the first version has a better match for parameter 1, the second version has a better match for parameter 2.
The remaining question is: why does using 'int' instead of 'bool' avoid the ambiguity? The answer is that a pointer may implicitly convert to bool but not int.

A: When you match "Test", "xx", 1, 2 against const char*, ..., the conversion sequence for the first argument has exact match rank, the second through fourth one are ellipsis conversion sequences. So (exact match, ellipsis, ellipsis, ellipsis).
When you match "Test", "xx", 1, 2 against bool, const char*, ..., the first conversion sequence for the first argument has conversion rank; the second is an exact match, the third and fourth are ellipsis conversion sequences. In other words, (conversion, exact match, ellipsis, ellipsis).
Exact match beats conversion; everything beats ellipsis (see [over.ics.rank]). Thus we have a so-called criss-cross situation here where one function has a better conversion sequence for one argument and the other function has a better conversion sequence for another argument. Since a necessary (but not sufficient) condition for a function to be better than another function is that none of the conversion sequences are worse than those of the other function ([over.match.best]/1), neither of those two functions is better than the other.


text:
Q: How to create calculated column / Property in the User Profiles with Visual Studio or Manually? I have to create one calculated column / Property in the User Profiles with custom / Visual Studio or Manually.
Is it possible and How?
I know that, we can create the Property but I don't know how to create calculated property/column.


text:
Q: Example for Model-dependant state ember concept using cache Below is my route,
this.route('posts',{path: 'posts/:PostId/:PageIndex/:PageSize'});
For the postId=1 user is creating some filter stuff and navigates to postId=2 and comes back to postId=1 then user should be able to view created filters.
Typically, I would like to persist some controller sticky properties to each route user visits. how to do that ?.


text:
Q: Polymer: building nested paper-tabs and core-pages I am trying to create nested paper-tabs and core-pages. My problem is that after Tab 2 is selected, Page Content 11 or Page Content 12 is left over. How do I hide the unselected "page content", enclosed by div in my case?
index.html:
<!doctype html>
<html>
<head>
    <title>Home</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="page.css">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
    <script src="bower_components/webcomponentsjs/webcomponents.js"></script>
    <link rel="import" href="bower_components/core-header-panel/core-header-panel.html">
    <link rel="import" href="my-page.html">
    <style>
        html,body {
            height: 100%;
            margin: 0;
            font-size:62.5%;
        }
        core-header-panel {
            height: 100%;
            overflow: auto;
            -webkit-overflow-scrolling: touch;
            font-size:3em;
        }
    </style>
</head>
<body unresolved>
    <core-header-panel>
        <my-page id="p"></my-page>
    </core-header-panel>
    <script>
        data=[
            {
                TabCaption:"Tab 1"
                ,children:[
                    {
                        TabCaption:"Tab 11"
                        ,PageContent:"Page Content 11"
                        ,children:null
                    }
                    ,{
                        TabCaption:"Tab 12"
                        ,PageContent:"Page Content 12"
                        ,children:null
                    }
                ]
            }
            ,{
                TabCaption:"Tab 2"
                ,PageContent:"Page Content 2"
                ,children:null
            }
        ];
        document.querySelector("#p").pages=data;
    </script>
</body>
</html>

my-page.html:
<link rel="import" href="bower_components/paper-tabs/paper-tabs.html">
<link rel="import" href="bower_components/core-pages/core-pages.html">
<polymer-element name="my-page" attributes="pages">
    <template repeat if="{{pages}}">
        <style>
            paper-tabs {
                margin: 0;
                -webkit-user-select: none;
                -moz-user-select: none;
                -ms-user-select: none;
                user-select: none;
                text-transform: uppercase;
                color: #F00;
                background-color: #00BCD4;
            }
            core-selected {
                background-color: #00FF00;
            }
            paper-tab {
                font-size:1.6em;
            }
        </style>
        <paper-tabs selected="{{selected}}" flex self-end layout>
            <template repeat="{{p in pages}}">
                <paper-tab>{{p.TabCaption}}</paper-tab>
            </template>
        </paper-tabs>
        <core-pages selected="{{selected}}">
            <template repeat="{{p in pages}}">
                <div one flex vertical layout>
                    <template if="{{p.PageContent}}">
                        {{p.PageContent}}
                    </template>
                    <template if="{{p.children}}">
                        <my-page pages="{{p.children}}"></my-page>
                    </template>
                </div>
            </template>
        </core-pages>
    </template>
    <script>
        Polymer({
            selected:0
        });
    </script>
</polymer-element>

Thank you in advance for the enlightenment!

Edit:
@JoppeSchwartz:
Thank you for your kind help! I learn a lot from it.
Iceweasel v.35 behaves the same as those screen shots in my original post. Chromium v.40 renders incorrect effects.

A: After inspecting the elements in the browser debugger, I find that the div enclosing the PageContent is being rendered with zero height. To resolve this, I used the following steps:

*

*In index.html:

*

*Add the fullbleed attribute to the <body> element, per the Polymer layout docs. This tells the body to take up all available space in the viewport.
<body unresolved fullbleed>

*Add the vertical layout and flex attributes to the code in the body so that they take up available vertical space:
<core-header-panel vertical layout>
    <my-page flex id="p"></my-page>
</core-header-panel>

*In my-page.html:

*

*Add the vertical layout attributes to the <my page> component and the flex attribute to the ` element so that it takes up :
    <polymer-element name="my-page" attributes="pages" vertical layout>
    . . .
    <core-pages selected="{{selected}}" flex>

*At this point, the <paper-tabs> will be pushed to the right side of the page. This is not what you want, I gather, so remove the self-end attribute:
    <paper-tabs selected="{{selected}}" layout>

*Finally, although this is not strictly necessary, I noticed that the core-selected selector in your style section should read .core-selected if you want to select the CSS class of that name.
For completeness, here are the edited versions of your code:
index.html
<!doctype html>
<html>
<head>
    <title>Home</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="page.css">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
    <script src="bower_components/webcomponentsjs/webcomponents.js"></script>
    <link rel="import" href="bower_components/core-header-panel/core-header-panel.html">
    <link rel="import" href="my-page.html">
    <style>
        html,body {
            height: 100%;
            margin: 0;
            font-size:62.5%;
        }
        core-header-panel {
            height: 100%;
            overflow: auto;
            -webkit-overflow-scrolling: touch;
            font-size:3em;
                    }
    </style>
</head>
<body unresolved fullbleed>
    <core-header-panel vertical layout>
        <my-page flex id="p"></my-page>
    </core-header-panel>
    <script>
        data=[
            {
                TabCaption:"Tab 1"
                ,children:[
                    {
                        TabCaption:"Tab 11"
                        ,PageContent:"Page Content 11"
                        ,children:null
                    }
                    ,{
                        TabCaption:"Tab 12"
                        ,PageContent:"Page Content 12"
                        ,children:null
                    }
                ]
            }
            ,{
                TabCaption:"Tab 2"
                ,PageContent:"Page Content 2"
                ,children:null
            }
        ];
        document.querySelector("#p").pages=data;
    </script>
</body>
</html>

my-page.html
<link rel="import" href="bower_components/paper-tabs/paper-tabs.html">
<link rel="import" href="bower_components/core-pages/core-pages.html">
<polymer-element name="my-page" attributes="pages" vertical layout>
    <template repeat if="{{pages}}">
        <style>
            paper-tabs {
                margin: 0;
                -webkit-user-select: none;
                -moz-user-select: none;
                -ms-user-select: none;
                user-select: none;
                text-transform: uppercase;
                color: #F00;
                background-color: #00BCD4;
                            }

            .core-selected {
                            background-color: #00FF00;
            }
            paper-tab {
                font-size:1.6em;
                            }
        </style>
        <paper-tabs selected="{{selected}}" layout>
            <template repeat="{{p in pages}}">
                <paper-tab>{{p.TabCaption}}</paper-tab>
            </template>
        </paper-tabs>
        <core-pages selected="{{selected}}" flex>
            <template repeat="{{p in pages}}">
                <div one flex vertical layout>
                    <template if="{{p.PageContent}}">
                        {{p.PageContent}}
                    </template>
                    <template if="{{p.children}}">
                        <my-page pages="{{p.children}}"></my-page>
                    </template>
                </div>
            </template>
        </core-pages>
    </template>
    <script>
        Polymer({
            selected:0
        });
    </script>
</polymer-element>


text:
Q: ScrollView not scrolling after setting View.OnTouchListener on it I have a scrollview that needs to be moved on top of another view and only after that start scrolling process.
I've added a TouchListener on the ScrollView and implemented onTouch method - to be able to move the scrollview.
The problem is that event if the scrollview reaches the desired position - and the moving process is stopped - the scrolling does not take place.
I'm thinking maybe because I've attached the Touch listener - it somehow interferes with the scrolling listener or something?


text:
Q: Python re: Regex expression for pattern following 3 letters and comma How would one write a regex expression in python re, where the pattern is :
3 english letters followed by a comma
Example:
string_var = "AAA, BBB, CCC"  # follows the pattern
string_var = "AAA, BBBB, CCC, DDD" # does not follow the pattern

A: If you want to only check if a string matches, use ^[A-Za-z]{3}, [A-Za-z]{3}, [A-Za-z]{3}$ (https://regexr.com/5i22s). This will be true for "AAA, BBB, CCC", but is not useful for finding matches like in "test asf, cat, dog".
^        Start of string
[A-Za-z] Alphabet characters
{3}      3 alphabet characters
,        A comma followed by a space
...
$        End of string

A: Try this
^([a-zA-Z]{3},\s){2}[a-zA-Z]{3}$

or use this with re.I flag
^([a-z]{3},\s){2}[a-z]{3}$


text:
Q: Apply a function to elements inside a list of lists Let's say I have a function:
def f(i: Int): String = i.toString

How can I define xxx such as (assume I can add methods to list without implicit conversions):
val source1: List[List[Int]] = List(List(1,2), List(3,4))
val source2: List[Int] = List(1,2)

val result1: List[List[String]] = source1.xxx(f)
val result2: List[String] = source2.xxx(f)

because with

List [ _ ]

I can't tell if _ can have map applied or not. Is it possible?

A: You could try this:
object Container1 {
  implicit class RichList1(l: List[List[Int]]) {
    def xxx(f: (Int) => String): List[List[String]] = {
      l.map(l => l.map(n => f(n)))
    }
  }
}

object Container2 {
  implicit class RichList2(l: List[Int]) {
    def xxx(f: (Int) => String): List[String] = {
      l.map(n => f(n))
    }
  }
}

object Mapping extends App {
  def f(i: Int): String = i.toString

  val source1: List[List[Int]] = List(List(1, 2), List(3, 4))
  val source2: List[Int] = List(1, 2)

  import Container1._
  val result1a: List[List[String]] = source1.xxx(f)
  println(result1a)

  import Container2._
  val result2a: List[String] = source2.xxx(f)
  println(result2a)

}

A: It looks like you're trying to apply your function to the inner most item of the collection regardless of how deep you're values are nested (in this case, List[T] and List[List[T]]).
trait CanMapInner[WrappedV, WrappedB, V, B] {
  def mapInner(in: WrappedV, f: V ⇒ B): WrappedB
}

// simple base case (no nesting involved).
implicit def simpleMapper[V, B] = new CanMapInner[V, B, V, B] {
  def mapInner(in: V, f: (V) ⇒ B): B = f(in)
}

// drill down one level of "List".
implicit def wrappedMapper[V, B, InnerV, InnerB](implicit innerMapper: CanMapInner[InnerV, InnerB, V, B]) =
  new CanMapInner[List[InnerV], List[InnerB], V, B] {
    def mapInner(in: List[InnerV], f: (V) ⇒ B): List[InnerB] =
      in.map(innerMapper.mapInner(_, f))
  }

implicit class XXX[WrappedV](list: List[WrappedV]) {
  def xxx[V, B, WrappedB](f: V ⇒ B)(implicit mapper: CanMapInner[WrappedV, WrappedB, V, B]) = {
    list.map(inner ⇒ mapper.mapInner(inner, f))
  }
}

Adapted from qmajor's solution for Map.
Usage:
def f(i: Int): String = "Hello " + i.toString

val source1: List[List[Int]] = List(List(1, 2), List(3, 4))
val source2: List[Int] = List(1, 2)

val result1: List[List[String]] = source1.xxx(f)
val result2: List[String] = source2.xxx(f)

Console println source1
// > List(List(1, 2), List(3, 4))
Console println source2
// > List(1, 2)
Console println result1
// > List(List(Hello 1, Hello 2), List(Hello 3, Hello 4))
Console println result2
// > List(Hello 1, Hello 2)

I changed your f function for demo purposes.

A: You could use shapeless' Scrap Your Boilerplate to do that. Example copied from readme:
val nested = List(Option(List(Option(List(Option(23))))))

val succ = everywhere(inc)(nested)
succ == List(Option(List(Option(List(Option(24))))))

Up to you if you are ready to include a library to do that.


text:
Q: Pentaho PDI (Spoon): MySQL table output very slow (~2000 rows/s) My table output step is terribly slow (~2.000 rows/second), compared to the input (100.000-200.000 rows/second). The MySQL server is not the problem, using native MySQL, e.g. with the "Execute SQL script" step, I get something in the 100thousands/second. I already tried (without success) the common solution of extending the SQL options by:
useServerPrepStmts=false
rewriteBatchedStatements=true
useCompression=true

I also varied the commit size parameter (100, 1.000, 10.000) and Use batch updates for inserts is enabled, also without success. What else can I do? I have tables with ~10.000.000 rows and Pentaho runs on a very potent machine, so this is not acceptable.

A: For this I think the ideal step is MySQL Bulk Loader step which is listed under Bulk loading section. Along with that use the said
useServerPrepStmts=false
rewriteBatchedStatements=true
useCompression=true

in JDBC options in the connection.
These useCompression will compress the traffic between the client and the MySQL server
where as other two will form INSERT INTO tbl (a,b) VALUES (1,'x'),(2,'y'),(3,'z'); without using separate insert statements for each.

A: Follow these steps:

*

*Increase the RAM Size for PDI a.k.a Spoon.

*Using the Command line utility such as ( Kitchen or Pan) run your Job or Transformation.

Well Now compare the speed.
Cheers!


text:
Q: url rewriting issue with js,css etc I've got a little problem with URL rewriting in my .htaccess running on my local apache. I configured the entry point of my server via symbolic link (localhost/memap/), so "memap" leads to my project root (no vhost configured).
I'm not very familiar with url rewriting, but redirecting all requests to my index.php works fine. The index.php leads to a custom request controller, that processes the request and returns the according page.
My problem now is that no js,css etc. gets loaded. I tried several RewriteRules, but don't get a solution. This is my current .htaccess file, that doesn't contain any rule for js,css etc. yet:
# Allows ModRewrite to work
Options FollowSymLinks

# Turn on rewrite engine
RewriteEngine On
RewriteBase /memap

# Redirect all requests to index
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^page/(.*)/(.*)$ index.php?page=$1&id=$2 [NC,L,QSA]
RewriteRule ^page/(.*)$ index.php?page=$1 [NC,L,QSA]

If I'm not mistaken, the rewrite conditions should lead requests for files and directory, without actual rewriting, directly to its target in case the target file/directory exists.
Unfortunately this doesn't happening. E.g. my css-file (memap.css) is reachable via "localhost/memap/css/memap.css", but the server looks up on "localhost/css/memap.css" (without my memap symlink). Accordingly the same happens with my js ("localhost/js/memap.js"). This is how include them in my html:
<script src="js/memap.js"></script>
<link rel="stylesheet" href="css/memap.css" media="screen" />

I tried a lot of things, but don't know how to achieve my goal. Does anyone have a solution to this? It's probably just a minor thing that's missing...
Thanks in advance!

A: Your RewriteConds only apply to the first RewriteRule.
You can write two time the RewriteCond block:
RewriteBase /memap/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^page/(.*)/(.*)$ index.php?page=$1&id=$2 [NC,L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^page/(.*)$ index.php?page=$1 [NC,L,QSA]

Or you can skip two RewriteRule with [S=2]:
RewriteBase /memap/

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .* - [S=2]
RewriteRule ^page/(.*)/(.*)$ index.php?page=$1&id=$2 [NC,L,QSA]
RewriteRule ^page/(.*)$ index.php?page=$1 [NC,L,QSA]

And you should write, for your JS & CSS files:
<script src="/memap/js/memap.js"></script>
<link rel="stylesheet" href="/memap/css/memap.css">


text:
Q: how to fill the hook using foreach I need to fill hook using foreach statement. Using my code I can only assign the last value from Data object. Please help me to create right approach to fill the hook using 'value' from Data. I need Percent={123,456,789} instead {789} only.

function App() {
  const [Percentage, SetPercentage]=useState([]);
  const Data=[
    {sensor: 'abcd', value: 123},
    {sensor: 'efgh', value: 456},
    {sensor: 'ijkl', value: 789}
  ]
  const Show=()=>
  {
      Data.forEach((key)=>{
      SetPercentage([...Percentage,key.value]);
    })}
  return (
    <View style={styles.app}>
      <Button onPress={Show} title='Show'></Button>
      {Percentage.map(()=>{
        return(
             <View>
             <Text>map={Percentage}</Text>
          </View>
      )})}
    </View>
  );
}

A: You can do this using map approach
SetPercentage(data.map(entry=>entry.value))

This will fill the percentage with 123,456,789

A: You are going to get incorrect results and performance issues by updating state in loops like:
  const Show=()=>
  {
      Data.forEach((key)=>{
      SetPercentage([...Percentage,key.value]);
    })}

Avoid mutation like this and rather build up your value and set the state once:
const show = () => {
    const vals = data.map((item) => item.value);
    setPercentage(vals);

    // or
    setPercentage(data.map((item) => item.value));
  };

While you are simply showing a demo, it would be best to move data outside the component and also ensure you have a unique key in your map--ideally not the index iterator and rather something unique.
const data = [
  { sensor: "abcd", value: 123 },
  { sensor: "efgh", value: 456 },
  { sensor: "ijkl", value: 789 }
];

export default function App() {
  const [percentage, setPercentage] = useState<Array<number>>([]);

  const show = () => {
    // set state once
    const vals = data.map((item) => item.value);
    setPercentage(vals);

    // or
    setPercentage(data.map((item) => item.value));
  };

  return (
    <>
      <button onClick={show}>Show</button>
      {percentage &&
        percentage.map((item, index) =>
{item}
)}
    </>
  );
}

Codesandbox Demo


text:
Q: MVVM Referencing Assemblies I am implementing the MVVM pattern in the application I'm working on, and I have 3 seperated assemblies in my solution, the Model, View, and ViewModel. The ViewModel has a reference to the Model, and the View has a reference to the ViewModel.
In my Model I have a class Event, and in the ViewModel I create an ObservableCollection<Event>.
The problem is when I try to set this collection as the DataContext of a ListView in the View. I get this error:
error CS0012: The type 'Model.Event' is defined in an assembly that is not referenced. You must add a reference to assembly 'Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

I want to have the app decoupled as much as possible, and this is not decoupling my app. I know that when I add a reference of the Model to my View, then I would not get the error, but I do not want my View having a Model Reference. How to make this working?

A: There's nothing wrong with having your view assembly reference the model assembly.  I think it's common practice and the only way your going to get your models to display in your view.  Assuming you're binding to your view-model's ObservableCollection from your view's xaml (not code-behind), I don't see tightly coupled assemblies here.