text:
Q: React js converting a class to functions I currently have a timer that works with a class but I need to use only functions so it works with the App.js file I am running to show what I need. Here is an example of how I would call my file from the App:
return (

Example Timer

Other files have been removed for example purposes

  <Timer onClick ={this.startTimer} />

)

And here is my Timer class which needs to be converted to functions so I can export it like:
export default function Timer(onClick)

Here is the entire class component for the timer
import React from 'react';
import "./timer.css";

class Timer extends React.Component{

constructor(){
    super();
    this.state = { time: {}, seconds: 5, color: 'darkgrey'};
    this.timer = 0;
    this.startTimer = this.startTimer.bind(this);
    this.startCountDown = this.startCountDown.bind(this);

    }

convertToSeconds(sec){
let divisor_for_minutes = sec % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);

let divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);

var obj = {"m": minutes, "s": seconds};
return obj;
}

componentDidMount() {
    let timeLeftVar = this.convertToSeconds(this.state.seconds);
    this.setState({ time: timeLeftVar });
  }

startTimer(){
// If timer is not set, set the interval

if(this.timer === 0 && this.state.seconds > 0){
    // 1000 ms = 1 second
    this.timer = setInterval(this.startCountDown, 1000);

}
}

startCountDown() {
        let seconds = this.state.seconds - 1;
        if(seconds >= 0){
          if(seconds<=2){
            this.setState({color: 'red'})
          }
        this.setState({
            time: this.convertToSeconds(seconds),
            seconds: seconds
        });
      }
    else{
        this.setState({time: this.convertToSeconds(5), seconds: 5, color: 'darkgrey'});
        clearInterval(this.timer);
        this.timer = 0;
    }

}

render(){
    return(

        <button onClick={this.startTimer}>Start</button>

        m: {this.state.time.m} s: {this.state.time.s}

    );
    }
}

export default Timer;

A: With a new version of react we can use Hook useState and it will look like this
import React, { useState } from 'react';
import "./timer.css";

const convertToSeconds = (sec) => {
  let divisor_for_minutes = sec % (60 * 60);
  var minutes = Math.floor(divisor_for_minutes / 60);

  let divisor_for_seconds = divisor_for_minutes % 60;
  var seconds = Math.ceil(divisor_for_seconds);

  var obj = {"m": minutes, "s": seconds};
  return obj;
}

const Timer= () => {
  const [seconds, setSeconds] = useState(5)
  const [time, setTime] = useState(convertToSeconds(seconds))
  const [color, setColor] = useState('darkgrey')
  const [timer, setTimer] = useState(0)

  const startTimer = () => {
    // If timer is not set, set the interval
    if(timer === 0 && seconds > 0){
        // 1000 ms = 1 second
        setTimer(setInterval(startCountDown, 1000))
    }
  }

  const startCountDown = () => {
        let newSeconds = seconds - 1;
        if(newSeconds >= 0){
          if(newSeconds<=2){
            setColor('red')
          }
            setTime(convertToSeconds(newSeconds))
            setSeconds(newSeconds)
      }
    else{
        setTime(convertToSeconds(5))
        setSeconds(5)
        setColor('darkgrey')
        setTimer(0)
    }
  }

  return(

          <button onClick={startTimer}>Start</button>

          m: {time.m} s: {time.s}

  )
}

export default Timer

A: This is the line by line conversion of the class component to function component using react hooks... (You need react version higher than 16.8.x https://reactjs.org/docs/hooks-intro.html)
import React, { useState, useEffect } from 'react';
import './timer.css';

export default function Timer() {
  const [seconds, setSeconds] = useState(5);
  const [time, setTime] = useState({});
  const [color, setColor] = useState('darkgrey');
  const [timer, setTimer] = useState(0);

  //only executes when component mounts by passing "[]".
  useEffect(() => {
    setTime(convertToSeconds(seconds));
  }, []);

  function convertToSeconds(sec) {
    let divisor_for_minutes = sec % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);

    let divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);

    var obj = { m: minutes, s: seconds };
    return obj;
  }

  function startTimer() {
    // If timer is not set, set the interval

    if (timer === 0 && seconds > 0) {
      // 1000 ms = 1 second
      setTimer(setInterval(startCountDown, 1000));
    }
  }

  function startCountDown() {
    let _seconds = seconds - 1;
    if (_seconds >= 0) {
      if (_seconds <= 2) {
        setColor('red');
      }
      setTime(convertToSeconds(_seconds));
      setSeconds(_seconds);
    } else {
      setTime(convertToSeconds(5));
      setSeconds(5);
      setColor('darkgrey');
      clearInterval(timer);
      setTimer(0);
    }
  }
  return (

        <button onClick={startTimer}>Start</button>

          m: {time.m} s: {time.s}

  );
}

A: You do not need function to work, you can use your class component and use it to render in directly in index.js or anywhere you want to render
Code is somewhat like this

import React from 'react';
import ReactDOM from 'react-dom';
import Timer from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(

Example Timer

Other files have been removed for example purposes

  <Timer />

  , document.getElementById('root'));
registerServiceWorker();


text:
Q: Computing an infinite product $\prod_{n=1}^{\infty} e(\frac{n}{n + 1})^n * \sqrt\frac{n}{n + 1}$
The answer to the question is $\frac{\sqrt{2\pi}}e$, although I do not know how to come to this solution. This is a problem from a math contest from the year 2016.

A: Hint:
\begin{align*}
\mathcal{I}&=\prod_{n=1}^\infty \Bigg [e\left(\frac{n}{n+1}\right)^{n}\sqrt{\frac{n}{n+1}}  \,\Bigg ]=\lim_{N\to\infty}\prod_{n=1}^N \Bigg [e\left(\frac{n}{n+1}\right)^{n}\sqrt{\frac{n}{n+1}}  \,\Bigg ]\\
&=\lim_{N\to\infty}e^N\left[\left(\frac 12\right)^1\left(\frac 23\right)^2\left(\frac 34\right)^3\cdots \left(\frac N{N+1}\right)^N\right]
\sqrt{\frac12\cdot\frac23\cdot\frac34\cdots\frac{N}{N+1}}\\
&=\lim_{N\to\infty}e^N\left[\frac{1\cdot 2\cdot 3\cdots N}{(N+1)^N}{\cdot \frac{N+1}{N+1}}\right]\sqrt\frac1{N+1}\\
&=\lim_{N\to\infty}e^N\frac{{(N+1)!}}{(N+1)^{N+\frac{3}{2}}}\\
\end{align*}
Hope you can take it from here using Stirling formula.

A: The logarithm of such product is given by
$$ \sum_{n\geq 1}\left(1-\left(n+\frac{1}{2}\right)\log\frac{n+1}{n}\right)=\sum_{n\geq 1}\int_{n}^{n+1}\frac{n+\tfrac{1}{2}-x}{x}\,dx $$
that is:
$$ -\int_{-\frac{1}{2}}^{\frac{1}{2}}\sum_{n\geq 1}\frac{t}{n+\tfrac{1}{2}+t}\,dt = -\int_{0}^{1}\sum_{n\geq 1}\frac{u^2}{(2n+1)^2-u^2}\,du$$
or, by considering the logarithmic derivative of the Weierstrass product for the cosine function,
$$ -\int_{0}^{1}\left(\frac{u^2}{u^2-1}+\frac{\pi u}{4}\tan\left(\frac{\pi u}{2}\right)\right)\,du $$
that is:
$$ -\lim_{t\to 1^-}\left(t-\text{arctanh}(t)-\tfrac{t}{2}\log\cos\tfrac{\pi t}{2}+\tfrac{1}{2}\log 2\right){=}\tfrac{1}{2}\log(2\pi)-1. $$
Exponentiating back, we get that the value of the infinite product is $\color{red}{\large\frac{\sqrt{2\pi}}{e}}$ without exploiting Stirling's approximation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: GQL: Comparison operator doesn't work i am trying to execute a GQL query on a location dataset stored in Datastore. Here's some example data:

Name/ID | latitude | longitude
------------------------------
- location1 | 34.4104149048 | -116.850200484
- location2 | 34.4118891533 | -116.865934048
- location3 | 34.4146973835 | -116.847347137

However, this GQL query doesn't return any results:
SELECT * FROM Location WHERE latitude > 1.0

As a simple GQL query where I select all items of type Location works, I am wondering what I am doing wrong?
Thanks in Advance!

A: Figured this out by myself:
I didn't create an index for the latitude and longitude properties, which is apparently needed to query over these properties...


text:
Q: Radgrid delete command error "Object must implement IConvertible" I am using Radgrid to manage the membership.
I want to use the delete command to delete a use from database,
but when I click the delete button I keep getting this error:

Object must implement IConvertible.

The weird thing is that the deletion mechanism works; my user is no longer available.
What could cause the error?
Here is my code:
<telerik:RadGrid ID="RadGrid1" runat="server" AllowFilteringByColumn="True" AllowPaging="True" AllowSorting="True" AutoGenerateEditColumn="True" DataSourceID="SqlDataSource1" GroupPanelPosition="Top" Skin="Black"
        AllowAutomaticUpdates="True" AllowAutomaticDeletes="True" AutoGenerateDeleteColumn="True" OnDeleteCommand="RadGrid1_DeleteCommand">
  <MasterTableView AutoGenerateColumns="False" DataSourceID="SqlDataSource1" DataKeyNames="UserId">
    <Columns>
      <telerik:GridBoundColumn DataField="UserId" DataType="System.Guid" FilterControlAltText="Filter UserId column" HeaderText="UserId" ReadOnly="True" SortExpression="UserId" UniqueName="UserId" Visible="false">
      </telerik:GridBoundColumn>
      <telerik:GridCheckBoxColumn DataField="IsApproved" DataType="System.Boolean" FilterControlAltText="Filter IsApproved column" HeaderText="????? ?????" SortExpression="IsApproved" UniqueName="IsApproved">
      </telerik:GridCheckBoxColumn>
      <telerik:GridCheckBoxColumn DataField="IsLockedOut" DataType="System.Boolean" FilterControlAltText="Filter IsLockedOut column" HeaderText="IsLockedOut" SortExpression="IsLockedOut" UniqueName="IsLockedOut">
      </telerik:GridCheckBoxColumn>
      <telerik:GridBoundColumn DataField="UserName" FilterControlAltText="Filter UserName column" HeaderText="UserName" SortExpression="UserName" UniqueName="UserName">
      </telerik:GridBoundColumn>
      <telerik:GridBoundColumn DataField="Email" FilterControlAltText="Filter Email column" HeaderText="Email" SortExpression="Email" UniqueName="Email">
      </telerik:GridBoundColumn>
    </Columns>
  </MasterTableView>
</telerik:RadGrid>

And in code-behind:
protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
{
try
    {
       GridDataItem dataItem = e.Item as GridDataItem;
       string username = Convert.ToString(dataItem["UserName"].Text);
       Label1.Text = "jkjh";

       MembershipUser user = Membership.GetUser(username.ToString());
       Membership.DeleteUser(user.UserName.ToString(),true);
    }
...
}


text:
Q: Number of distinct necklaces using K colors I have a task to find the number of distinct necklaces using K colors.

Two necklaces are considered to be distinct if one of the necklaces
  cannot be obtained from the second necklace by rotating the second
  necklace by any angle .
  Find the total number of distinct necklaces modulo 10^9+7.

I think this formula is good to solve a problem:

And I implemented a program using C++:
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;
const int M = 1e9 + 7;

int main()
{
    long long  n, k;
    cin >> n >> k;

    long long x = 0;
    for (int i = 1; i <= n; ++i) {
        x += pow(k, __gcd(i,n));
    }

    cout << x/n % M;
    return 0;
}

I paste my code to program with test cases but my solution passed half of test cases. I can't find my mistake and I see only one test case.
First test case is n = 5 and k = 2, and answer is 8.
Where I could make a mistake? I'm not about code, maybe I wrong with this formula? Maybe I need to use another formula?

A: There are a few problems with your code. Firstly, $\verb+x+$ is going to get very large very quickly, and you will get an integer overflow even using $\verb+long long+$ for the type for $\verb+x+$. For example, when $n=64$ and $k = 2$, one of the terms in your sum is $2^{64}$, which is already larger than the value which can be stored in a $\verb+long long+$.
What you will want to do instead (since it seems that you have to output your answer modulo $10^9+7$) is to calculate $k^{\gcd(i,n)}$ modulo $10^9+7$ before adding it to $x$, and then also mod the result with $10^9+7$ so that your value of $\verb+x+$ is always less than $10^9 + 7$.
You then get another problem though. When you want to divide by $n$ later, you can't simply do the division as $\verb+x/n+$. Since we now only have the value of $x$ modulo $10^9+7$, we also have to do the division modulo $10^9+7$. To do this, you will have to calculate the inverse of $n$ modulo $10^9+7$ and multiply $\verb+x+$ by this number.


text:
Q: Help with permissions I am trying to set up permissions, but I don't know what exactly, as a user.
Could anyone tell me which permission will allow me to execute the touch and echo commands in a directory?

A: Everyone should be able to execute the echo command.  If you can't there's something seriously wrong with your Linux install.  To run touch you need to have write access to the destination directory.


text:
Q: Google App Engine - Writing app.yaml for a particular url like applicationName.appspot.com/docs/ec-quickstart/index.html I have a google app engine application and I am using python 27.
I want my url when deployed to be applicationName.appspot.com/docs/ec-quickstart/index.html
How do I write my app.yaml file?
The code below loads my index.html file without the css.
  handlers:

  - url: /docs/ec-quickstart/index.html
  static_files: docs/ec-quickstart/index.html
  upload: docs/ec-quickstart/index.html

However, if I change my file to
  handlers:

  - url: /(.*)
  static_files: docs/ec-quickstart/\1
  upload: docs/ec-quickstart/(.*)

  - url: /docs/ec-quickstart/index.html
  static_files: docs/ec-quickstart/index.html
  upload: docs/ec-quickstart/index.html

Everything loads properly with the css for the url applicationName.appspot.com
I want the url to be mapped to applicationName.appspot.com/docs/ec-quickstart/index.html

A: You need to specify rules for every piece you're going to serve and construct your html to reference them accordingly. Pay attention to the patterns as the 1st match will be used even if a more specific one follows below.
The 1st attempt doesn't specify where your .css file exists.
The 2nd attempt suggests your .css file is in the same directory with the index.html file and are both served using just the 1st rule (index.html matches as well, the 2nd rule is not actually used).
So you could use just one rule matching both file but modify the html to reference the css as /docs/ec-quickstart/blah.css:
  - url: /docs/ec-quickstart/(.*)
  static_files: docs/ec-quickstart/\1
  upload: docs/ec-quickstart/(.*)

Or still use 2 rules (and possibly more for other pieces but make sure the respective patterns don't match index.html) with no html modification:
  - url: /(.*\.css)$
  static_files: docs/ec-quickstart/\1
  upload: docs/ec-quickstart/(.*\.css)$

  - url: /docs/ec-quickstart/index.html
  static_files: docs/ec-quickstart/index.html
  upload: docs/ec-quickstart/index.html

A: The answer suggested by Dan Cornilescu works perfectly. For anyone else out there who has the same problem, here's another approach which I figured out.
  handlers:

  - url: /docs/ec-quickstart
    static_dir: docs/ec-quickstart


text:
Q: Proxy NDP, intermittent Address Unreach I've configured NDP proxying on my Digital Ocean droplet to allow containers to obtain public IPv6 addresses.  It seems to work, but occasionally I'll get Destination Unreachable (Address Unreachable) errors.  It seems that while this occurs the neighbor's table on the container host shows the router reachability as INCOMPLETE (show as x:x:x:x::1).  Then, randomly, it'll start working again.  Why is this happening, and is there anything I can do to fix it?
Host configuration:
# ip -6 address show
<...>
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP qlen 1000
    inet6 x:x:x:x::x:5000/64 scope global
       valid_lft forever preferred_lft forever
3: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP qlen 1000
<...>
# ip -6 route show | grep -v fe80::/64
x:x:x:x::x:5000/124 dev br0 metric 128  pref medium
x:x:x:x::/64 dev eth0 proto kernel metric 256  pref medium
default via x:x:x:x::1 dev eth0 metric 1024  pref medium
# ip -6 neigh show proxy
x:x:x:x::x:5000 dev br0  proxy
x:x:x:x::x:5001 dev eth0  proxy
# sysctl net.ipv6.conf.{all,br0,eth0}.{forwarding,proxy_ndp}
net.ipv6.conf.all.forwarding = 1
net.ipv6.conf.all.proxy_ndp = 0
net.ipv6.conf.br0.forwarding = 1
net.ipv6.conf.br0.proxy_ndp = 1
net.ipv6.conf.eth0.forwarding = 1
net.ipv6.conf.eth0.proxy_ndp = 1

Guest configuration:
# ip -6 address show
<...>
2: host0@if4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP qlen 1000
    inet6 x:x:x:x::x:5001/124 scope global
<...>
# ip -6 route show | grep -v fe80::/64
x:x:x:x::x:5000/124 dev host0  proto kernel  metric 256
default via x:x:x:x::x:5000 dev host0  metric 1024


text:
Q: Interest rate program I am just beginning to learn C. So for practice I decided to write a interest rate calculator but for some reason my calculation always comes out as 0 and I can't figure it out. If you can please take a look.
#include <stdio.h>

main()
{

int time;
float principle, rate, total;

printf("What is your starting amount? ");
scanf(" %f", &principle);
printf("What is your interest rate? ");
scanf(" %f", &rate);
printf("How long do you want to save? ");
scanf(" %d", &time);

total = principle * rate * time;
printf("You will have earned an interest amount of $%d", total);
return 0;
}

A: printf("You will have earned an interest amount of $%d", total);

Since total is a float, %d should be %f. Also, it's a nice touch to throw in a new line at the end of each line.
printf("You will have earned an interest amount of $%f\n", total);


text:
Q: How do I draw a rectangle with OpenGL ES 2.0 in iOS ? I have been learning and using Objective-C and cocos2d (iOS game-engine) for a couple of years now and so I decided to start with OpenGL ES for iOS devices. I have started reading a book that covers this topic, however with little background in this area I have to admit that I am a little lost. I am a really practical person and I only learn by doing things myself. The book does give some nice examples, but unfortunately mostly covers triangular shapes.
So, I have a couple of questions regarding OpenGL:

*

*Do vertices really need to be declared in a counter-clockwise order to prevent culling ?

*Does OpenGL really draw all shapes based on triangles ?

*If so, how would I draw a rectangle ?

I would really appreciate it if somebody could write a quick vertex array sample of how to achieve to draw a rect on the screen. No need for the buffers or anything, really just the vertices of the rectangle.

A: OpenGl ES 2.0 supports the following rendering types: GL_POINTS, GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, and GL_TRIANGLES.
If you ignore the ones for drawing points and lines you can choose between triangle strips, triangle fans and simple triangles. To draw a rectangle you can easily use two triangles.
To specify the ordering for face culling you can use glFrontFace. However its common practise (as far as i know) to use counter clockwise ordering.
If you have problems finding good opengl es 2.0 tutorials for ios you should maybe look for some tutorials on some plattforms. WebGL and Android are also using opengl es 2.0 and (except the syntax) the code will look nearly identical.


text:
Q: Script works fine in Rstudio but not in Rscript I would like to schedule a R script which works fine via Rstudio. But when try to run the script with Rscript I got an error. The script take some parameters in a csv file and try to gather data on opentsdb.
library(devtools)
install_local("/home/me/Downloads/opentsdbr-master")
install_local("/home/me/Downloads/nomalyDetection-master")
install_local("/home/me/Downloads/anomalydots", force="TRUE")
install_local("/home/me/Downloads/RAD")
library(reticulate)
library(anomalydots)
lbrary('methods')

l <- read.csv(file = "/home/bbtex/Downloads/metrics_list.csv", sep = ",")
n <- length(l$metrics)
for (i in 1:n){
  tag=as.character(l$tags[i])
  metric=as.character(l$metrics[i])
  tag=eval(parse(text=paste("c(",tag,")",sep="")))
  newdata=getTsOpenTSDBOptimized(metric=metric,hostname="opentsdb-read.intcs.meshcore.net",port=4242,downsample=10,endDate=as.character(Sys.Date()),agg=l$agg[i],tags=tag)
  newdata = anomalydots::fillHoles2(newdata)
  newdata = anomalydots::timeSeriePreparation(newdata)
  timeseries[[i]] <- newdata
}
print ("Upload completed successfully")

When I run the following code with Rscript I have the following error:

Error in tsd_get_ascii(metric, interval, tags, agg, rate, downsample,
  :
      Calls: getTsOpenTSDBOptimized -> getTsOpenTSDB -> tsd_get -> tsd_get_ascii
      In addition: Warning messages:
      1: In tsd_get_ascii(metric, interval, tags, agg, rate, downsample,  :
        Response code 503
      2: In tsd_get_ascii(metric, interval, tags, agg, rate, downsample,  :
        URL: http://opentsdb-read.intcs.meshcore.net:4242/q?start=2018%2F10%2F19-02%3A00%3A00&m=avg%3A600s-sum%3Adb.mysql.threads_connected%7Bhost%3Dbpct4005s%7D&end=2018%2F10%2F22-01%3A59%3A59&ascii=
      Execution halted

When I follow the link in the error, I can see the data printed in the webpage.
Thank you in advance for your help


text:
Q: Difference between std::vector::back and vector::operator[ vector::size() - 1] is there a difference between:
mvt_act_idx = openCloseList.size()-1;
openCloseList[mvt_act_idx].A += a;

and
 openCloseList.back().A += a;

Besides readability?

A: mvt_act_idx = openCloseList.size()-1;
openCloseList[mvt_act_idx].A += a;

If openCloseList is empty the unsigned subtraction will produce a huge value, which then is used to index the vector. The indexing operator may assert, or not.
openCloseList.back().A += a;

If openCloseList is empty the back operation may assert, or not.
In the case of such error, a fault in back is probably easier to understand.
And anyway, the first code snippet can be in conflict with some guideline to not use unsigned integers as numbers (except where the modulo behavior simplifies and clarifies the code), while the call to back can not be in conflict with any such guideline.

A: No useful difference.
Using back() directly might be fractionally more efficient, but I doubt it. You could have a look at the generated assembler if you felt really keen. Might make the difference of an instruction or two, depending on how clever your compiler is.
I do note that the former way which uses only size() and [] would be a lot more familiar to people who understand arrays or use similar contructs in any other language; back() is a bit more C++ specific (though it is hardly a cryptic idiom).


text:
Q: Shopify tags - Avoiding duplicate content I used below code to prevent duplicate content. Everything works fine except ALL PRODUCT URL with tags(collections/all/red) are pointing to homepage as canonical.
{% if template contains 'collection' and current_tags %} <meta name="robots" content="noindex" /> <link rel="canonical" href="{{ shop.url }}{{ collection.url }}" /> {% else %} <link rel="canonical" href="{{ canonical_url }}" /> {% endif %}

A: It may be that collections/all sometimes behave in weird way. The best solution is to manually create collection all, with automatic rule like: include all products with name not equal to "!@#" or similar.
The collections/all exists on each shopify store, even if you cannot see this collection in admin panel. Sometimes it helps to overwrite this collection by creating another one with same handle


text:
Q: keycloak stops working when enabling tls behind nginx ingress controller I need advice on how to configure nginx ingress controller and keycloak on eks kubernetes with TLS.
My first attempt was to get keycloak working without TLS. This works fine. But when I add TLS to the ingress definition, keycloak gives a Invalid parameter: redirect_uri error.
This is the working sample:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: keycloak-tls-test
  namespace: keycloak-tls-test
spec:
  rules:
  - host: keycloak.test.myhops.com
    http:
      paths:
      - backend:
          serviceName: keycloak
          servicePort: 80

When I add the tls part, I get the aforementioned error. See yaml file below.
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: keycloak-tls-test
  namespace: keycloak-tls-test
spec:
  tls:
  - hosts:
    - keycloak.test.myhops.com
    secretName: test-myhops-tls
  rules:
  - host: keycloak.test.myhops.com
    http:
      paths:
      - backend:
          serviceName: keycloak
          servicePort: 80

Any suggestions on how to solve this? One online suggestion was to add https://keycloak.test.myhops.com/* to the Valid Redirect URL for the security-admin-console client in the master realm. This solved the invalid redirect_uri error, but then I only got blank pages. I could not find hints in the keycloak logging.

A: I figured out what caused the problem. It seems that when keycloak is used behind a reverse proxy that terminates the TLS, then keycloak needs proxy-address-forwarding to be set. For the docker container this means that the env var PROXY_ADDRESS_FORWARDING=true does the trick. So Ingress was correct and the keycloak deployment needed an extra environment variable.
Please not that ingress-nginx already set the correct headers for this to work:

*

*X-Forwarded-For

*X-Forwarded-Proto

Docker documentation
[keycloak documentation2


text:
Q: Crockford's module for secure objects I understand there's loads of questions and documentation around "Javascript: The Good Parts" but I'm trying to understand the meaning of a sentence in the book and can't quite get it. In the pages 41-42 he defines the serial_maker function:
var serial_maker = function (  ) {

// Produce an object that produces unique strings. A
// unique string is made up of two parts: a prefix
// and a sequence number. The object comes with
// methods for setting the prefix and sequence
// number, and a gensym method that produces unique
// strings.

    var prefix = '';
    var seq = 0;
    return {
        set_prefix: function (p) {
            prefix = String(p);
        },
        set_seq: function (s) {
            seq = s;
        },
        gensym: function (  ) {
            var result = prefix + seq;
            seq += 1;
            return result;
        }
    };
};

var seqer = serial_maker();
seqer.set_prefix('Q');
seqer.set_seq(1000);
var unique = seqer.gensym(); // unique is "Q1000"

And then he says:

The methods do not make use of this and that. As a result, there is no way to compromise the sequer. It isn't posible to get or change the prefix or seq except as permitted by the methods

How should I use this and/or that to break that encapsulation? I can't see it
Thanks

A: Consider the variation below:
var serial_maker = function () {
    return {
        prefix: '',
        seq: 0,

        set_prefix: function (p) {
            this.prefix = String(p);
        },
        set_seq: function (s) {
            this.seq = s;
        },
        gensym: function (  ) {
            var result = this.prefix + this.seq;
            this.seq += 1;
            return result;
        }
    };
};

Now, the intended use of the sequer is the following:
var sequer = serial_maker();
sequer.set_prefix('right');
sequer.set_seq(1000);

However, in the version I posted above, you could also do this:
var sequer = serial_maker();
sequer.prefix = 'wrong';
sequer.seq = -500;

Or even this:
delete sequer.prefix;

Since both prefix and seq are exposed as properties of the sequer object, and properties in JavaScript are always public. Any code that has access to the object can at least read its properties, and usually modify them as well (unless you use some of the features provided by Object.defineProperty()).
As for that: before arrow functions were introduced, it was a very common problem that functions defined as methods weren't able to access the context where they were created.
Consider the following example:
var ButtonInitializer = {
    message: 'Hello!'

    init: function() {
        for (let button of document.querySelectorAll('button')) {
            button.onclick = function() {
                alert(this.message);
            }
        }
    }
};

ButtonInitializer.init();

The object ButtonInitializer searches the document for <button> elements and sets their onclick event listener to display an alert; our intention is to show the message defined in ButtonInitializer.message. However, if you run the above code, you'll find that the alert is "undefined". This is because the function we assign to button.onclick becomes a method of the button, so the this keyword inside the function will now refer to the button, and not the ButtonInitializer.
Today, we can solve this with an arrow function:
button.onclick = () => {
    alert(this.message);
}

Arrow functions don't have their own this scope, so the alert will display ButtonInitializer.message, as we meant. Before arrow functions were introduced, this was a common workaround:
var that = this;
button.onclick = function() {
    alert(that.message);
}

This technique was used very commonly together with closures, and allowed a limited implementation of "private" members that the object's methods could access, but weren't directly visible from outside code.

A: There are two popular ways of creating objects from a function in JavaScript:

*

*The factory pattern

*The constructor pattern (Better illustrated using ES6 class)

The factory Pattern
In this example, he is using and referring to the factory pattern, which does not make use of the new keyword and also does not create a this binding on the newly created object. It only creates a new object and returns it as a value of the function expression, thus why it is called a factory.
Factory functions are the best way to create true object private attributes in JavaScript, thus encapsulation using closure. Because there is no this binding, you cannot access the variables prefix and seq that are encapsulated within the factory function. Using this pattern is the only way to create fully-private encapsulated object "property" in JavaScript (in comparison to Java's use of private.)

How should I use this and/or that to break that encapsulation?

You would re-factor that code using the Constructor Pattern (Make it into a constructor) which would look like this (using ES6):
class SerialMaker {
    // Creates a `this` binding to the instance of the class
    // No actual encapsulation on the private properties
    constructor () {
        // PSEUDO-PRIVATE PROPERTIES
        this.__prefix__ = '';
        this.__seq__ = 0;
        // METHODS
        this.set_prefix: function (p) {
            this.__prefix__ = String(p);
        };
        this.set_seq: function (s) {
            this.__seq__ = s;
        };
        gensym: function (  ) {
            var result = this.__prefix__ + this.__seq__;
            this.__seq__ += 1;
            return result;
        };
    }

Now, you can create new object using the new operator
var seqer = new SerialMaker(); // Calls the constructor and creates a new instance object
seqer.set_prefix('Q'); // Set on this instance only: this.__prefix__
seqer.set_seq(1000); // Set on this instance only: this.__seq__
var unique = seqer.gensym(); // unique is "Q1000"

Same thing up to this point, but the problem is...
sequer.__prefix__ // => 'Q' // What??? This was supposed to be private!
sequer.__seq__ = 2000 // Works with no error

... the encapsulation is completely broken. The seqer is compromised.


text:
Q: Why Doesn't Hibernate Just Shut Down Without Clearing the RAM Most people know that RAM memory is cleared when shutting down a computer. Since RAM is a type of memory/storage, why can't we just keep everything in the RAM, and shutdown without clearing it. Therefor, when the computer turns on, it doesn't take a good ten seconds to read a few gigabytes of data from the hard drive, and push it into RAM. This would be much faster, and not require swap partitions or pagefiles.

A: It sure can. That is called 'Sleep Mode'.
It uses a small amount of power, as the memory needs power to remember the content. if you want to have no power usage, you need to put the content on a non-volatile place, which is the hard disk, and it takes a moment to write it there.


text:
Q: Python - strings and numbers in array, want to sum all numerical values in row, and append value to end of row Beginner here. I just started trying to learn Python yesterday as sort of a summer project.
I have a CSV that I stored as an array. Its a little bigger than this example but if you can show me how to do it on this one, I can probably extrapolate it.
Bob  |  10  |  15  |  20
Jim  |  20  |  23  |  32
Sue  |  03  |  21  |  09

I'd like to add a column to the end of the table that sums the values, obviously ignoring the strings in the first column. So to get something like this:
Bob  |  10  |  15  |  20  |  45
Jim  |  20  |  23  |  32  |  75
Sue  |  03  |  21  |  09  |  33

So far I have code something like this
import numpy
import csv
vlhpcsv = open('file.csv')
importeddata = csv.reader(vlhpcsv)

from numpy import genfromtxt
genfromtxt_vlhp = genfromtxt('file.csv',delimiter=',', skip_header=1, dtype=None, usecols=(9,10,11,19,21,22))

relevant_columns = numpy.array(genfromtxt_vlhp)

print(relevant_columns)

This does what I expect, and shows me a pared-down version of the original CSV, with just the data I care about. Any attempt to try to sum and append afterward though, is met with a "cannot perform reduce with flexible type" error. I know this is because of the strings in the first column; I just don't know what to do about it. Thanks!

A: I would use pandas.read_csv:
import  pandas as pd

df = pd.read_csv("test.csv")

df["tot"] = df.sum(axis=1)
print(df)

Input:
name,v1,v2,v3
Bob,10,15,20
Jim,20,23,32
Sue,03,21,09

Output:
 name  v1  v2  v3  tot
0  Bob  10  15  20   45
1  Jim  20  23  32   75
2  Sue   3  21   9   33

To save the data to csv you just need to_csv using header=False if you don't want a header and with index=False  to output without row names/indexes:
df.to_csv("test2.csv", index=False,header=False)

Output:
Bob,10,15,25
Jim,20,23,43
Sue,3,21,24

You can specify the columns to use with usecols the same way, using axis=1 will sum the rows and any non numeric cols data will be ignored.

A: Since you said you're a beginner, I'm going to ask if you have an explicit reason to be using numpy. What you're doing in this specific scope doesn't really call for it, so it might be easier for you to take advantage of Python's built-in csv handling:
import csv

output_rows = []

# Open the input file with Python's built-in open()
with open('file.csv', 'r') as csvfile:
    # Create a Reader object pointing to the csv file
    reader = csv.reader(csvfile, delimiter=',')
    # Use the Reader to loop through each row in the csv
    for row in reader:
        sum = 0
        # Each row is given to us a list; loop through that list
        # to gather up all the numbers and sum them
        # Note the [1:] says "start at position 1 (the second element)
        # and continue to the end of the list"
        for number in row[1:]:
            sum += float(number)
        # We'll give output_rows a new row that's the original
        # row + the computed sum at the end
        output_rows.append(row + [sum])

# Open the output file, passing 'w' to note it's in write mode
with open('output.csv', 'w') as outputfile:
     # Make a csv Writer object with the file
     writer = csv.writer(outputfile, delimited=',')
     for row in output_rows:
         # Write each row to the file using writerow(), which takes
         # a list and prints it to the file, using the specified delimiter
         # to separate each entry
         writer.writerow(row)


text:
Q: Is it possible to move an app to a split view / a slider over view programmatically inside ui test after an app running? I want to test that some functionality works in a split/a slide over view.
My current ui test opens the dock panel and tries to drag the iMessage app to the right border of a simulator's screen.
Looks like that any interaction doesn't work with elements which are not related to my app.
Is it possible to move an app to a split view or a slider over view programmatically inside ui test after an app running?

A: It is possible on older iOS versions. However, it will need to be done manually using coordinates as far as I'm aware. There is an existing helper repo I found here that might help (I've not used it though) https://github.com/superz515/UITestingMultitaskingHelper.
iOS 15 makes this slightly easier with the multi-task support UI.

If you observe the springboard application in XCUITest process you will see:
Default state:
Button, 0x600001a02d80, {{1004.5, 667.0}, {14.0, 32.0}}, identifier: 'top-affordance:XCUITestSplit', label: 'XCUITestSplit, Multitasking controls'

After tapping the control:
Button, 0x600001431340, {{968.0, 609.0}, {40.0, 40.0}}, identifier: 'top-affordance-full-screen-button', label: 'Full screen', Selected
Button, 0x600001431500, {{968.0, 663.0}, {40.0, 40.0}}, identifier: 'top-affordance-split-view-button', label: 'Split view'
Button, 0x6000014316c0, {{968.0, 717.0}, {40.0, 40.0}}, identifier: 'top-affordance-slide-over-button', label: 'Slide over'

After tapping an option:
BannerNotification, 0x600001a38000, {{966.0, 574.5}, {50.0, 217.5}}
    Button, 0x600001a380e0, {{966.0, 574.5}, {50.0, 217.5}}, label: 'Split View, Choose another app'

Icons example
Icon, {{0.0, 0.0}, {0.0, 0.0}}, identifier: 'Files', label: 'Files'
Icon, {{0.0, 0.0}, {0.0, 0.0}}, identifier: 'Reminders', label: 'Reminders'
Icon, {{0.0, 0.0}, {0.0, 0.0}}, identifier: 'News', label: 'News'
Icon, {{0.0, 0.0}, {0.0, 0.0}}, identifier: 'Calendar', label: 'Calendar'
Icon, {{0.0, 0.0}, {0.0, 0.0}}, identifier: 'Reminders', label: 'Reminders'
Icon, {{0.0, 0.0}, {0.0, 0.0}}, identifier: 'Maps', label: 'Maps'
Icon, {{0.0, 0.0}, {0.0, 0.0}}, identifier: 'News', label: 'News'
Icon, {{0.0, 0.0}, {0.0, 0.0}}, identifier: 'Settings', label: 'Settings'
Icon, {{810.5, 155.0}, {95.5, 77.0}}, identifier: 'Shortcuts', label: 'Create XCUITestSplit split view with Shortcuts'
Icon, {{810.5, 353.0}, {95.5, 72.5}}, identifier: 'Contacts', label: 'Create XCUITestSplit split view with Contacts'
Icon, {{810.5, 548.0}, {95.5, 75.0}}, identifier: 'Magnifier', label: 'Create XCUITestSplit split view with Magnifier'

Example
The above can get you in split view pretty quickly.
However more control over how many columns requires moving the divider which is a bit more work (as I mentioned earlier), and you also need to consider resetting the state so the app doesn't launch again in split view.
func testExample() throws {
    let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
    let app = XCUIApplication()

    app.launch()
    springboard.buttons["top-affordance:XCUITestSplit"].tap()
    springboard.buttons["top-affordance-split-view-button"].tap()
    springboard.icons["Shortcuts"].firstMatch.tap()
}

Gif (tap to watch, forgive orientation)


text:
Q: How to transition something in a  when hovering over that  circle style
.circle
{

background-color: white;
height: 120px;
width: 120px;
border-radius: 70px;
box-shadow: 2px 2px 5px;
border-top-color: black;
margin: auto;
border-width: 5px;
border-bottom-color: blue;
transition-timing-function: ease-in;
transition-duration: 1.2s;
margin-top: 70px;
transition-property: transform, transform;
animation-timing-function: ease-in;
animation-duration: 1s;
animation-name: animation;
}

circle transition
.circle:hover
{

transform: rotateY(180deg);

}

text I want to fade with the circles transition
.circle-text
{

font-family: Verdana;
font-style: bold;
color: black;
margin-left: 43px;
padding-top: 50px;
line-height: 120px;
font-size: 13px;
transition-duration: 1s;
transition-timing-function: ease-in ;

}

I want this text to fade with the transition of the circle. How can I
make it so when I hover over the circle it does that?

 Hello

A: 1- Style the text opacity when hover on circle
2- Add transition: opacity 0.4s and transition-delay: 0.6s to balance between the animation and the fade
Check 'Added' comment

Add the new properties to the selectors for DRY coding

.circle{
    background-color: white;
    height: 120px;
    width: 120px;
    border-radius: 70px;
    box-shadow: 2px 2px 5px;
    border-top-color: black;
    margin: auto;
    border-width: 5px;
    border-bottom-color: blue;
    transition-timing-function: ease-in;
    transition-duration: 1.2s;
    margin-top: 70px;
    transition-property: transform, transform;
    animation-timing-function: ease;
    animation-duration: 1s;
    animation-name: animation;
}

.circle:hover{
    transform: rotateY(180deg);
}

.circle-text{
    font-family: Verdana;
    font-style: bold;
    color: black;
    margin-left: 43px;
    padding-top: 50px;
    line-height: 120px;
    font-size: 13px;
    transition-duration: 1s;
    transition-timing-function: ease-in ;
}

/*ADDED:*/
.circle:hover .circle-text {
    opacity: 0;
}

.circle-text{
  transition: opacity 0.4s;
  transition-delay: 0.6s;
}

  Hello


text:
Q: How to calculate the duration between Phase I have the following history table (record user action):
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| parent_id | property_names                                                          | changed_property                                                                                | time_c        | outcome |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| 123456    | {PhaseId,LastUpdateTime}                                                | {"PhaseId":{"newValue":"Fulfill","oldValue":"Approve"},"LastUpdateTime":{"newValue":1671027321749,"oldValue":1671027321170}}                                                                                | 1671027321749 | success |
| 123456    | {PhaseId,LastUpdateTime,ApprovalStatus}                                 | {"PhaseId":{"newValue":"Approve","oldValue":"Log"},"LastUpdateTime":{"newValue":1671011168777,"oldValue":1671011168043},"ApprovalStatus":{"newValue":"InProgress"}}                                                                                | 1671011168777 | success |
| 123456    | {LastUpdateTime,PhaseId,Urgency}                                        | {"LastUpdateTime":{"newValue":1671011166077},"PhaseId":{"newValue":"Log"},"Urgency":{"newValue":"TotalLossOfService"}}                                                                                | 1671011166077 | success |
| 123456    | {LastUpdateTime,ApprovalStatus}                                         | {"LastUpdateTime":{"newValue":1671027321170,"oldValue":1671027320641},"ApprovalStatus":{"newValue":"Approved","oldValue":"InProgress"}}                                                                                | 1671027321170 | success |
| 123456    | {PhaseId,LastUpdateTime,ExecutionEnd_c}                                 | {"PhaseId":{"newValue":"Accept","oldValue":"Fulfill"},"LastUpdateTime":{"newValue":1671099802675,"oldValue":1671099801501},"ExecutionEnd_c":{"newValue":1671099802374}}                                                                                | 1671099802675 | success |
| 123456    | {PhaseId,LastUpdateTime,CompletionCode}                                 | {"PhaseId":{"newValue":"Review","oldValue":"Accept"},"LastUpdateTime":{"newValue":1671099984979,"oldValue":1671099982723},"CompletionCode":{"oldValue":"CompletionCodeAbandonedByUser"}}                                                                                | 1671099984979 | success |
| 123456    | {PhaseId,LastUpdateTime,ExecutionStart_c}                               | {"PhaseId":{"newValue":"Fulfill","oldValue":"Review"},"LastUpdateTime":{"newValue":1671100012012,"oldValue":1671099984979},"ExecutionStart_c":{"newValue":1671100011728,"oldValue":1671027321541}}                                                                                | 1671100012012 | success |
| 123456    | {UserAction,PhaseId,LastUpdateTime,ExecutionEnd_c}                      | {"UserAction":{"oldValue":"UserActionReject"},"PhaseId":{"newValue":"Accept","oldValue":"Fulfill"},"LastUpdateTime":{"newValue":1671100537178,"oldValue":1671100535959},"ExecutionEnd_c":{"newValue":1671100536730,"oldValue":1671099802374}}                                                   | 1671100537178 | success |
| 123456    | {PhaseId,Active,CloseTime,LastUpdateTime,LastActiveTime,ClosedByPerson} | {"PhaseId":{"newValue":"Close","oldValue":"Accept"},"Active":{"newValue":false,"oldValue":true},"CloseTime":{"newValue":1671101084529},"LastUpdateTime":{"newValue":1671101084788,"oldValue":1671101083903},"LastActiveTime":{"newValue":1671101084529},"ClosedByPerson":{"newValue":"511286"}} | 1671101084788 | success |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Description of the column :
parent_id : link to the parent element
property_names : property having a modification
changed_property : New value for the properties. for ex:
{
   "PhaseId":{
      "newValue":"Fulfill",
      "oldValue":"Approve"
   },
   "LastUpdateTime":{
      "newValue":1671027321749,
      "oldValue":1671027321170
   }
}

The property PhaseId change the value from Approve to Fulfill
time_c : Unix Timestamp of the update
outcome : Status of the update
My goal is to calculate the duration of each phase.
Expected output :
------------------------------------------------------------
| parent_id | Log  | Approve  | Fulfill  | Accept | Review |
------------------------------------------------------------
| 123456    | 2700 | 16152972 | 73006092 | 729914 | 27033  |
------------------------------------------------------------

Log : 1671011168777 - 1671011166077 = 2700
Approve : 1671027321749 - 1671011168777 = 16152972
Fulfill : (1671100537178 - 1671100012012) + (1671099802675 - 1671027321749) = 73006092
Accept : (1671101084788 - 1671100537178) + (1671099984979 - 1671099802675) = 729914
Review : 1671100012012 - 1671099984979 = 27033
At this moment, I'm able to retreive the new and old value of the PhaseId and convert the unix timestamp to datetime.
My issue is how to calculate the duration of a phase using SQL
My current SQL request :
SELECT * FROM
(SELECT
  parent_id,
  property_names,
  changed_property,
  time_c,
  to_char(to_timestamp(time_c/1000.0) at time zone 'Europe/Paris', 'yyyy-mm-dd hh24:mi:ss') AS "time to datetime",
  outcome,
  changed_property::json->'PhaseId'->> 'newValue' AS "PhaseId (new)",
  changed_property::json->'PhaseId'->> 'oldValue' AS "PhaseId (old)"
FROM history
WHERE array_to_string(property_names, ', ') like '%PhaseId%'
ORDER BY time_c DESC) AS temp_c
/*
WHERE "PhaseId (new)" = 'Close'
OR "PhaseId (old)" = 'Close'
*/

DB fidle : https://www.db-fiddle.com/f/ckqtYy3EuASF4RdF9dSEcv/2


text:
Q: What's the simplest way to request information from (own) other applications The company that I work for has some small android applications running that communicate with their ERP software lately they requested to authenticate users and have sessions for safety reasons
Instead of integrating the autheticate and session code into every app (6) I want to build an Android app that acts like a dashboard. The app will authenticate the user, create a session and show the available apps on the device that the user can access with their user role.
The problem is I need the know which app requires which user role
I don't want to store this information in the dashboard app sinds that will require me to update the dashboard app each time i create or change an app
I was thinking or using an Content provider but that seems to be a lot of work and redundant since it has to be integrated into every app that I have (6)
So my question, is there a way to get data from apps that can easily be implemented. The data isn't big (only one Integer)
thanks in advance.


text:
Q: MongoDb Summing multiple columns I'm dabbling in mongoDb and trying to use map reduce queries. I need to sum up multiple values from different columns (num1, num2, num3, num4, num5). Going off this guide http://docs.mongodb.org/manual/tutorial/map-reduce-examples/ . There I'm trying to alter the first example there to sum up all the values.
This is what I am trying/tried. I'm not sure if it can take in multiple values like this, I just assumed.
var query1 = function(){ emit("sumValues", this.num1, this.num2, this.num3, this.num4, this.num5)};

    var query1query = function(sumValues, totalSumOfValues){ return Array.sum(totalSumOfValues); }

    db.testData.mapReduce( query1, query1query, {out: "query_one_results"})

This is the error I get.
Sun Dec  1 18:52:24.627 JavaScript execution failed: map reduce failed:{
        "errmsg" : "exception: JavaScript execution failed: Error: fast_emit takes 2 args near 'ction (){ emit(\"sumValues\", this.c' ",
        "code" : 16722,
        "ok" : 0
Is there another way to sum up all these values? Or where is my error in what I have.
I also tried this and it seemed to work. but when I do a .find() on the file it creates it only seems to be retrieving the values of sum5 and adding them together.
var query1 = function(){ emit({sum1: this.sum1,sum2: this.sum2,sum3: this.sum3,sum4: this.sum4,sum5:  this.sum5},{count:1});}
 var query1query = function(key, val){ return Array.sum(val); };
 db.testData.mapReduce( query1, query1query, {out: "query_one_results"})
{
        "result" : "query_one_results",
        "timeMillis" : 19503,
        "counts" : {
                "input" : 173657,
                "emit" : 173657,
                "reduce" : 1467,
                "output" : 166859
        },
        "ok" : 1,
}

Ok I think I got it. This is what I ended up doing
> var map1= function(){
... emit("Total Sum", this.sum1);
... emit("Total Sum", this.sum2);
... emit("Total Sum", this.sum3);
... emit("Total Sum", this.sum4);
... emit("Total Sum", this.sum5);
... emit("Total Sum", this.sum6);
… };

> var reduce1 = function(key, val){
... return Array.sum(val)
... };
> db.delayData.mapReduce(map1,reduce1,{out:'query_one_result'});
{
        "result" : "query_one_result",
        "timeMillis" : 9264,
        "counts" : {
                "input" : 173657,
                "emit" : 1041942,
                "reduce" : 1737,
                "output" : 1
        },
        "ok" : 1,
}

> db.query_one_result.find()
{ "_id" : "Total Sum", "value" : 250 }

A: You were getting the two values that you need to emit in map backwards.   The first one represents a unique key value over which you are aggregating something.  The second one is the thing you want to aggregate.
Since you are trying to get a single sum for the entire collection (it seems) you need to output a single key and then for value you need to output the sum of the four fields of each document.
map = function() { emit(1, this.num1+this.num2+this.num3+this.num4+this.num5); }
reduce = function(key, values) { return Array.sum(values);   }

This will work as long as num1 through num5 are set in every document - you can make the function more robust by simply checking that each of those fields exists and if so, adding its value in.
In real life, you can do this faster and simpler with aggregation framework:
db.collection.aggregate({$group:{{$group:{_id:1, sum:{$sum:{$add:["$num1","$num2","$num3","$num4","$num5"]}}}})


text:
Q: NPE in Jenkins/Maven analysis after upgrade to SonarQube 4.2 After some time the analysis throws an NPE. But its not the first module it analyses. So I'm do not have a clue, what the problem might be. With SonarQube 4.1.2 it worked without a problem.
Here the logout of the NPE:
15:06:41 org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.2:sonar (default-    cli) on project XXX: Can not execute SonarQube analysis
15:06:41    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:216)
15:06:41    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
15:06:41    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
15:06:41    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
15:06:41    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
15:06:41    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
15:06:41    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
15:06:41    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:317)
15:06:41    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:152)
15:06:41    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:555)
15:06:41    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:214)
15:06:41    at org.apache.maven.cli.MavenCli.main(MavenCli.java:158)
15:06:41    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
15:06:41    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
15:06:41    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
15:06:41    at java.lang.reflect.Method.invoke(Method.java:601)
15:06:41    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
15:06:41    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
15:06:41    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
15:06:41    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
15:06:41 Caused by: org.apache.maven.plugin.MojoExecutionException: Can not execute SonarQube analysis
15:06:41    at org.codehaus.mojo.sonar.Bootstraper.executeMojo(Bootstraper.java:109)
15:06:41    at org.codehaus.mojo.sonar.Bootstraper.start(Bootstraper.java:67)
15:06:41    at org.codehaus.mojo.sonar.SonarMojo.execute(SonarMojo.java:109)
15:06:41    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:106)
15:06:41    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
15:06:41    ... 19 more
15:06:41 Caused by: org.apache.maven.plugin.MojoExecutionException
15:06:41    at org.sonar.maven.ExceptionHandling.handle(ExceptionHandling.java:37)
15:06:41    at org.sonar.maven.SonarMojo.execute(SonarMojo.java:175)
15:06:41    at org.codehaus.mojo.sonar.Bootstraper.executeMojo(Bootstraper.java:104)
15:06:41    ... 23 more
15:06:41 Caused by: java.lang.NullPointerException
15:06:41    at org.sonar.plugins.java.bridges.DsmSerializer.serializeCell(DsmSerializer.java:86)
15:06:41    at org.sonar.plugins.java.bridges.DsmSerializer.serializeRow(DsmSerializer.java:74)
15:06:41    at org.sonar.plugins.java.bridges.DsmSerializer.serializeRows(DsmSerializer.java:53)
15:06:41    at org.sonar.plugins.java.bridges.DsmSerializer.serialize(DsmSerializer.java:43)
15:06:41    at org.sonar.plugins.java.bridges.DsmSerializer.serialize(DsmSerializer.java:94)
15:06:41    at org.sonar.plugins.java.bridges.DesignBridge.serializeDsm(DesignBridge.java:133)
15:06:41    at org.sonar.plugins.java.bridges.DesignBridge.onProject(DesignBridge.java:83)
15:06:41    at org.sonar.plugins.java.Bridges.saveProject(Bridges.java:76)
15:06:41    at org.sonar.plugins.java.Bridges.save(Bridges.java:67)
15:06:41    at org.sonar.plugins.java.JavaSquidSensor.analyse(JavaSquidSensor.java:87)
15:06:41    at org.sonar.batch.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:79)
15:06:41    at org.sonar.batch.phases.SensorsExecutor.execute(SensorsExecutor.java:70)
15:06:41    at org.sonar.batch.phases.PhaseExecutor.execute(PhaseExecutor.java:134)
15:06:41    at org.sonar.batch.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:186)
15:06:41    at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:92)
15:06:41    at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:77)
15:06:41    at org.sonar.batch.scan.ProjectScanContainer.scan(ProjectScanContainer.java:199)
15:06:41    at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:194)
15:06:41    at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:192)
15:06:41    at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:192)
15:06:41    at org.sonar.batch.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:187)
15:06:41    at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:92)
15:06:41    at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:77)
15:06:41    at org.sonar.batch.scan.ScanTask.scan(ScanTask.java:56)
15:06:41    at org.sonar.batch.scan.ScanTask.execute(ScanTask.java:44)
15:06:41    at org.sonar.batch.bootstrap.TaskContainer.doAfterStart(TaskContainer.java:82)
15:06:41    at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:92)
15:06:41    at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:77)
15:06:41    at org.sonar.batch.bootstrap.BootstrapContainer.executeTask(BootstrapContainer.java:144)
15:06:41    at org.sonar.batch.bootstrap.BootstrapContainer.doAfterStart(BootstrapContainer.java:132)
15:06:41    at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:92)
15:06:41    at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:77)
15:06:41    at org.sonar.batch.bootstrapper.Batch.startBatch(Batch.java:92)
15:06:41    at org.sonar.batch.bootstrapper.Batch.execute(Batch.java:74)
15:06:41    at org.sonar.runner.batch.IsolatedLauncher.execute(IsolatedLauncher.java:45)
15:06:41    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
15:06:41    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
15:06:41    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
15:06:41    at java.lang.reflect.Method.invoke(Method.java:601)
15:06:41    at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:87)
15:06:41    at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75)
15:06:41    at java.security.AccessController.doPrivileged(Native Method)
15:06:41    at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69)
15:06:41    at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50)
15:06:41    at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:102)
15:06:41    at org.sonar.runner.api.Runner.execute(Runner.java:90)
15:06:41    at org.sonar.maven.SonarMojo.execute(SonarMojo.java:173)
15:06:41    ... 24 more

A: JIRA ticket created : http://jira.codehaus.org/browse/SONARJAVA-501 with priority "Blocker"

A: Based on this thread it seems to be an issue of plugin not being up to date with SonarCube 4.2. It seems the changes are not backwards compatible.
Latest version of Jenkins plugin is 2.1. It was released in 2013, and since SonarCube 4.2 was just released a month ago, it would look like a new version of the plugin needs to be released for this to work.

A: Just for the record and to provide a more complete answer :
Issue is due to the fact that in one of the directory of your project some of your Java files define multiple packages :
directory  : foo
                file A.java :
                           package foo;
                           class A {....

                file B.java
                           package bar;
                           class B { ....

This is totally supported by javac but it is a bad practice and it is detected by sonar-java analysis and raise the warning :
"Directory contains files belonging to different packages - some metrics could be reported incorrectly: ..."
If the class B is referring some other classes of your project in another directory then it will raise the null pointer exception you are facing.
The fix implemented in sonar-java 2.2 is to raise a specific exception in case you don't have a the skipDesign flag to fail the analysis and invite you either to fix the source code or to use the skipPackageDesign flag.
One question you might ask is why was that working prior to SQ 4.2 and sonar-java 2.1 : This was working because Java was a particular citizen of the SonarQube covered languages and used a specific Object called JavaPackage.
We get rid of that particularity in SQ 4.2 and sonar-java 2.1 and so we are not able anymore to attach metrics correctly if you have multiple packages in one directory. And in the case you raised we even have trouble generating the dependency graph.
Solution is therefore to fix the code by putting files into the directories corresponding to their packages or to skip this dependency analysis using the flag already mentioned.
We provide a better error handling for this in upcoming sonar-java 2.2.


text:
Q: Show Button from Form2 in Form1 C# I Have two form and both contain a button.
And I want to show button1 from Form2 in Form1 But I can't do that !!
I tried everything but no success
Can anyone please help me ??

A: Form1
public class Form1:Form
{
    public Form2 MyFrom { get; set; }
    public void From_Load ( object sender ,EventArgs e)
    {
        MyForm = new Form2();
        MyForm.Show();
    }
    public void btn_Click ( object sender ,EventArgs e)
    {
        MyForm.btn.Visible = true;
    }
}


text:
Q: XAMARIN / Android App installation problem I have a ready XAMARIN/Android App. When i export an APK file and install it on mobile phone the first time, there is no problem. The second time comes error "app not installed". The first time the system asks for permission to install, the second time not.

A: When you install the second time, have you uninstalled the previous version before ?
If not, you need to increment the build number and the version number of your APK before installing, so the system know it's an update.
If you do not increment the build and version number, you will need to uninstall the app before reinstalling it.
You can also try to install it via adb :

*

*Plug your phone in USB and enable USB debugging

*Then in a shell do : adb install <path to apk>


text:
Q: Does the QuorumChain model reward nodes for determining the next block? I know Proof Of Work models such as Bitcoin has mining which rewards the miner for finding the next block. However, do such rewards exist in the QuorumChain model, and why?

A: Quorum is built on ethereum (EVM) and uses a different type of consensus algorithm, which doesn't need any incentive model to create blocks. Also gas price is zero in quorum blockchain, which means even you require certain number of gas to execute tasks on blockchain you don't need to pay in ether, which works fine without creating any new ether in the ecosystem.


text:
Q: In linear regression, why is the hat matrix idempotent, symmetric, and p.s.d.? In linear regression,
   $$y = X \beta + \epsilon$$
where $y$ is a $n \times 1$ vector of observations for the response variable,
$X = (x_{1}^{T}, ..., x_{n}^{T}), x_{i} \in \mathbb{R}^p. i =1,...,n$ is a data matrix of $p$ explanatory variables, and $\epsilon$ is a vector of errors.
Further, assume that $\mathbb{E}[\epsilon_i] = 0$ and $var(\epsilon_i) = \sigma^2, i=1,...n$
The least-squares estimate,
$$\hat{\beta} = (X^{T}X)^{-1}X^{T}y$$
The least-squares estimators are the fitted values,
$$\hat{y} = X \hat{\beta} = X(X^{T}X)^{-1}X^{T}y = X C^{-1}X^{T}y = Py$$
$P$ is a projection matrix. It is has the following properties:

*

*idempotent, meaning P*P = P

*symmetric

*positive semi-definite

For property 1, what's the intuition behind this? How can you take some matrix do transformation, inverse and multiplication, then, you get idempotent. It's an important concept. But, it's hard to follow through the math to get an intuition.
Why will we get property 2 and property 3, How am I supposed to think about this?

A: I believe you're asking for the intuition behind those three properties of the hat matrix, so I'll try to rely on intuition alone and use as little math and higher level linear algebra concepts as possible.
Preliminaries
Start with the fact that the projection matrix $P$ allows you to obtain the orthogonal projection of an arbitrary vector onto the column space of X. Let's use $v_p$ for the  orthogonal projection of $v$:
$$
 P v =  v_p
$$
You can use $P$ to decompose any vector $v$ into two components that are orthogonal to each other. Think of $v_n$ as what is "left over" after the rest of $v$ is projected onto the column space of X, so it is orthogonal to the column space of X (and any vector in the column space of X).
$$
v = v_p + v_n
$$
$$
v_p \perp v_n
$$
1. Why does P * P = P?
Intuitively, projecting a vector onto a subspace twice in a row has the same effect as projecting it onto that subspace once. The second projection has no effect because the vector is already in the subspace from the first projection.
Less intuitive
If that isn't intuitive, it may be easier to consider the equivalent question: why does $P * P v= P v$ for any arbitrary vector v?
Start by simplifying the left hand side:
$$ P * (P v) = P v_p $$
 since $P v = v_p$.
Next consider $ P v_p $, which (by definition of P) projects $v_p$ onto the column space of X. This has no effect since $v_p$ is already entirely in the column space of X. Therefore
$$
P v_p = v_p
$$
Since $v_p = P v$, we conclude:
$$
P v_p = P v
$$
Chaining all these equations together gives:
$$
P * P v= P v
$$
2. Why is P symmetric?
Intuitively, consider two arbitrary vectors $v$ and $w$. Take the dot product of one vector with the projection of the other vector.
$$
(P v) \cdot w
$$
$$
v \cdot (P w)
$$
In both dot products, one term ($P v$ or $P w$) lies entirely in the 'projected space' (column space of X), so both dot products ignore everything that is not in the column space of X. This means both dot products are equal. Some simple dot product identities then imply that $P = P^T$, so $P$ is symmetric.
Less intuitive
If that isn't intuitive, we first prove that both dot products are equal. Decompose $v$ and $w$ as shown in the preliminaries above.
$$
v = v_p + v_n
$$
$$
w = w_p + w_n
$$
The projection of a vector lies in a subspace. The dot product of anything in this subspace with anything orthogonal to this subspace is zero. We use this fact on the dot product of one vector with the projection of the other vector:
$$
(P v) \cdot w \hspace{1cm}  v \cdot (P w)
$$
$$
v_p \cdot w \hspace{1cm}  v \cdot w_p
$$
$$
v_p \cdot (w_p + w_n) \hspace{1cm}  (v_p + v_n) \cdot w_p
$$
$$
v_p \cdot w_p + v_p \cdot w_n \hspace{1cm}  v_p \cdot w_p + v_n \cdot w_p
$$
$$
v_p \cdot w_p  \hspace{1cm}  v_p  \cdot  w_p
$$
Therefore
$$
(Pv) \cdot w = v \cdot (Pw)
$$
Next, we can show that a consequence of this equality is that the projection matrix P must be symmetric. Here we begin by expressing the dot product in terms of transposes and matrix multiplication (using the identity $x \cdot y = x^T y$ ):
$$
(P v) \cdot w = v \cdot  (P w)
$$
$$
(P v)^T w = v^T (P w)
$$
$$
v^T P^T w = v^T P w
$$
Since v and w can be any vectors,  the above equality implies:
$$
P^T = P
$$
3. Why is P positive semidefinite?
By definition a matrix $P$ is positive semidefinite if and only if for every non-zero column vector $v$:
$$
 v^T P v >= 0
$$
or equivalently:
$$
v \cdot (P v) >= 0
$$
Intuitively, a dot product is a projection of one vector onto another vector, and then scaling by the length of the second vector. We want to show that this dot product is non-negative.
In the equation immediately above, $v \cdot (P v)$ means "project $v$ onto $P v$ and scale by $P v$". The first part of this, project $v$ onto $P v$, is equivalent to "project $v$ onto $v_p$", since $P v = v_p $.
Projecting $v$ onto $v_p$ projects $v$ onto something that lies entirely in the column space of X, so this projection is just $v_p$. Next, scaling this $v_p$ by $v_p$ squares its length. A squared length must be non-negative.
Less intuitive
If that isn't intuitive, the dot product can be simplified by decomposing $v$ into orthogonal components
$$
 v \cdot (P v)
$$
$$
 (v_p + v_n) \cdot (P v)
$$
$$
 (v_p + v_n) \cdot  v_p
$$
$$
 v_p \cdot  v_p + v_n \cdot  v_p
$$
Since $v_p$ and  $v_n$ are orthogonal, the second term is zero and we have only
$$
v_p \cdot v_p
$$
The quantity immediately above is the length of the vector $v_p$ squared (i.e., $\|v_p\|_2^2$ ). This must be a non-negative value.
$$
v_p \cdot v_p = \|v_p\|_2^2 >= 0
$$

A: Basically when you have $n$ observations with $p$ unknown coefficients where $n> p$, it means that you have an over-determined system of equations, that is
$$
X\beta = y.
$$
Namely, every subset of $p$ equations will give you another set of $\hat{\beta}$. Hence, you cannot just solve this system of equation rather you have to find an approximate solution. Such a solution lives in the column space of $X$ (as every solution of $Ax=b$ belongs, by definition, to the column space of $A$). Now, you are interested in the "best" solution, namely, a vector $\beta$ that will solve the modified system of linear equations. Namely, instead of solving $X\beta = y$ you can solve $X'X\beta = X'y$ which will have a unique solution w.r.t. $\beta$ and instead of the original $y$ you will have $\hat{y}$ that is a vector that belongs to $C(X)$ and it is the "closest" possible vector in $C(X)$ to the original $y$.
Why it is the best? A matrix $P=A(A'A)^{-1}A'$ is a projection matrix into the column space of $A$ (why it has this specific form you can read in the link that is given in the comments). Why does $P^2 = P$?   Let us see what does $X(X'X)^{-1}X'$ to$x$, where $x \in C(X)$. If $x$ is already in the column space of $X$ thus "projecting" it on $C(X)$ will do nothing, i.e., will return $x$ itself. $P^2 = PP$ is in a sense like projecting set of vectors from $C(X)$ onto $C(X)$, hence you should get $P$ itself.


text:
Q: C++ WriteProcessMemory Doesn't work in 32 bit The Question is in the title
im using write process memory to change some values in memory
i tried it in 64 bit windows and its works perfectly
but the problem is in 32 bit windows it doesn't write the value i want
read process memory works in 64 bit windows and 32 bit windows but the problem is in writing
please help me (:
Edit:
Code is :
    #include "stdafx.h"
    #include <iostream>
    #include <fstream>
    #include <windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Loading..."<< endl;
    int address = 0x3458CBC0;
    int address2 = 0x3458CBC4;
    int value = 20;
    DWORD pid;
    HWND hwnd = FindWindowA(NULL,"some window");
    GetWindowThreadProcessId(hwnd,&pid);
    HANDLE phandle;
    cout << "Found Proccess ID:" << pid << endl;
    phandle = OpenProcess(0x1F0FFF,0,pid);
    cout << "Loaded Successfully."<< endl ;
    ReadProcessMemory(phandle,(LPVOID)address,&value,4,0);
    cout << "Readed Value:" << value << endl;
    ReadProcessMemory(phandle,(LPVOID)address2,&value,4,0);
    cout << "Readed Value:" << value << endl;
    address = 0x3458CBC0;
    address2 = 0x3458CBC4;
    value = 20;
    WriteProcessMemory(phandle,(LPVOID)address,&value,4,0);
    WriteProcessMemory(phandle,(LPVOID)address2,&value,4,0);
    cin.get();
    return 0;
}

Solution :
The application hooked the apis of writing in memory in the kernel
the hook does'nt work in 64bit Windows so i can write to memory
Thanks everyone!

A: A 32-bit app running under Windows is really using a special 32-bit emulation wrapper (WOW64). You can't write to the address space of 64-bit applications from there.
Here's a page that explains it better than I can.
Edited to add:
If you're doing a 32-bit build, running on 32-bit Windows, it should work. If it doesn't, please post your code.
Edited to add:
Test the return value of WriteProcessMemory(). If it's zero (which seems likely), call GetLastError() -- that should give you a clue.


text:
Q: Commenting after a move I commented on someone else's answer on SO.
Then the post was moved to SF, where I don't have the required rep to comment other people's posts.
The answer poster @commented me, but now I'm unable to reply.
IMHO you should be always able to add comments to any post or answer where you do already have comments, regardless of reputation.

A: Go to your profile page on SF, click "accounts", unassociate your accounts and reassociate them. I suppose you didn't have 200 rep on SO when you first associated the accounts. Now that you have enough on SO, associating with that will give you a 100 rep bonus on Server Fault. Then you can comment.


text:
Q: VueJs How to Split string from a variable in API I'm new in VueJs. I want to split a string with comma (,) and save it to another variable. This string is from API.
This is my API, i'm using json server
"featured-property": [
    {
        "id": "1",
        "name": "Property 1",
        "address": "Address Property 1",
        "geo": "0.5307596, 101.4461512"
    },
    {
        "id": "2",
        "name": "Property 2",
        "address": "Address Property 2",
        "geo": "0.5055971577036701, 101.452919"
    }

I want to split "geo" and save it into variable "lat" and "lng",so i can use it to vue2-google-maps. I'm using axios to fetch the API.
export default{
    name: 'PropertyDetail',
    data(){
        return{
            property: [],
        }
    },
    methods: {
        setProperty(data){
            this.property = data
        },
    },
    mounted() {
        axios
        .get("http://localhost:3000/featured-property")
        .then((response) => this.setProperty(response.data))
        .catch((error) => console.log(error))
    }
}

How to do it in vue ways..?
Thanks..

A: If the data gives you the Array of Object from the JSON, then you can have a function like this when you loop through the array;
saveObject: function(object){
  var latLngArray = object.geo.split(', ');
  object["lat"] = latLngArray[0];
  object["lng"] = latLngArray[1];
}

and in your setProperty function, you can call it like this
setProperty(data){
   var arrayProperty = [];
   var self = this;
   data.forEach(function(item){
      arrayProperty.push(self.saveObject(item));
   })
   this.property = arrayProperty;
}

The saveObject function will manipulate the data you pass in. This is not the ideal way. it is better to just create a variable that is the same as the passed in object and just return that variable


text:
Q: Adding Same type of collection as children in different parent entity within the same DataContext category collection will be children of either Transaction Entity or Product Entity.
And Product Collection Always children of category. But when adding category collection to product, it also shows the categories added in transaction.
Here is the code.
    private void buttonUpdate_Click(object sender, RoutedEventArgs e)
    {
        using (var data = new ProductContext())
        {
            var t = new Transaction();
            data.Transaction.Add(t);
            t.Dscr = "t1";

            var c = new Category{  Name= "cat under trans 1"};
            t.Categories.Add(c);
            var p = new Product{ Name="p 1"};

            var c1 = new Category{  Name= "cat under product 1"};
            p.Categories.Add(c1);

            //******p.Categories ALSO SHOWS t.Categories **************//

            c.Products.Add(p);

            data.SaveChanges();
        }
    }

public class ProductContext : DbContext
{
    public ProductContext()
    {
        this.Database.Connection.ConnectionString = "workstation id=.;packet size=4096;user id=sa ;Password =123;data source=.; Initial Catalog=YRX;persist security info=False; MultipleActiveResultSets=True; connection timeout=5"; //ConnectionString                            // ConnectionString;
        //this.Configuration.AutoDetectChangesEnabled = true;

    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
        //base.OnModelCreating(modelBuilder);
    }
    public DbSet<Transaction> Transaction { get; set; }
}

public class Transaction
{
    public Transaction()
    {
        this.Categories = new ObservableCollection<Category>();
    }
    [Key]
    public int TransId { get; set; }
    public string Dscr { get; set; }
     [ForeignKey("TransId")]
    public virtual ObservableCollection<Category> Categories { get; private set; }

}

public class Category
{
    public Category()
    {
        this.Products = new ObservableCollection<Product>();
    }
    [Key]
    public int CategoryId { get; set; }
    public string Name { get; set; }
    [ForeignKey("CategoryId")]
    public virtual ObservableCollection<Product> Products { get; private set; }
    public int? ProductId { get; set; }
    public int? TransId { get; set; }
}
public class Product
{
    public Product()
    {
        this.Categories = new ObservableCollection<Category>();
    }
    [Key]
    public int ProductId { get; set; }
    public string Name { get; set; }
    //public virtual Category Category { get; set; }
    public int CategoryId { get; set; }
    [ForeignKey("ProductId")]
    public virtual ObservableCollection<Category> Categories { get; private set; }
}


text:
Q: aggregations on multiple fields in nested object not working in elastic search 1.7x? Mapping in amazon index looks like below.  book has nested authors that have the multi-field "alias".  "alias" and "alias.raw" should be valid fields in authors.
{
    mappings: {
        book: {
            properties: {
                title: {
                    type: "string",
                    fields: {
                        raw: {type: "string", index: "not_analyzed"}
                    }
                },
                authors: {
                    type: "nested",
                    properties: {
                        alias: {
                            type: "string",
                            fields: {
                                raw : {
                                    type: "string",
                                    index: "not_analyzed"
                                }
                            }
                        },
                        alias_raw: {
                            type: "string",
                            index: "not_analyzed"
                        }

                    }
                }
            }
        }
    }
}

Sample data:
{index: {_id: "1", _type: "book"}}
{title: "Being Awesome for Dummies", pages: "100", authors:[{firstName: "Apollo", lastName: "Cabrera", alias: "Mister Awesome", alias_raw: "Mister Awesome"}, {firstName:"Mark", lastName:"Twain", alias: "Julius Caesar", alias_raw: "Julius Caesar"}]}
{index: {_id: "2", _type: "book"}}
{title: "Understanding Women", pages: "100000", authors:[{firstName: "Megyn", lastName: "Kelly", alias:"Wonder Woman", alias_raw:"Wonder Woman"}, {firstName:"Donald", lastName:"Trump", alias:"Lone Ranger", alias_raw:"Lone Ranger"}]}
{index: {_id: "3", _type: "book"}}
{title: "Snap Chat", pages: "30", authors:[{firstName: "Hilary", lastName: "Clinton", alias:"Code Zero", alias_raw:"Code Zero"}, {firstName:"Harry", lastName:"Houdini", alias: "Abra Cadabra", alias_raw: "Abra Cadabra"}]}
My aggregation query looks like this...
{
    query: {
        match_all: {}
    },
    aggs: {
        authors: {
            nested: {
                path: "authors"
            },
            aggs: {
                aliases: {
                    terms: {
                        field: "alias.raw"
                    }
                }
            }
        }
    }
}

When I execute the aggregation query, I get no aggregation at all.  If I use "alias_raw" (which is another separate field I added), I get the full alias as expected...
"aggregations" : {
    "authors" : {
      "doc_count" : 6,
      "aliases" : {
        "doc_count_error_upper_bound" : 0,
        "sum_other_doc_count" : 0,
        "buckets" : [ {
          "key" : "Abra Cadabra",
          "doc_count" : 1
        }, {
          "key" : "Code Zero",
          "doc_count" : 1
        }, {
          "key" : "Julius Caesar",
          "doc_count" : 1
        }, {
          "key" : "Lone Ranger",
          "doc_count" : 1
        }, {
          "key" : "Mister Awesome",
          "doc_count" : 1
        }, {
          "key" : "Wonder Woman",
          "doc_count" : 1
        } ]
      }
    }
  }

Is there another way to get at "alias.raw" for aggregating a multi-field? If I use just "alias", I get the parsed, tokenized, analyzed, lower-case fields.  I want the non-analyzed raw alias. I really don't think I need nor want the redundant "alias_raw" field.
Thanks in advance :)

A: Figured it out.  You have to use a full path for the field name...
field: "authors.alias.raw"
i.e.
{
    query: {
        match_all: {}
    },
    aggs: {
        authors: {
            nested: {
                path: "authors"
            },
            aggs: {
                aliases: {
                    terms: {
                        field: "authors.alias.raw"
                    }
                }
            }
        }
    }
}

Owe right :)


text:
Q: Mergin plugin options Can I use the points created from field study via free Input App on Iphone, and Synchronize them into free QGIS, and then use these points in creating a heatmap on QGIS?

A: Mergin Maps Input App can be used on iPhone, install it via AppStore. You can use Mergin Maps QGIS Plugin to synchronise the data back to QGIS and create a heatmap.


text:
Q: Creating a plist file only on first runnable in the device's documents directory I current have everything setup to read from the documents directory and write to it , but Cannot do it because the file doesnt exist yet.
How is a file created within the code?

A: Use NSFileManger's fileExistsAtPath: to see if the file exist. If not create it before going on to the code that requires the file.

A: If you already have a template version of the document in your application's bundle then you should be able to write it to the application's document directory using something similar to the following.  I haven't tested this code so I've probably got a few things wrong but that's the general idea.
- (void) applicationDidFinishLaunching {
  NSArray* directories = NSSearchPathsForDirectoriesInDomain(NSDocumentsDirectory, NSUserDomainMask, YES);
  NSString* documentsDirectory = [directories objectAtIndex: 0];
  NSString* path = [documentsDirectory stringByAppendingPathComponent: @"Something.plist"];

  if (![[NSFileManager sharedInstance] fileExistsAtPath: path]) {
    NSString* infoTemplatePath = [[NSBundle mainBundle] pathForResource: @"Something" ofType: @"plist"];
    NSDictionary* info = [NSDictionary dictionaryWithContentsOfFile: infoTemplatePath];
    [info writeToFile: path];
  }
}

A: This one works better for me:
        NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *documentDBFolderPath = [documentsDirectory stringByAppendingPathComponent:@"*.db"];

    if (![fileManager fileExistsAtPath:documentDBFolderPath])
    {
        NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"*.db"];
        [fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error];
    }


text:
Q: Comparaison of two version of Fractional sobolev spaces: what do we have $W^{s,p}(\mathbb{R}^{n})=H^{s,p}(\mathbb{R}^{n})$? There are two version of Fractional sobolev spaces .
Definition1: (Via Galiardo semi-norm) Let $1\leq p\leq +\infty$, $0<s<1$ and $\Omega\subseteq \mathbb{R}^n$ an open set. The fractional Sobolev space $W^{s,p}(\Omega)$ is defined to be
$$ W^{s,p}(\Omega) = \left\{ u\in L^p(\Omega) : \frac{|u(x)-u(y)|}{|x-y|^{\frac{n}{p} + s}} \in L^p(\Omega\times\Omega) \right\} $$
equipped with the norm
$$ \|u\|_{W^{s,p}(\Omega)} = \left( \int_\Omega |u|^p \; dx + \int_\Omega\int_\Omega \frac{|u(x)-u(y)|^p}{|x-y|^{n+ sp}} \; dx dy \right)^{1/p}. $$
Definition2:(Via Fourier Transform)
For $s\in\mathbb{R}$, $1<p<\infty$, and $n\geq 1$, define the Sobolev space $H^{s,p}(\mathbb{R}^{n})$ by
    $$H^{s,p}(\mathbb{R}^{n}):=\left\{f\in\mathcal{S}(\mathbb{R}^{n}) : \|(\langle{\xi}\rangle^{s}\widehat{f})^{\vee}\|_{L^{p}}<\infty\right\}$$,
equipped with norm
    $$\|f\|_{H^{s,p}}=\|(\langle{\xi}\rangle^{s}\widehat{f})^{\vee}\|_{L^{p}}$$
Where, $$\langle{\xi}\rangle^{s} =(1+|\xi|^2)^s$$
From these definitions I have a couples of questions

1) What are the value of $p\in[1,\infty)$ such that $W^{s,p}(\mathbb{R}^{n})$ and $H^{s,p}(\mathbb{R}^{n})$ coincide?

I have found that this true for $p=2$ that is $$W^{s,2}(\mathbb{R}^{n})=H^{s,2}(\mathbb{R}^{n})$$

Do we still have equality or one side inclusion for some $p\neq 2$ if yes which one ? if no please provide me with some counter example or reference.

2) Next I would like to  know what are the advantage and disadvantage using one   the spaces  $W^{s,p}(\mathbb{R}^{n})$ and $H^{s,p}(\mathbb{R}^{n})$.
I know that  the definition $W^{s,p}(\Omega)$
makes sense on any domain  which not the case for $H^{s,p}(\Omega)$ due to the lack of Fourier transforms.


text:
Q: Do visual basic forms each run in separate memory? Do visual basic forms each run in separate memory and if not is there a way that I can force them to do so. I want them to be in separate memory so that if one form freezes the entire program won't.

A: You're really asking about separate threads rather than separate memory. If you have several forms within the same application, they will usually run within the same thread. While you can force each window to use a different thread, that will make your life much more complicated at other times.
I would recommend that instead of trying to work around the problem of one form freezing, you simply fix it so that it doesn't freeze. To do that, you should avoid doing significant amounts of work on the UI thread - you should use background threads or asynchronous operations to avoid blocking the UI thread.

A: Jon Skeet's gives you the idea but here's the specific class & code snippet to create responsive UI.
class: BackgroundWorker
code snippet: Using BackgroundWorker class for long running processes in WPF or Silverlight


text:
Q: Properties of unit vector scaling What properties are kept when we scale a vector to unit length, i.e.  $\frac{\mathbf{v}}{||\mathbf{v}||_1}$?
Imagine that we have an unconstrained optimization problem, and we obtain as solution $x_i = k_i$. We now add $\sum x_i = 1$ as a new constraint, i.e. $\mathbf{x}$ should be unit-length.
One possibility would be to set $x_i = k_i - \frac{\sum x_i - 1}{N}$, where $N$ is the size of $\mathbf{x}$, and this can be interpreted as splitting the extra (or deficit) of $||\mathbf{x}||_1$ equally among all the values. As far as I understand, this minimizes the squared error between $\mathbf{x}$ and $\mathbf{k}$.
However, this is not common. In many applications we scale $\mathbf{x}$ so that we keep  the relative distances intact: $\frac{\mathbf{x}}{||\mathbf{x}||_1}$. Why? What properties are kept by doing this? In terms of optimization, what are we minimizing/maximizing? Why would we prefer this solution over any other?


text:
Q: Automatic Retry on grain fail-over in Microsoft Orleans so we're testing out how Grain Fail-over works in case  some silo is unresponsive for some reason (server is down, etc...). Currently we have two silos running on two different machines with grains activated on each of them. We then proceed to kill one of the silos (unexpectedly). We try to call a grain on the DEAD silo and after some timeout (I believe it is 3 minutes or so in total) an Exception is thrown, stating that the Silo is rejecting the connection. Now, we believe that after a silo is declared DEAD a grain is only activated on another silo if we retry the activation. This is working fine for us. However, we would like to know if there is some way to do the retry automatically instead of doing the logic ourselves.

A: First, the 3 minutes sounds way too much. It should be tens of a second, if you are using the default liveness settings. What system store is it?
If you want to automatically retry, you better wrap all your client grain calls in a wrapper which will retry with exponential back off for example. Doing retries yourself gives you much more control, and what to retry and how.


text:
Q: easy_install is different for python2 and python3 or not? I had installed easy_install using sudo apt-get install python-setuptools. Will it install easy_install for python2 or python3?
I want to install virtualenv using sudo easy_install virtualenv. So, will virtualenv python interpreter will depends on easy_install python interpreter ? Or I can run virtualenv for any python interpreter ?

A: sudo apt-get install python-setuptools

installs setuptools for Python 2. For Python 3 the command is
sudo apt-get install python3-setuptools

As for virtualenv — you can install it for one Python but use with any:
virtualenv --python python3.4

even if virtualenv is for Python 2.7 or 3.6.


text:
Q: Can I hide 'Edit with Notepad++' for certain filetypes? Is it possible to hide the 'Edit with Notepad++' context-menu option when right-clicking certain file types?
To clarify, I want to keep the edit option for text-based filetypes like .txt, .ini, and .java. I'm not looking to remove or disable the shell integration. I instead want to hide the option for certain filetypes (e.g. photos, music, videos).

A: The Edit with Notepad++ option is provided by a shell extension that's registered for all file types by default. I don't think you can't hide it for specific file types without editing the shell extension itself. Instead, you can remove the registration for all file types and add it only to the file types you want.
First, export the key HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\ANotepad++ (32-bit) or HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\ANotepad++64 (64-bit) to a .reg file. For reference, here's what it looks like on a 64-bit system:
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\ANotepad++64]
@="{B298D29A-A6ED-11DE-BA8C-A68E55D89593}"

Then, delete that key. This will immediately remove the Edit with Notepad++ option on all files.
Finally, copy the .reg file, replace * with a file type you want the Edit with Notepad++ option on. This must be the file type class, not the file extension; you can find the file type class by looking at the default value on the key for the file extension (though it may be overridden by a user preference in HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts). For example, for .txt, this is txtfile by default. You can also copy the section and specify a different file type for each, then import the new .reg file to the registry, and you should see the Edit with Notepad++ option only on the file types you specified.
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\txtfile\shellex\ContextMenuHandlers\ANotepad++64]
@="{B298D29A-A6ED-11DE-BA8C-A68E55D89593}"

[HKEY_CLASSES_ROOT\inifile\shellex\ContextMenuHandlers\ANotepad++64]
@="{B298D29A-A6ED-11DE-BA8C-A68E55D89593}"

A: Download Notepad++ standalone executable as a 7zip or Zip file from this repository https://notepad-plus-plus.org/repository/. Now extract the compressed file and you are ready to run Notepad++.  e.g. Here URL for version 7.0;

*

*7zip file for 64 bit::https://notepad-plus-plus.org/repository/7.x/7.0/npp.7.bin.x64.7z

*Zip file for 64bit:: https://notepad-plus-plus.org/repository/7.x/7.0/npp.7.bin.x64.zip
Remove the shell integration, open cmd.exe and cd to your installation folder. At this point, and Notepad++ being closed, enter with command regsvr32 /u NppShell.dll. See more:: Adding Notepad++ to the context menu.
To add context menu for all file types use this registry script. Say Notepad++ executable is saved in "E:\Notepad".
[HKEY_CLASSES_ROOT\*\shell\Notepad++]
"Extended"=""
[HKEY_CLASSES_ROOT\*\shell\Notepad++\command]
@="\"E:\\Notepad\\notepad++.exe\" \"%1\""
Note that the extended value will hide the context menu and show only when you press shift key and right click. Alternatively you can create a file type and associate any extension as you want, with this command::
ftype NotepadPlus="E:\Notepad\notepad++.exe" "%1"
assoc .txt=NotepadPlus


text:
Q: How to encode md5 sum into base64 in BASH I need to encode md5 hash to base 64. The problem is that if give output of md5sum command to base64 command, it is considered as a text and not as a hexadecimal data. How to manage it? Base64 command has no option to set it's input as a hexadecimal number.
Thanks for any help.

A: You can also use xxd (comes with vim) to decode the hex, before passing it to base64:
(echo 0:; echo -n foo | md5sum) | xxd -rp -l 16 | base64

A: Use openssl dgst -md5 -binary instead of md5sum. If you want, you can use it to base64-encode as well, to only use one program for all uses.
echo -n foo | openssl dgst -md5 -binary | openssl enc -base64
(openssl md5 instead of openssl dgst -md5 works too, but I think it's better to be explicit)

A: In busybox you might not be able to use for loop syntax. Below unhex() is implemented with a while loop instead:
unhex ()
{
    b=0;
    while [ $b -lt ${#1} ];
    do
        printf "\\x${1:$b:2}";
        b=$((b += 2));
    done
}

md5sum2bytes ()
{
    while read -r md5sum file; do
        unhex $md5sum;
    done
}

md5sum inputfile | md5sum2bytes | base64

A: unhex ()
{
    for ((b=0; b<${#1}; b+=2))
    do
        printf "\\x${1:$b:2}";
    done
}

md5sum2bytes ()
{
    while read -r md5sum file; do
        unhex $md5sum;
    done
}

md5sum inputfile | md5sum2bytes | base64


text:
Q: What is the contrapositive of the definition of onto? I feel that the problem I am working on will be easier to prove by contrapositive, namely instead of showing surjective I want to show the contrapositive of surjective.

A: The term "contrapositive" refers to a certain formal transformation of implications.
Specifically, the contrapositive of
$$p\implies q$$
is
$$\lnot q \implies \lnot p.$$
It doesn't really make sense to ask for the contrapositive of a property like surjectivity.
Edit:
The statement "$f\colon A \to B$ is surjective" (when $f$ is known to be a function from $A$ to $B$) can be written
$$(\forall y\in B)(\exists x \in A)\bigl((x,y)\in f\bigr).$$
The negation of this statement is $f\colon A \to B$ is not surjective.
By the usual laws of predicate logic, this is equivalent to
$$(\exists y\in B)(\forall x \in A)\lnot\bigl((x,y)\in f\bigr).$$

A: Surjectivity of $f:A\to B$ can be expressed as:

If $b\in B$, then $\exists a\in A: f(a)=b$.

The contrapositive of this is:

If $(\forall a\in A: f(a)\neq b)$ then $b\notin B$.

I can't imagine any case where that would be any easier to prove, however.

A: A function $f:X\to{Y}$ is surjective if:
$$(\forall y)\space(\exists x)\space{f(x)}=y$$
Negating this:
$$\lnot((\forall y)\space(\exists x)\space{f(x)}=y)$$
$$(\exists y)\space\lnot((\exists x)\space{f(x)}=y)$$
$$(\exists y)\space(\forall x)\space{f(x)}\ne{y}$$
Therefore the contrapositive of the standard definition of surjective is:

If there exists a $y\in{Y}$ such that for all $x\in{X}$ $f(x)\ne{y}$, then $f:X\to{Y}$ is not surjective.

A: What you're (probably) looking for is the negation of the definition of surjective.  To find the negation, remember that "for alls become there exists" and "there exists become for alls".  So,
$$
\neg (\forall b\in B\exists a\in A: f(a)=b)\quad\text{is}\quad  (\exists b\in B:\forall a\in A, f(a)\neq b)
$$  Try to really think about what surjective means though, and what it would mean to not be that.  Drawing pictures always helps!


text:
Q: Is this a bug? @Outheader anootation is null but from exchange it is a Map I tried @OutHeaders outHeaderBound - I inspected in debug, I could see it is null. If I initialize a new hashtable/map for outHeaderBound, the headers key/value were not propagated to downstream queues.
e.g code snippet:
  public void populateCorrelationId(@Body String body, @Headers Map<String, Object> headers,
    @OutHeaders Map<String, Object> outHeaderBound, Exchange exchange) {
Map<String, Object> outHeader = exchange.getOut().getHeaders();
String msgId = (String) headers.get(msgIdKey);
String currentCorrId = (String) headers.get(correlationIdKey);

I tried outHeader = exchange.getOut().getHeaders(), I got an empty map, and headers that I put in outHeader got propagated.
I expect that @OutHeader and exchange.getOut.getHeader() both must give an empty map rather then one giving null.
Is this a bug? or intended for some functionality.
Oops I could not submit screenshot image of debug session.

A: See this FAQ - http://camel.apache.org/using-getin-or-getout-methods-on-exchange.html
And see the javadoc of the getOut() method on Exchange, then you would see that getOut will lazy create empty message if it was null. And therefore one is null and the other is an empty map, as the latter is due, getOut created an empty message.
http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/Exchange.html