text:
Q: swagger path $ref for OPTIONS requests I want to construct an API gateway deployment from a swagger.yml file.  I need to support CORS for all endpoints.  All my options path definitions are exactly the same.  How do I define the options path one place and $ref it where I want to use it?
I was hoping to do something like this (note the $ref: '#/definitions/CorsOptions' at the same level as get):
---
swagger: "2.0"
info:
  version: "2016-10-26T03:15:31Z"
  title: "corstest"
host: ""
basePath: ""
schemes:
- "https"
paths:
  /page:
    get:
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
          headers:
            Access-Control-Allow-Origin:
              type: "string"
      x-amazon-apigateway-integration:
        responses:
          default:
            statusCode: "200"
            responseParameters:
              method.response.header.Access-Control-Allow-Origin: "'*'"
        uri: "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:1234:function:myLambdaFunc/invocations"
        passthroughBehavior: "when_no_match"
        httpMethod: "GET"
        type: "aws_proxy"
    $ref: '#/definitions/CorsOptions'
definitions:
  Empty:
    type: "object"
    title: "Empty Schema"
  CorsOptions:
    options:
      consumes:
      - "application/json"
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
          headers:
            Access-Control-Allow-Origin:
              type: "string"
            Access-Control-Allow-Methods:
              type: "string"
            Access-Control-Allow-Headers:
              type: "string"
            Cache-Control:
              type: "string"
      x-amazon-apigateway-integration:
        responses:
          default:
            statusCode: "200"
            responseParameters:
              method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'"
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
        requestTemplates:
          application/json: "{\"statusCode\": 200}"
        passthroughBehavior: "when_no_match"
        type: "mock"

This yaml does not pass swagger validation.  How can I pull off what I'm trying to do so my yaml file is not huge and bloated with the same options path definition.
The swagger spec supports $ref as a path item object however I can't figure out where I can put that definition of the path item object.  I think API Gateway swagger import restricts pulling yaml files from other places but I'm not 100% sure.

A: I don't think that will work.  API Gateway currently only supports $ref for models and schemas, not for arbitrary objects.  We have a backlog item to support $ref in more places, so we might add support for this eventually.

A: If you would like to specify $ref values in arbitrary places, you can use the expand-swagger-refs module.
This will take a Swagger schema as an input, and automatically inline all your $ref values, giving you back a schema that is suitable for use with API gateway.
It is available on the command line with support for stdin and stdout:
swagger-expand < my-complex-schema.json > aws-compatible.json

And also as an importable Node module:
const { expand, expanded } = require('expand-swagger-refs');
const schema = require('./api/swagger.json');

// Create a copy of the schema, with $ref values expanded:
const expandedSchema = expanded(schema);

// Or expand the schema object in-place (mutates the object):
expand(schema)


text:
Q: Convert JSON to CSV-BASH JSON file:
"UserDetailList": [
        {
            "UserName": "citrix-xendesktop-ec2-provisioning",
            "GroupList": [],
            "CreateDate": "2017-11-07T14:20:14Z",
            "UserId": "1234556",
            "Path": "/",
            "AttachedManagedPolicies": [
                {
                    "PolicyName": "AmazonEC2FullAccess",
                    "PolicyArn": "arn:aws:iam::aws:policy/AmazonEC2FullAccess"
                },
                {
                    "PolicyName": "AmazonS3FullAccess",
                    "PolicyArn": "arn:aws:iam::aws:policy/AmazonS3FullAccess"
                }
            ],
            "Arn": "arn:aws:iam::1234567890:user/citrix-xendesktop-ec2-provisioning"
        },
        {
            "UserName": "rundeck-read-only-iam-permissions",
            "GroupList": [],
            "CreateDate": "2018-03-09T11:13:38Z",
            "UserId": "AIDAJQOQGKISLCWDXG6EQ",
            "Path": "/",
            "AttachedManagedPolicies": [
                {
                    "PolicyName": "IAMReadOnlyAccess",
                    "PolicyArn": "arn:aws:iam::aws:policy/IAMReadOnlyAccess"
                }
            ],
            "Arn": "arn:aws:iam::279052847476:user/rundeck-read-only-iam-permissions"
        }
    ],

with jq -r '.UserDetailList[] | [.UserName] | @csv' output.json > fileout2.csv
I can get
citrix-xendesktop-ec2-provisioning"
"rundeck-read-only-iam-permissions"

How to get IAM policies for these 2 users, i need to extract AmazonEC2FullAccess and AmazonS3FullAccess under AttachedManagedPolicies ?
so output can be
citrix-xendesktop-ec2-provisioning",AmazonEC2FullAccess
citrix-xendesktop-ec2-provisioning",AmazonS3FullAccess
rundeck-read-only-iam-permissions,IAMReadOnlyAccess

A: got it working: jq -r '.UserDetailList[] | .UserName as $u | .AttachedManagedPolicies[] | [$u, .PolicyName] | @csv' output.json > fileout.csv

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to use multipal components in angular2 I am new in angular2, I am trying to use two components in single page but it gives me 404 error.
this is my two .ts files
app.ts
import {Component, View, bootstrap} from 'angular2/angular2';

import {events} from './event.component';

@Component(
    {
        selector: 'contact'
    })
    @View({

        templateUrl: './Travel Operator/login.html',

        directives: [events]
})

export class Contact {
}

bootstrap(Contact);

and event.component.ts
import {Component, View, bootstrap} from "angular2/angular2";

@Component(
    {

        selector: 'events'
    })
@View({
        template: '
Hello World
'
})

export class events {

    }
}

bootstrap(events);

and i am trying to use it on my main index.html file like

First Angular App

        <contact></contact>

        <events></events>

but it gives

"NetworkError: 404 Not Found - http://localhost:55777/event.component"
  error

I am stuck over there please help

A: The problem is that the module containing your event component isn't correctly loaded. It's rather a problem with your SystemJS configuration. Perhaps you don't put the TypeScript files with an app or src folder.
From the 5 Min Quickstart (https://angular.io/guide/quickstart):
var map = {
  'app': 'app', // 'dist',
  (...)
}

var packages = {
  'app': { main: 'main.js',  defaultExtension: 'js' },
  (...)
};

In this case, both JS files for components (resulting from TypeScript transpilation) are located in the same folder (the app one) so import {events} from './event.component'; will look for an event.component.js file in the app folder.


text:
Q: Can two eigenfunctions be almost linearly dependent in a region? Consider the Schrödinger operator $H=-\Delta+|x|^a$ on $\mathbb{R}$, where $a>0$. Since the potential is growing at $\infty$, we have compact resolvent thus the eigenvalues are discrete and tend to $\infty$. We denote the eigenvalues by $\{\lambda_n\}_{n=1}^{\infty}$. Let $\{\phi_n\}$ be the correspoding $L^2$-normalized eigenfunctions. It's trivial that  eigenfunctions corresponding to different eigenvalues are orthogonal, i.e.,
$$
\int_{R}\phi_n\phi_m=0,\quad\text{whenever $m\ne n$.}
$$
But if we only consider a subregion of $\mathbb{R}$, for instance, let
$$
I_{mn}(\Omega):=\int_{\Omega}\phi_n\phi_m,\quad\text{where $\Omega\subset \mathbb{R}$,}
$$
then this quantity may not vanish. Actually, I'm asking the opposite. How large can $I(\Omega)$ be? To make it more precise, let $\Omega=(0, \infty)$ be the half line. Note that all eigenfunctions are either odd or even, thus one has $\int_0^{\infty}\phi_n^2\,dx=\frac12$ for all $n$. Thus by Cauchy inequalty one has the upper bound
\begin{align}\label{eq}
\left\lvert\int_0^{\infty}\phi_n\phi_m\right\rvert\leq \frac12.
\end{align}
Is this upper bound the sup of $I_{mn}((0, \infty))$? or can we find a sequence of eigenfunctions such that
$$I_{mn}((0, \infty))\rightarrow \frac12?$$
Moreover, is there some physical explanation to this? I think it's related to something which is opposite to orthogonality. Note that the equality holds in Cauchy inequality iff $\phi_n$ and $\phi_m$ are linearly dependent, which seems "impossible" at first sight. I'm trying to prove this when $a=\frac12$, since the spectrum of the unharmonic oscillator grows like $(\frac{3\pi}{4}n)^{\frac{2}{3}}$, in this case, the spectral gap tends to zero when $n\rightarrow \infty$, then intuitively, the eigenfunctions of two consecutive eigenvalues may be almost linearly dependent in this special subregion.


text:
Q: How to show in the same legend data points (geom_point) and lines (from stat_ecdf)? After estimating the parameters of a distribution through bootstrapping, starting from "known" data (i.e., coming from the literature, experiments, and so on) for wihch the teoretical distribution is known, I want to display on the same plot the original data (with associated cumulative probability), and the CDFs of both the "true" distribution and the estimated one.
However, I am failing to display data and curves in the same legend.
Minimal reproducible example:
  libary(ggplot2)

  n.studies <- 50
  cumulative.prob <- seq(1 / n.studies, 1 - 1 / n.studies, length.out = n.studies)
  known.values <- qnorm(cumulative.prob)
  group <- rep(c("Source 1", "Source 2", "Source 3"), length.out = n.studies)
  data <- data.frame(x = known.values, y = cumulative.prob, group = group)
  # Simulate the bootstrap procedure
  sampler <- function(x) {
    bootstrap <- sample(x = known.values, size = length(known.values), replace = T)
    return(c(mean = mean(bootstrap), sd = sd(bootstrap)))
  }
  simulated.statistics <- as.data.frame(do.call(rbind, lapply(rep(1, 10000), sampler)))
  simulated.dist <- data.frame("Simulated" = rnorm(10000, mean = mean(simulated.statistics$mean), sd = mean(simulated.statistics$sd)),
                               "LCL" = rnorm(10000, mean = quantile(simulated.statistics$mean, .025, names = F), sd = mean(simulated.statistics$sd)),
                               "UCL" = rnorm(10000, mean = quantile(simulated.statistics$mean, .975, names = F), sd = mean(simulated.statistics$sd)),
                               "Original" = rnorm(10000))
  # Plot data and CDFs
  g <- ggplot() +
    stat_ecdf(data = simulated.dist, aes(x = Simulated), colour = "darkgreen", linetype = "solid", geom = "step", lwd = 1) +
    stat_ecdf(data = simulated.dist, aes(x = LCL), colour = "lightgreen", linetype = "dashed", geom = "step", lwd = 1) +
    stat_ecdf(data = simulated.dist, aes(x = UCL), colour = "lightgreen", linetype = "dashed", geom = "step", lwd = 1) +
    stat_ecdf(data = simulated.dist, aes(x = Original), colour = "red", linetype = "dotted", geom = "step", lwd = 1) +
    geom_point(data = data, aes(x = x, y = y, colour = group, shape = group)) +
    xlab("Value") +
    ylab("CDF") +
    theme_bw() +
    theme(legend.position = "bottom",
          legend.title = element_blank())
  print(g)

What I want to obtain is exactly this graph, with a legend displaying in addition to the data points (exactly as they are) the four curves (i.e. two "dashed lightgreen" curves labeled as "LCL" and "UCL", a "solid darkgreen" curve labeled "Simulated", and a "red dotted" curve labeled "Original").
So far I tried to manually set legends for colors, shapes and linetypes, but I am either obtaining "more than one legend" or an incorrect graph (e.g., points or curves are disappearing), I suppose this is due to the fact that stat_ecdf and geom_point do not share the same aesthetics.
Thank you in advance for your precious help

A: I couldn't find an elegant solution focused on tidying the simulated.dist dataset, but the one below seems to get the job done.
Ultimately, OP wants two legends:

*

*One that shows the points and their colors, and

*One that shows the lines and their colors.

The "tidy" solution would be to make use of all aesthetics mapped to the data, but this actually makes things a bit cumbersome.  Instead, with this example I will concede on some mapping to make adjustment a bit more straightforward.  The most problematic aesthetic here is color, which would be shared across the two legends.  Therefore, the solution I present is to ensure they are not shared:  color is mapped with geom_point() already, so we'll keep the color "not-mapped" for the stat_ecdf() lines.  Unfortunately, this means we cannot combine the stat_ecdf() calls into one common line: hence the cumbersome solution.
To get a legend showing for the stat_ecdf(), we need to map something into aes().  Here I'm using linetype= since this is not an aesthetic in geom_point(), so it's an easy way to keep the legends separate.  By doing this, ggplot2 will decide to reorder our legend items alphabetically, and also will not apply color to the lines in the legend to match the panel.  Therefore, I will have to specify the order and colors of the legend keys manually using override.aes().  We also need to specify the actual linetypes.  We do all this via the scale_linetype_manual() and guides() functions.
g1 <- ggplot() +
  stat_ecdf(data = simulated.dist, aes(x = Simulated, linetype="Simulated"), colour = "darkgreen", geom = "step", lwd = 1) +
  stat_ecdf(data = simulated.dist, aes(x = LCL, linetype="LCL"), colour = "lightgreen", geom = "step", lwd = 1) +
  stat_ecdf(data = simulated.dist, aes(x = UCL, linetype="UCL"), colour = "lightgreen", geom = "step", lwd = 1) +
  stat_ecdf(data = simulated.dist, aes(x = Original, linetype="Original"), colour = "red", geom = "step", lwd = 1) +
  geom_point(data = data, aes(x = x, y = y, colour = group, shape = group)) +
  xlab("Value") +
  ylab("CDF") +
  theme_bw() +
  theme(legend.position = "bottom",
        legend.title = element_blank()) +
  scale_linetype_manual(
    limits=c("Simulated", "LCL", "UCL", "Original"),
    values=c("Simulated"="solid", "LCL" = "dashed", "UCL" = "dashed", "Original" = "dotted")
  ) +
  guides(linetype=guide_legend(
    override.aes = list(
      color=c("darkgreen", "lightgreen", "lightgreen", "red"))
  ))

g1


text:
Q: CSS: Weird lines when using a scale-transition I am experiencing some weird issues with CSS scale transitions. The scaling works fine, however there are some weird lines around the scaled element, which disappear after scrolling. This happened in a Chrome browser and in Microsoft Edge. And I don't assume it has something to do with margin, padding, the z-index, colors or anything else along those lines, because it happened with and without these properties being included in the relevant CSS.
This is the relevant CSS as a quick draft:
.element {
    background-color:black;
    transition: transform 0.5s;
    transform:scale(1, 1, 1);
}

.element:hover {
    transform:scale(1.1, 1.1);
}

Here is a quick recording to demonstrate that: https://streamable.com/cyvkjm
Here is also a screenshot for those who can't see the video for some reason:

A: Your streamable link worked fine for me. I remember having a problem similar to that a while ago, and it was something to do with using 3d scaling
Check this out though, I'm fairly certain backface-visibility: hidden and the -webkit equivalent will fix it. As I can't reproduce this I can't be of much more help
CSS transition on element leaving lines
Edit: after reproducing the problem we found a fix. Tested and works in Chrome/Edge/Firefox. perspective(1000px) seems to work better than perspective(0)
.element {
  transform: scale(1) perspective(1000px);
}
.element:hover {
  transform: scale(1.1) perspective(1000px);
}


text:
Q: Short story about a 'hole' that trades art/fiction that people make for things from alternative realities Looking for a short story about a 'hole' that trades art/fiction that people make for things from alternative realities (like trading your high-school essay for the manuscript of an award-winning novel alternative you wrote).
Not sure about the publishing date (could be anywhere from 70's-00's), since I was reading a lot of anthologies at the time (10 years ago) and I'm not that good at remembering names.

A: I believe this is "Like Minds" by Robert Reed, first published in the Oct/Nov 2003 issue of Fantasy & Science Fiction, and collected in the 2012 anthology Other Worlds Than These.
The main character does in fact trade a high school essay for an award winning novel, as seen in these quotes:

Then Josh says, "A book, a novel."
Words cause a multitude of realms to work together, the Authority suddenly engaged.  A deceptively quiet voice asks the obvious: "Who is the author of this book, this novel?"
Josh can say any name.  But he takes a deep breath and blurts, "Me."

...

"Are there other criteria?"
"Like what?" Josh had thought that he came prepared, but he feels sick with nervous energy, almost too anxious to think."
"I pick random examples," the Authority cautions.  "But you may narrow the category in significant ways.  For instance, what is the author's age?  How well did this novel sell?  And did the author win any awards or commendations?"
"Awards?" He hadn't quite thought of that. "You mean, what...like the Nobel Prize?"
"Exactly."

...

"Okay.  I wrote the novel in my thirties, and I won the Nobel Prize and the Pulitzer, too."

He also gets memoirs of a version of himself that became world leader, and a porn video of himself in a threesome with a hot classmate and his algebra teacher.
In return:

"You must give your gifts now, sir.  Since you are requesting three examples of your genotype's accomplishments, you must surrender three works from your own life and accomplishments.  Please."
This can be a trauma.  Sometimes the client examines his own gifts with a suddenly critical eye, and all confidence collapses.  How can a tiny soul measure up against Nobel winners and God-like despots?
But eighteen-year-old boys are blend of cockiness and unalloyed ignorance.  Without hesitation, Josh pulls three offerings from a long gym bag: a fat rambling term paper about the role of robots in the War of Ignorance; an eleven-page story about a misunderstood adolescent; and a comic book written by him and illustrated with help from a popular software, the superhero wearing Josh's face and his unremarkable fantasies about violence and revenge.


text:
Q: CSV File Reader Module I have two directories each has 4 sets of CSV files.
Example :
folder a :
       - animal.csv
       - food.csv
       - fruits.csv

folder b :
      - animal.csv
      - food.csv
      - fruits.csv

Now I need to merge each files like folder a animal.csv to folder b animal.csv and write it to
folder c :
   - animal.csv
   - food.csv
   - fruits.csv

This is my set of code for reading and writing a single file
   const folA= `folderA/animal.csv`;
    const folB = `folderB/animal.csv`;
    const final = `folderC`;
    const filename = "animal";
    const fastcsv = require("fast-csv");
    const csv = require("csv-parser");
    const file1 = [];
    const file2 = [];

   //Reading folder A
    fs.createReadStream(folA)
      .pipe(csv())
      .on("data", (data) => file1.push(data))
      .on("end", () => {
        //Reading folder B
        fs.createReadStream(folB)
          .pipe(csv())
          .on("data", (data) => file2.push(data))
          .on("end", () => {
            const finalData = file1.concat(file2);
            console.log(finalData);
            fastcsv
              .writeToPath(`${finalFIlePath}/${filename}.csv`, finalData)
              .on("finish", function () {
                console.log("Done");
              });
          });
      });

When I run this I get a merged animal.csv file in folder C. But I need to do the same to rest file in the folder in once run.

A: You may need to create a generic function, which takes input and output file name and merges one into another and call this function 3 times since you have 3 files to read and merge, currently you are doing it for 1 file.
const fastcsv = require("fast-csv");
const csv = require("csv-parser");

mergeFiles ('folderA/animal.csv', 'folderB/animal.csv', 'folderC/', 'animal.csv');
mergeFiles ('folderA/food.csv', 'folderB/animal.csv', 'folderC/', 'food.csv');
mergeFiles ('folderA/fruits.csv', 'folderB/animal.csv', 'folderC/', 'fruits.csv');

function mergeFiles (folA, folB, finalFIlePath, filename) {
    //Reading folder A
    const file1 = [];
    const file2 = [];
    fs.createReadStream(folA)
        .pipe(csv())
        .on("data", (data) => file1.push(data))
        .on("end", () => {
            //Reading folder B
            fs.createReadStream(folB)
                .pipe(csv())
                .on("data", (data) => file2.push(data))
                .on("end", () => {
                    const finalData = file1.concat(file2);
                    console.log(finalData);
                    fastcsv
                        .writeToPath(`${finalFIlePath}/${filename}.csv`, finalData)
                        .on("finish", function () {
                            console.log("Done");
                        });
                });
        });
}

A: You can use this snippet to merge multiple files. Notes in the comments.
const fs = require('fs');
const path = require('path');
const { parse, writeToPath } = require('fast-csv');

// The folders which we want to merge their files
const folders = [
    path.resolve('./folder_a'),
    path.resolve('./folder_b'),
];

// The destination folder
const finalFolder = path.resolve('./folder_c');

// Create the destination if it is not there
if (!fs.existsSync(finalFolder)) fs.mkdirSync(finalFolder);

// Function to return a file's contents
const parseFile = async (file, folder) => {

    return new Promise((resolve) => {

        const contents = [];

        fs.createReadStream(`${folder}/${file}`)
            .pipe(parse())
            .on('data', (data) => {
                contents.push(data);
            })
            .once('end', () => {

                resolve({
                    file,
                    header: contents[0],
                    contents: contents.slice(1),
                });
            });
    });
};

const main = async () => {

    const data = {};

    for (const folder of folders) {

        // Get all the filenames the folder contains
        const files = fs.readdirSync(folder);

        // Parse the contents of the folder's files
        const contents = await Promise.all(
            files.map((file) => parseFile(file, folder))
        );

        // Keep for each file its name, header and contents
        for (const content of contents) {

            data[content.file] = data[content.file] || { header: content.header };

            data[content.file].contents = (data[content.file].contents || []).concat(content.contents);
        }
    }

    for (const [filename, { header, contents }] of Object.entries(data)) {

        // Wait for each write operation to finish
        await new Promise((resolve) => {

            writeToPath(`${finalFolder}/${filename}`, [header, ...contents]).once('finish', resolve);
        });
    }
};

main();


text:
Q: Identify whether a field is of type group: string (character) types Is there something in information schema, or some other method, that will tell me if a field is textual or not. I.e. Without checking DATA_TYPE against each possible type, i want to identify if that field belongs to the group: string (character) types.
This is so that i can create an object of the appropriate type in my c++ code.

A: To mark the question as answered GordonLinoff said: Try COLLATION_NAME. MySQL documentation is vague, but SQL Server documents this as only being used for character and text types. (And it documents CHARACTER_MAXIMUM_LENGTH as being used for image and binary types as well.)


text:
Q: iptables Source NAT with Multiple NIC & Public IP Addresses Not Working I just have a problem on the multiple NIC & IP addresses server. I've configured my Cent OS 7 server with an additional public IP address which belongs to eth1. When iptables source NAT enabled, only the additional IP address couldn't be used.
In this post, two public IP addresses are indicated by 99.0.1.100 (eth0) and 99.0.2.100 (eth1). Subnet-mask of 99.0.2.100 is 255.255.254.0, default gateway is set properly (99.0.1.1 for 99.0.1.100, 99.0.2.1 for 99.0.2.100).

below is contents of /etc/sysconfig/network-scripts/ifcfg-eth1. (HWADDR is censored)
DEVICE=eth1
TYPE=Ethernet
HWADDR=**:**:**:**:**:**
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=static
IPADDR=99.0.2.100
NETMASK=255.255.254.0

below is output of ip route.
default via 99.0.1.1 dev eth0 proto static metric 100
99.0.1.0/23 dev eth0 proto kernel scope link src 99.0.1.100 metric 100
99.0.2.0/23 dev eth1 proto kernel scope link src 99.0.2.100

below is output of ip rule.
0:      from all lookup local
32765:  from 99.0.2.100 lookup subroute-eth1
32766:  from all lookup main
32767:  from all lookup default

below is contents of /etc/sysconfig/network-scripts/route-eth1.
default via 99.0.2.1 table subroute-eth1

below is contents of /etc/sysconfig/network-scripts/rule-eth1.
from 99.0.2.100 table subroute-eth1

then, the following request has been sent properly and responded proper IP address as string for each public IP addresses.
# curl --interface eth0 api.ipify.org  # outputs 99.0.1.100
# curl --interface eth1 api.ipify.org  # outputs 99.0.2.100

here, I want each users of the system use different public IP address. So applied the following iptables source NAT. Where uid=1000 is A, uid=1001 is B, respectively.
# iptables -t nat -m owner --uid-owner 1000 -A POSTROUTING -j SNAT --to-source 99.0.1.100
# iptables -t nat -m owner --uid-owner 1001 -A POSTROUTING -j SNAT --to-source 99.0.2.100

in this situation, eth0 works correctly, but eth1 has timed out.
# curl api.ipify.org  # outputs 99.0.1.100
# sudo -u A curl api.ipify.org  # outputs 99.0.1.100
# sudo -u B curl api.ipify.org  # **time out**

I have no idea what is wrong because of lack of network experience. If anyone has ideas, help me, please.
Note that in this situation, ssh root@99.0.2.100 from Internet is still working properly.

Edit: below is output of ip route show table subroute-eth1
default via 99.0.2.1 dev eth1

A: The uid should trigger a routing change to use eth1 instead of eth0. nat/POSTROUTING's SNAT (while still needed) comes too late for this because as the name POSTROUTING implies it happens after the routing decisions: the network interface is chosen and won't change anymore.
For local traffic the rule has to happen in the mangle/OUTPUT chain to alter the route, by using marks which can trigger an ip rule lookup:
# iptables -t mangle -A OUTPUT -m owner --uid-owner 1000 -j MARK --set-mark 1000
# iptables -t mangle -A OUTPUT -m owner --uid-owner 1001 -j MARK --set-mark 1001

The information is then reused via ip rule. Even 1000 has to be considered (to handle the specific case uid1000$ curl --interface eth1 http://api.ipify.org/ which should not use entry 32765):
ip rule add fwmark 1000 lookup main
ip rule add fwmark 1001 lookup subroute-eth1

Note that the initial default IP was chosen before: SNAT is still needed to fix it to the new correct one. Why using this mark since there's already a rule with from 99.0.2.100 lookup subroute-eth1 then? Again that's because of the order of various evaluations in the network stack, as summarized by this Packet flow in Netfilter and General Networking schematic: only a change in mangle/OUTPUT can trigger the reroute check seen in the schematic, and by this time the IP hasn't been corrected to 99.0.2.100.
In the reverse path, some network elements will not know about those routing tables in time anyway, loose mode has to be set on eth1's rp_filter or return packets will be dropped:
# echo 2 > /proc/sys/net/ipv4/conf/eth1/rp_filter

Same for eth0 to handle the specific case for uid 1000 above (uid1000$ curl --interface eth1 http://api.ipify.org/):
# echo 2 > /proc/sys/net/ipv4/conf/eth0/rp_filter

With this it should mostly work. But actually a few packets aren't owned by uid 1001: TCP RST, last ACK once the process has ended, or for UDP, related ICMP errors... are owned only by the kernel. They won't match uid 1001, will be sent on the wrong interface (with the wrong IP on this wrong interface) and this will create some timeouts at the end of the connections, more probably at the remote side rather than locally. This can be seen by doing a kill -KILL on a client with an altered connection made with user 1001 via eth1, and witnessing several retry ACK packets with source 99.0.2.100 sent via eth0 (instead of eth1) acknowledging the FIN from remote received several times on eth1.
So all this has to be reworked using CONNMARK to track flows initiated by the user, instead of packets initiated by the user (some explanations here). nat doesn't have to change, since only the 1st packet in NEW state goes through iptables rules anyway and it's tracking flows already. Let's start over:
# iptables -t mangle -F
# iptables -t mangle -A PREROUTING -j CONNMARK --restore-mark
# iptables -t mangle -A OUTPUT -j CONNMARK --restore-mark
# iptables -t mangle -A OUTPUT -m owner --uid-owner 1000 -j MARK --set-mark 1000
# iptables -t mangle -A OUTPUT -m owner --uid-owner 1001 -j MARK --set-mark 1001
# iptables -t mangle -A OUTPUT -j CONNMARK --save-mark

Everything should behave correctly now.
Final note: while it wasn't needed in your setting, the link local route for eth1 should be duplicated on the table subroute-eth1, else accessing eth1's LAN from uid 1001 will give strange results, because rule 32765 is read before rule 32766 so there won't ever be the link local route defined, as the result of this command shows:
# ip route get 99.0.2.55 mark 1001
99.0.2.55 via 99.0.2.1 dev eth1 table subroute-eth1 src 99.0.2.100 mark 0x3e9 uid 0 \    cache

It might prevent access to all of the LAN except the gateway.
You should add (or put as appropriate in the system configuration files):
ip route add table subroute-eth1 99.0.2.0/23 dev eth1 scope link src 99.0.2.100

And then the previous ip route get command will give instead the correct:
99.0.2.55 dev eth1 table subroute-eth1 src 99.0.2.100 mark 0x3e9 uid 0 \    cache


text:
Q: Application Insights - Unit testing, Azure I have a MVC project which uses the application insight and it is working fine and it is capturing all the telemetric details in azure under the proper dashboard.
I am trying to test this functionality through the unit test project, from the unit test project i am calling the class file which is present in the MVC project.,
It is working and executing the the Funciton1() but these values are not diaplaying under the dashboard...
Any suggestions..
Application 1 -> Testproject C# Class project
[TestMethod]

 Method1()
{
    MVCAppinsightCls a = new MVCAppinsightCls();
    a.Function1();
}

MVC WebApplication
Class MVCAppinsightCls
{

  Funciton1()
 {

    TelemetryClient o = new TelemetryClient();
    o.trackEvent("someName");
  }
}

A: When you run the method like this from your Test project, then your Test project is your host so what you need is to add all the configurations related to your App Insights in your Test Peoject too (Instumentation Key settings and all other stuff) so that it sends the logs to App Insights.
You need the ApplicationInsights.config file and also you need to add the nuget packages related to App Insights to your Unit Test project.


text:
Q: Conditions for monotonic convergence in the CLT? (Revised to assume $\text{support}(X_i)=\mathbb{N}$ in response to counterexamples noted in comments.)
Let $S_n=X_1+...+X_n$, where the $X_i$ are i.i.d. with $\text{support}(X_i)=\mathbb{N}$ and $0<VX_i<\infty.$ Then we know by the CLT that $$\lim_{n\to\infty}P({S_n<ES_n})={1\over 2}.$$
Q1: What are necessary and/or sufficient conditions for the convergence of $P({S_n<ES_n})$ to be monotonic?
For the $X_i$-distributions that I've examined numerically (e.g., Negative Binomial and Poisson), computations suggest that $EX_i\in\mathbb{N}$ is neccesary & sufficient -- but I've been unable to prove it.
For example, if $X_i\sim\text{Geometric($p$)}$, then $EX_i\in\mathbb{N}$ iff $1/p\in\mathbb{N}$, and indeed the convergence appears monotonic iff $p$ is the reciprocal of a positive integer.
Similarly, if $X_i\sim\text{Poisson($\lambda$)}$, then $EX_i\in\mathbb{N}$ iff $\lambda\in\mathbb{N},$ and indeed the convergence appears monotonic iff $\lambda$ is a positive integer.
Here are some typical plots of $P({S_n<ES_n})$ v. $n$:
$X_i\sim\text{Geometric($p=1/3$)},\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad \text{Geometric($p=1/3.1$)}$

$X_i\sim\text{Poisson($\lambda=1$)},\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad \text{Poisson($\lambda=1.1$)}$

Here's my attempt to prove (strict) monotonicity when $X_i\sim\text{Geometric($p=1/3$)}$; i.e., $S_n\sim\text{NegativeBinomial($n,p=1/3$)},$ for which $ES_n=nq/p=2n$, with $q=1-p.$ The pmf of $S_n$ is the following:
$$P(S_n=k) = \binom{k+n-1}{n-1} p^nq^k\quad(k=0,1,2,...),$$
and we want to show that for all $n$,
$$\begin{align}P(S_{n+1}<ES_{n+1}) &< P(S_{n}<ES_{n}) \\[2ex]
\sum_{k=0}^{2(n+1)-1}\binom{k+n}{k}p^{n+1}q^k &< \sum_{k=0}^{2n-1}\binom{k+n-1}{k}p^{n}q^k\\[2ex]
\sum_{k=0}^{2n+1}\binom{k+n}{k}q^k &< \sum_{k=0}^{2n-1}\binom{k+n}{k}{3n\over k+n}q^k\\[2ex]
\sum_{k=2n}^{2n+1}\binom{k+n}{k}q^k &< \sum_{k=0}^{2n-1}\binom{k+n}{k}\left({3n\over k+n}-1\right)q^k\\[2ex]
\binom{3n}{2n}q^{2n}+ \binom{3n+1}{2n+1}q^{2n+1}&< \sum_{k=0}^{2n-1}\binom{k+n}{k}\left({3n\over k+n}-1\right)q^k\\[2ex]
{12n+5\over 12n+3}\binom{3n}{2n}\left({2\over 3}\right)^{2n}&< \sum_{k=0}^{2n}\binom{k+n}{k}\left({2n-k\over k+n}\right)\left({2\over 3}\right)^k\tag{*}\\[2ex]
...\ & ?\ ...
\end{align}$$
Q2: Any suggestions on how to proceed, or alternative approaches? (I tried using the cdf in the form of a regularized beta function, but it led to similar difficulty.) Anyone know of binomial identities/inequalities that will further simplify (*)?


text:
Q: How to access and create if statement variables C# I'm trying to keep to the DRY principle in C#, and I was wondering if it's possible to access the argument checks in an if block. For example, would the below be possible?
if (foo == true || bar == false)
{
  if (check0)
  {
    //foo is true
  }
  if (!check1)
  {
    //bar is false
  }
}

I was also wondering if it's possible to do this, to keep the scope clean?:
if (var foo = runTimeAccessedVariable == "bar")
{
  //we now have the runtime generated variable.
}
//but it doesn't exist here

A: Nope, it's not possible. In fact, since you use the short-circuiting ||  operator, the second check might not even be evaluated.
Obviously, you can work around it as follows:
var fooIsTrue = (foo == true);
var barIsFalse = (bar == false);

if (fooIsTrue || barIsFalse)
{
    ...
}

Note that this changes the behaviour of your code, since barIsFalse is always evaluated.

A: The scope and reuse can both be trivially solved by using a pair of brackets to define a new scope;
pulic void MyFunc()
{

    // do stuff here in the scope of MyFunc

    {
        // create child scope with new scoping rules and declare control variables
        var fooTrue = foo == true;
        var barFalse = bar== false;
        if (fooTrue || barFalse)
        {
            if (fooTrue)
            {
                //foo is true
            }
            if (barFalse)
            {
                //bar is false
            }
        }
    }

   // stuff here cannot access fooTrue, barFalse.
}

This stops the variables from 'leaking out' of this part of the function. There is a small semantic difference because the var barFalse line isn't shortcut, but it seems from your example that you'll probably need to test it anyway so it shouldn't be a concern.

A: Answering you second question, no it is not possible to declare a variable in this way. The only similar alternative is to use { } to create your own local scope and declare the local variable before the if statement:
{
    bool foo;

    if (foo = runTimeAccessedVariable == "bar")
    {

    }
}

In any case I'm not really sure what the benefits of this approach are. If you are insde the if statement, you already know foo is true, what is the use of having the scoped local?
Concerning your first question, I'd just push back on the whole approach. You are basically using an if statement based on a boolean expression made up of two or more conditions. Then, once inside the if statement you are discerning between what boolean condition is met or not. Also, you could have the case of an uninitialized variable, because check1 is not guaranteed to run.
I'd rewrite that completely and by-pass the need of any locally scoped variables:

*

*Work is independent for each condition:
if (foo)
{
    //whatever
}
else if (bar)
{
    //whatever
}

*There is common work for both conditions:
if (foo)
{
    //whatever

    if (bar)
    {
        //whatever
    }
}

Both would be semantically equivalent to what you are proposing.

A: You can actually. You can use (extension) methods like this:
// For first case.
public static void If(this Lazy<bool>[] checks, Predicate<Lazy<bool>[]> ifCondition, Action<Lazy<bool>[]> ifAction) {
    if (ifCondition(checks)) ifAction(checks);
}

// For second case.
public static void If(this object[] variables, Predicate<object[]> ifCondition, Action<object[]> ifAction) {
    if (ifCondition(variables)) ifAction(variables);
}

And use of it would look like this:
// First case.
new[] { new Lazy<bool>(() => foo == true), new Lazy<bool>(() => bar == false) }.
    If(checks => checks[0].Value || checks[1].Value, checks => {
    if (checks[0].Value) {
        //foo is true
    }
    if (!checks[1].Value) {
        //bar is false
    }
});

// Second case.
new[] { "bar" }.If(variables => (string)variables[0] == "bar", variables => {
    //we now have the runtime generated variable.
});

This will limit the scope of those temporary values. However, this does not provide any check for whether you actually using checks or variables in the right way. And it would be harder to debug if something goes wrong then simple if statement.
This could also be extended to accept Func instead of Action that your If method could return result as well. And it is possible to even add ElseIf and Else methods to chain with If method (to mimic all if statement behavior).


text:
Q: PhoneGap под Android, iPhone Посоветуйте статьи по этому вопросу пожалуйста, желательно на русском, можно и на английском. Киньте туториалов, на офф сайты фонГэп не шлите пожалуйста.
A: *

*Introduction to PhoneGap

*PhoneGap Beginner's Guide


text:
Q: Как при помощи gulp-livereload сделать обновление страницы в браузере? Как при помощи gulp-плагина gulp-livereload сделать реактивное обновления страницы в браузере в подобие тому, как работает live-reload в Sublime Text. Интересует решение этой задачи именно с пакетом gulp-livereload: чтобы можно было октрыть файл html в браузере и при изменении в редакторе кода он изменялся без обновления страницы, автоматически

A: Придется еще и сервер настроить. Вот, вроде, на русском статья неплохая
http://habrahabr.ru/post/269673/
Но, я бы на вашем месте присмотрелся бы  к этому способу решения перезагрузки
https://github.com/browsersync/browser-sync


text:
Q: How to make a portable Kubuntu on external drive (GPT) on UEFI computer? The problem: after installation Kubuntu on external SSD (Transcend ESD400 512Gb) on UEFI computer I can't use it on another one. I made some attempts but all of them were unsuccessful.
My computer: UEFI, Core i7 - 4 cores, Windows 7 Ultimate 64bit, 2 internal drives with GPT, external SSD with GPT.
Kubuntu distro: LiveUSB, created with Universal USB Installer 1.9.5.4, Kubuntu 14.04 LTS
External SSD was partitioned with GParted, partitions are alligned.
After each installation SSD was formatted and repartitioned. GRUB was checked: version 2.02, EFI (not grub-pc).

Attempt 1: with plugged internal drives.
I booted from LiveUSB. Perform usual installation. My partition table:
512Mb - EFI - fat32
30Gb - / - ext4
100Gb - /home - ext4
50Gb - /usr - ext4
50Gb - /opt - ext4

Bootloader was installed on External SSD (/dev/sdc).
After rebooting I found 2 boot entries ubuntu in UEFI. If my external SSD is plugged and I choose every of this 2 entries - everything works well: Kubuntu starts and works. If the external SSD is off - a black screen Minimal BASH-like line editing is supported appeared. If I choose UEFI TS512... (boot entry with label of the external SSD), it seems that the next entry works (Windows Boot Manager).
Attempt 2: with unpluged internal drives.
Installation procedure was the same. After rebooting system started and worked. But after plugging the internal drives, on booting from external (both ubuntu and UEFI TS512... entries) a black screen with blinking text cursor appears and nothing wants to start. If I choose Windows Boot Manager Windows starts well.
Attempt 3: tried to modify efi files.
Copied grubx64.efi from /dev/sda1 to dev/sdc1 and renamed to bootx64.efi. Nothing new - it goes down the list of entries until Windows Boot Manager.
Attempt 4: tried to modify grub.cfg and fstab.
In /boot/grub/grub.cfg replaces all hd2 with hd0. And in fstab I changed the UUID of EFI partition: before it pointed to /dev/sda1, now it points to /dev/sdc1.

So how can I make a portable system on external SSD, that will boot on every UEFI computer, but not only on mine?

A: Your problem is that the EFI boot process stores data on the boot loader's location in NVRAM, so when you install on one computer and then move the disk to another computer, the second computer doesn't know where to look to find the boot loader. The usual way around this problem is to use the default/fallback boot loader filename, EFI/BOOT/bootx64.efi, on the EFI System Partition (ESP; that's your FAT32 partition). The firmware looks for this filename on removable disks. The big caveat is that you may need to use the firmware's built-in boot manager to select that disk, and the details of how to access that boot manager vary from one computer to another.
You can copy the boot loader to that location manually. The way that's most likely to work, from a working Ubuntu installation, is:
cd /boot/efi/EFI
sudo mkdir -p BOOT
sudo cp ubuntu/shimx64.efi BOOT/bootx64.efi
sudo cp ubuntu/grubx64.efi BOOT/grubx64.efi

Note that these commands will overwrite any existing EFI/BOOT/bootx64.efi boot loader. You probably don't have one on your external disk right now, but you might want to double-check this. Also, this assumes that the ESP on the external disk is mounted at /boot/efi. You should definitely double-check that with df before you proceed. You don't want to overwrite the boot loader on your internal disk by accident!
If you're sure that you'll be booting with Secure Boot disabled, you could copy EFI/ubuntu/grubx64.efi to EFI/BOOT/bootx64.efi, but that won't work if the target computer has Secure Boot enabled.


text:
Q: Avoid inherited css I have a div in which I am dynamically loading html that contains different elements with their css, this div is in partial view and its css is overriding div's element css.
like in partial view we have set css table{border:none;} but in div elements we want to show table css as it is defined in table element.
how can I achieve this?
Regards,

A: One solution is to use a child selector.

table td {
  border: 1px solid black;
}

.partial > table td {
  border: none;
}

      1
      2

        1
        2

https://developer.mozilla.org/en-US/docs/Web/CSS/Child_selectors

A: Change the way you write css in partial view.
Instead of just writing table {border: none;} and override every table, you should do something like:
.partial-view-div table {
   border: solid 1px blue
}

Then it wouldn't override your table in other places.
Also Read up on CSS Specificity score.


text:
Q: How to handle different microphone gains in different android phones? I am developing an android application in which I have to record an audio from an android phone and find the power of a specific frequency using Goertzel algorithm. Using that power value, I am making some decisions regarding some secret messages sent through the audio.
In order for this application to be used in a variety of android phones, I need to make sure that the microphone gains of all the phones are the same. But unfortunately, different phones have different gains.

(Sony phones have very small gains and Samsung, HTC phones have very large gains). Is there a way to set a common gain to the microphones through android?

One other option is, I can record the audio to the full length and normalize it. However, I cannot do this because, I am doing this processing in real time, i.e. I have to do the processing for each and every frame received from the audiorecorder object and calculate the power value, the app cannot wait until the end of the audio to decide the message.
So, if possible, please suggest me some methods I can try to overcome this.


text:
Q: python plotting arrays in nested loops Plot of linear function:

import pylab as pylab
import numpy as np

xx = []
yy = []
zz = []

for x in np.arange(0, 12, 2):
    for y in np.arange(0, 11, 1):

        z=x+y
        xx.append(x)
        yy.append(y)
        zz.append(z)

pylab.plot(yy, zz, color="blue")
pylab.xlabel('x or y')
pylab.ylabel('z')
pylab.show()

The above code is intended  to plot a series of parallel lines.  However, it also connects the lines in a zigzag pattern which is not desired.  How can i fix this problem.  I need the double loop (nested loop) but I don't want to plot the the connection between the parallel lines.

A: The problem is the way you are generating and plotting the data. By changing to pylab.scatter you can see that the shape of your data is correct but the way you are generating it is overcomplicated.

Below is a simplified example which produces the graph:
import pylab as pylab
import numpy as np

x = np.arange(0, 11, 1)
y = np.arange(0, 11, 1)

for i in range (6):
    pylab.plot(x, y, color='blue')
    y = np.add(y,2)

pylab.xlabel('x or y')
pylab.ylabel('z')
pylab.show()

This produces the following graph:


text:
Q: Java Dice Roller Project (JButton) I have a project that accepts the number of die and the number of faces on each die from the user. It will roll the number of die the user wanted, display the face each die landed on, and show the total of all the die together. This is exactly what my program is supposed to do.
However, all of this is supposed to happen within a JFrame and a JPanel. As you can see, I have GUI code, but it is currently commented out due to the fact that it does not work. Everything initially displays correctly, with the labels, button, and text boxes... But I do not know how to make the "Roll" button work.
As of right now, nothing happens when I click the "Roll" button. I don't know how to make it work. I need the GUI part of my program to display the face each die landed on and the total of all the die when the "Roll" button is clicked.
I would like to delete the DiceRollerTest() code when my program functions correctly, and only use showGUI().
Could someone please lead me in the right direction?
Here is my main, DiceRollerTest(), ShowUI(), and ShowGUI() code...
public static void main(String[] args)
{
    //showGUI();
    showUI();
}

public void DiceRollerTest()
{
    try
    {
        d = new DiceBag(6,6);
    }

    catch (FaceRangeException e){System.out.println(e.getMessage()); return;}
    catch (DiceRangeException e){System.out.println(e.getMessage()); return;}

    System.out.println(d.getClass());
    int total = d.roll();

    System.out.println(Integer.toString(total)+" "+d.toString());
}

static void showUI()
{
    Scanner keyboardInput = new Scanner(System.in);

    String input;
    int numberOfDice;
    int numberOfFaces;

    System.out.println("Enter number of dice to roll:");
    input = keyboardInput.nextLine();
    numberOfDice = Integer.parseInt(input);

    System.out.println("Enter number of faces:");
    input = keyboardInput.nextLine();
    numberOfFaces = Integer.parseInt(input);

        try
        {
            d = new DiceBag(numberOfDice, numberOfFaces);
        }
    catch (FaceRangeException e){System.out.println(e.getMessage());}
    catch (DiceRangeException e){System.out.println(e.getMessage());}

    d.roll();

    System.out.println("Rolls: "+d.toString());
    System.out.println("Total: "+d.getTotal());

    keyboardInput.close();

static void showGUI()
{
    JFrame frame = new JFrame("Dice Roller");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DiceRollerPanel panel = new DiceRollerPanel();
    frame.getContentPane().add(panel);

    frame.pack();
    frame.setVisible(true);
}

And here is my DiceRollerPanel() and RollButtonListener code...
public DiceRollerPanel()
{
    numberOfDiceLabel = new JLabel("Enter Number of Dice:");
    dice = new JTextField(5);

    numberOfFacesLabel = new JLabel("Enter Number of Faces:");
    faces = new JTextField(5);

    rollButton = new JButton("Roll");
    rollButton.addActionListener(new RollButtonListener());

    displayRolls = new JLabel("Rolls:");
    total = new JLabel("Total:");

    add(numberOfDiceLabel);
    add(dice);
    add(numberOfFacesLabel);
    add(faces);
    add(rollButton);
    add(displayRolls);
    add(total);

    setPreferredSize(new Dimension(225,100));
    setBackground(Color.gray);
}

private class RollButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent event)
    {
        displayRolls.setText("Rolls:");
        total.setText ("Total:");
        DiceBag.roll();

    }
}


text:
Q: What controller to use for 'dashboard' style UI which touches multiple domains I'm vague about I should be using in a sort of a simulation app where the user is presented with a web page that presents data from multiple domains and provides a variety of interactions that touch multiple domains.
In this case it is a real estate simulation where the UI presentation shows the user data about houses, offer to buy and sell, status of the users negotiations, etc, information about "state of the world" and that kind of thing.  A fair amount of ajax going on in the page as well.
Can I just have a controller which is not associated with a particular domain and then just provide all the different objects?  Maybe use a command object to deal with actions coming back from the user?
Hopefully this quesiton is not too vague for a coherent answer, I'm just looking for suggestions on the high level approach.

A: Yes, you can have a controller which does not directly correlate to a specific domain. For instance you could create a DashboardController. The use of command objects is up to you and your needs, but you can use Domain instance in the above controller just like any other controller.

A: As @Joshua Moore stated, it's no problem, let me give a small - shortened - example. (hope it gives you a bit of an idea...)
I use in the application a bootstrap-theme and the information on the dashboard (several statistic widgets) is generated through ajax-calls into the dashboard-controller.
First, the UrlMappings.groovy file:
class UrlMappings {
static mappings = {
    "/$controller/$action?/$id?(.$format)?"{
        constraints {
            // apply constraints here
        }
    }

    "/"(controller: "dashboard", action:"index")
    "500"(view:'/error')
}

}
Then the controller-code:
package example

import java.util.Random
import grails.converters.JSON
import groovy.time.TimeCategory

class DashboardController {

    def index() {}

    def contractAmountAsJson() { ...someCode; return Data as JSON... }

}

Then the index.gsp page:
<!DOCTYPE html>

<meta name="layout" content="main">
<g:set var="entityName" value="${message(code: 'syParameter.label', default: 'SyParameter')}" />
<title><g:message code="default.list.label" args="[entityName]" /></title>

Vertragsvolumen aktiver Kunden-Verträge pro Monat

And the javascript as an example:
if ($('#customerContractAmount').length) {
    $.ajax({
        url: '${request.contextPath}/dashboard/contractAmountAsJson?type=customer',
        dataType: 'json',
        success: function(chartData) {
            Morris.${session?.user?.statisticStyle ? session.user.statisticStyle : "Area"}({
                element : 'customerContractAmount',
                data : chartData,
                xkey : 'period',
                ykeys : ['a', 'b', 'c'],
                labels : ['bestätigt', 'erstellt', 'in Arbeit']
            });
        }
    });
}


text:
Q: Rewrite Wordpress-Post-Url to a new domain Is it possible to rewrite / replace a wordpress-post-url "http://myfirstdomain/special-post" like this: "http://anotherdomain/" ?
(Whitout installing WP-Multisite)

A: Try this code:
RewriteEngine On
RewriteCond %{HTTP_HOST} !oldexample.com$ [NC]
RewriteRule ^(.*)$ http://www.newexample.com/$1 [L,R=301]


text:
Q: How can I make a .delay function in a h3 with JQuery in Selenium? I tried to made a click in an 'h3' that contains two 'divs' so I tried to make a loop to go through them but it only opens the second 'div'.
Just it opens both 'divs' when I put an alert which stop the application between both of them. It works but I want to make this without have to block the application with the alert because I'm using it with Selenium in a Java project of Eclipse.
I tried to make this with a .delay() function but it didn't works. I put here the code that I use for it:
$("#proveDiv > div > h3").each(function(i, obj){
      $(obj).delay(60000).fadeIn().click();
})

It only opens the second 'div', but I want to the test go through both 'divs' and not only on one of them.
I want to know if there is some function like delay or sleep that do this task but without blocking the application.
Any help would be appreciated.
Thank you very much!
EDIT: I also tried with the function setTimeout but it didn't work also. Please let me know if I'm doing something wrong.
$("#proveDiv > div > h3").each( function(i)
{
    setTimeout(function()
    {
       $(this).click()} , 10000)
    }
)

A: Assuming you are executing this Javascript through Selenium and wants to test it.
How about selecting and clicking them one by one
JavascriptExecutor driver = (JavascriptExecutor) webdriver;
driver.executeScript("$(`proveDiv > div > h3`).eq(0).click();");
TimeUnit.SECONDS.sleep(100); // or Thread.sleep(100);
driver.executeScript("$(`proveDiv > div > h3`).eq(1).click();");


text:
Q: Overwrite laravel package config in own package I have multiple laravel 8 projects with some common logic. For these logics, I am currently creating a package, so that I can use it in all projects and don't have to make changes multiple times.
In all these projects, I am using spatie/laravel-feed package, which has a config file feed.php to customize the paths/routes. Is there a way to create a centralized config file feed.php inside the package? So the hierarchy of config merging should be:

*

*vendor/spatie/laravel-feed/config/feed.php

*vendor/my-package/-my-package/config/feed.php

*config/feed.php

Using the following in the my-package ServiceProvider::register method doesn't work:
$this->mergeConfigFrom(
    __DIR__.'/../../config/feed.php', 'feed',
);


text:
Q: Passing textarea input from html to flask
*

*I am trying to pass textarea input from my html form to flask, but some how i am not able to achieve it. Below is the code.

html file
<form action="{{ url_for('next') }}" method="post">
<textarea rows="10" name="test"></textarea>
<button>submit</button>
</form>

so i wish to take multiline input from user and store it in the same way for example:
user input in textarea:-

abc
def
ghi
jkl

the desired output or store it in same way as multiline string and newline.
output:-
abc
def
ghi
jkl

python code -
def next():
  if request.method == 'POST':
     name= request.form['test']
     #this doesn't work

Error -  raise exceptions.BadRequestKeyError(key)

I am very much new to flask and trying to explore.Thanks for the help.

A: Your form is
<form action="{{ url_for('next') }}" method="post">
<textarea rows="10" name="test"></textarea>
<button>submit</button>
</form>

that is textarea is named test, but here
def next():
  if request.method == 'POST':
     name= request.form['name']

you are asking about something naming name which is not present and therefore BadRequestKeyError happen, you should do
def next():
  if request.method == 'POST':
     name= request.form["test"]


text:
Q: Java FX - How to terminate a ScheduledService I wrote a little code to download some files from internet..if user click on cancel button this must be stopped..i use the cancel() method for do it..but it didn't work.
ScheduledService<Object> service = new ScheduledService<Object>() {
            protected Task<Object> createTask() {
                return new Task<Object>() {
                    protected Object call() {
                        if (checkinternet()) {
                            downloadFiles();
                        }
                        return null;
                    }

                };
            }
        };
        service.start();

In buttons action event handler i called cancel method for stop service..
but it wasn't successful..
service.cancel();

How do i do that...

A: There is no automatic way to cancel a task or service.
From the documentation (https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm):

Cancelling the Task.
There is no reliable way in Java to stop a thread in process. However, the task must stop processing whenever cancel is called on the task. The task is supposed to check periodically during its work whether it was cancelled by using the isCancelled method within the body of the call method.

The example referenced in the above block looks like this:
Task<Integer> task = new Task<Integer>() {
    @Override protected Integer call() throws Exception {
        int iterations;
        for (iterations = 0; iterations < 100000; iterations++) {
            if (isCancelled()) {
               break;
            }
            System.out.println("Iteration " + iterations);
        }
        return iterations;
    }
};

So you will have to implement the cancel logic by yourself, unfortunately.


text:
Q: Export a java library in a .jar file I'm still pretty new to java and I'm VERY new to exporting .jar files. I've got a little game that I want to send to some friends and I was told in another question that I should export it to an executable jar file. Well I finally got that working on my computer but when I send it to other people it doesn't work because they don't have the library.
I'm importing the objectdraw library and without that my program won't run at all!
So basically I need to find a way to export the object draw library as part of my .jar file so that they can use it too. Do I simply include it in the included files part of the jar command?
ex: jar cmf MANIFEST.mf Archery.jar * /System/Library/Java/Extensions/objectdraw.jar
or what? I'm working out of the command line right now.

A: The simplest way is to send the JAR library file too and add a Class-Path entry to the manifest. This entry would look like:
Class-Path: objectdraw.jar

You could also set the CLASSPATH environment variable manually.
Alternatively, you can unpack the library and add all (or just the required files) to your final jar. This doesn't always work though, because some libraries rely on the integrity of teir JAR file.
Finally, it is possible to include the dependency in the main JAR, but it would require a custom class loader.

A: Turns out the best way I've found to do this is to unpack the library and then put all the resulting files in with your final archive. This way it actually works on other computers.
jar xf library_wanted.jar; jar cvmf MANIFEST.mf end_result.jar *.class library_wanted/


text:
Q: Running ASP.net V5 in VSCode I am trying to run code sample from https://github.com/aspnet/home in the VSCode in Windows 7 OS. I successfully launched the website but it errors out
An unhandled exception occurred while processing the request.

MissingMethodException: Method not found:'Microsoft.Framework.Runtime.Compilation.ILibraryExport Microsoft.Framework.Runtime.ILibraryManager.GetLibraryExport(System.String)'.

Microsoft.AspNet.Mvc.Razor.Compilation.RoslynCompilationService.GetApplicationReferences()
I tried upgrading the DNVM and tried listing the version available and did "dnu restore"
Active Version     Runtime Architecture Location                           Alia
                                                                       s
------ -------     ------- ------------ --------                           ----
 *    1.0.0-beta4 clr     x86          C:\Users\***\.dnx\runtimes d...

Please help fixing this.

A: I had the same problem, but I solved it by getting the latest dev build. So I'm guessing it's a bug in the current nuget package build. From the github page:

DNVM has the concept of a stable and unstable feed. Stable defaults to NuGet.org while unstable defaults to our dev MyGet feed. So if you add -u or -unstable to any of the install or upgrade commands you will get our latest CI build of the DNX instead of the one last released on NuGet

Try running the below command and then launching the site again.
dnvm upgrade -u


text:
Q: Is there an automatic gem5 configuration generator based on my Server? Is there a tool or script that would read my server properties (Number of CPUS, Cores, Memory layout and Structure) and automatically generate a full system mode (FSE) configuration script based on that ?
I know this might little ambitious, but maybe something like that exists somewhere ....


text:
Q: MongoDb GridFS with the existing specific collection in a database Consider the below "restaurants" collection documents in the "restaurant" mongodb database.
{
"_id" : ObjectId("55f6564073fc0a09338cf434"),
"address" : {
    "building" : "97-22",
    "coord" : [
        -73.8601152,
        40.7311739
    ],
    "street" : "63 Road",
    "zipcode" : "11374"
},
"borough" : "Queens",
"cuisine" : "Jewish/Kosher",
"grades" : [
    {
        "date" : ISODate("2014-11-23T17:30:00.000-06:30"),
        "grade" : "Z",
        "score" : 20
    },
    {
        "date" : ISODate("2013-01-16T17:30:00.000-06:30"),
        "grade" : "A",
        "score" : 13
    },
    {
        "date" : ISODate("2012-08-01T17:30:00.000-06:30"),
        "grade" : "A",
        "score" : 13
    },
    {
        "date" : ISODate("2011-12-14T17:30:00.000-06:30"),
        "grade" : "B",
        "score" : 25
    },

   ........
   .......
   .......
     {
        "date" : ISODate("2011-12-14T17:30:00.000-06:30"),
        "grade" : "AZZ",
        "score" : 25
    },   -- It reaches 15 MB
],
"name" : "Tov Kosher Kitchen",
"restaurant_id" : "40356068"

}
In this document "grades" filed is the embedded document array. This array is going to reach mongodb maximum document size 16Mb. So now we are in the situation to alter the data model for this collection. I came to know that in the mongoDb we can store the documents which exceed the default limit of 16mb by using "gridfs" . I'm not able to find the links to demonstrate this. I need to store gridfs documents along with existing fields in the collection.

A:
Just because you can embed documents, it doesn't mean that it's always a good idea. More often than not, it isn't.
Markus W Mahlberg

It basically only works in a "One-to-(Very-)Few" relationship. In your case, it's different.
Ask the right question. What do you really want to know? My guess is

What are the grades for a given restaurant?

So, modeling becomes easy. First, a restaurants collection
{
  _id: someObjectId,
  name: "The Foo Bar",
  cuisine: "Foo and Baz",
  ...
}

and a grades collection:
{
  _id: new ObjectId(),
  restaurant: someObjectId,
  grade: "A",
  date: someISODate
}

Answering the question is nothing more than:
db.grades.find(
  { restaurant: givenRestaurantsObjectId }
)


text:
Q: android nested LinearLayout sizing I am trying to achieve the following layout for my expandable listview.
Layout
Problem:
On android previewer the layout looks as expected:

refer to first image in attachment below.

However, when I run it on an emulator or a device the second TextView is not displayed.

refer to second image in attachment below

I have to set the height of the second ImageView (ivGroupIndicator) to match parent in order for the second TextView to display. But this stretches the expandable arrow icon.

refer to last image in attachment below

Images
Here is my layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="25dp"
        android:layout_height="match_parent"
        android:src="@drawable/ci_hand_cursor"
        android:layout_gravity="center" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingLeft="5dp"
        android:paddingTop="5dp"
        android:layout_weight="0.8">

        <TextView
            android:id="@+id/route_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Dhelhi Belhi"
            android:fontFamily="sans-serif"
            android:textSize="16sp"
            android:textStyle="bold"
            android:textColor="@color/colorPrimaryText"
            android:paddingBottom="2dp"/>

        <TextView
            android:id="@+id/route_schedule_date"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="20-September-2017"
            android:fontFamily="sans-serif"
            android:textSize="14sp"
            android:textColor="@color/colorSecondaryText"
            android:paddingBottom="5dp"/>
    </LinearLayout>

    <ImageView
        android:id="@+id/ivGroupIndicator"
        android:layout_width="25dp"
        android:layout_height="match_parent"
        android:background="@drawable/group_indicator"
        android:layout_gravity="center"/>

</LinearLayout>

What am i missing here?

A: This should do the trick:

*

*Use 0dp as height/width when using weights

*Weight can just be 1 (not 0.8)

*Use equal weights on the 2 text views so they share equal vertical space

*Set gravity to center_vertical on text views so the text is centered.

*set scale type on image so it doesn't stretch.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="25dp"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:scaleType="centerInside"
        android:src="@drawable/ci_hand_cursor" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:paddingLeft="5dp"
        android:paddingTop="5dp">

        <TextView
            android:id="@+id/route_name"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:fontFamily="sans-serif"
            android:gravity="center_vertical"
            android:text="Dhelhi Belhi"
            android:textColor="@color/colorPrimaryText"
            android:textSize="16sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/route_schedule_date"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:fontFamily="sans-serif"
            android:gravity="center_vertical"
            android:text="20-September-2017"
            android:textColor="@color/colorSecondaryText"
            android:textSize="14sp" />
    </LinearLayout>

    <ImageView
        android:id="@+id/ivGroupIndicator"
        android:layout_width="25dp"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:background="@drawable/group_indicator"
        android:scaleType="centerInside" />
</LinearLayout>

A: The problem maybe is that you set the height of the parent layout to 50dp. Try to set it to wrap content, and use height=0dp and weight=1 for the vertical LinearLayout


text:
Q: matrix multiplication of arrays in python I feel a bit silly asking this, but I can't seem to find the answer
Using arrays in Numpy I want to multiply a 3X1 array by 1X3 array and get a 3X3 array as a results, but because dot function always treats the first element as a column vector and the second as a row vector I can' seem to get it to work, I have to therefore use matrices.
A=array([1,2,3])
print "Amat=",dot(A,A)
print "A2mat=",dot(A.transpose(),A)
print "A3mat=",dot(A,A.transpose())
u2=mat([ux,uy,uz])
print "u2mat=", u2.transpose()*u2

And the outputs:
Amat= 14
A2mat= 14
A3mat= 14
u2mat=
 [[ 0.  0.  0.]
        [ 0.  0.  0.]
        [ 0.  0.  1.]]

A: np.outer
is a builtin to do that:
A = array([1,2,3])
print( "outer:", np.outer( A, A ))

(transpose doesn't work because A.T is exactly the same as A for 1d arrays:
print( A.shape, A.T.shape, A[:,np.newaxis].shape )
>>> ( (3,), (3,), (3, 1) )

)
Added: np.add.outer adds pairs of elements --
np.outer is much like np.multiply.outer. And
np.ufunc.outer (A, B) combines pairs with any
binary ufunc.

A: >>> A=np.array([1,2,3])
>>> A[:,np.newaxis]
array([[1],
       [2],
       [3]])
>>> A[np.newaxis,:]
array([[1, 2, 3]])
>>> np.dot(A[:,np.newaxis],A[np.newaxis,:])
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

A: well one way to obtain this is to work with the matrix class/type instead.
import numpy as np
A = np.matrix([1,2,3])
B = A.T  #transpose of A

>>> B*A
>>> matrix([[1, 2, 3],
    [2, 4, 6],
    [3, 6, 9]])

the objects belonging to the matrix class behave pretty much the same as the arrays. Actually arrays and matrices are mutually interchangeable.


text:
Q: Magento SOAP API: How to get SOAP response using JavaScript I'm able to get SOAP response using Magento SOAP API by using PHP code. Now I want it using JavaScript/AJAX request.
How can I accomplish this? What steps should I follow prepare my Magento to allow AJAX http API request?
I tried with the following code for response:
$.soap({
      url: 'https://www.yourdomain.com/api/soap/?wsdl',
      method: 'login',

      data: {
          username:'xxxxx',
          apiKey:'xxxx'
      },

      success: function (soapResponse) {
          alert("yes!!");
      },
      error: function (SOAPResponse) {
          alert(SOAPResponse.toString());
      }
  });

I get this JavaScript error:
XMLHttpRequest cannot load https://www.yourdomain.com/api/soap/?wsdllogin. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 500.


text:
Q: Can't build Unreal Engine 4 project with Microsoft OpenXR plugin I am on on Unreal Engine 4.26.1. I am using Microsoft OpenXR 1.0. I have placed the plugin release files from https://github.com/microsoft/Microsoft-OpenXR-Unreal/releases in the Plugins folder of my Unreal project folder. I am able to compile all project source code from within the editor successfully.
However, when I attempt to package my project, I get the following error:
LogUObjectHash: Compacting FUObjectHashTables data took   0.88ms
LogMainFrame: Selected target: HoloLensTest
LogLauncherProfile: Unable to use promoted target - ../../../../../../Users/sealfoss/Documents/Unreal Projects/HoloLensTest/Binaries/HoloLens/HoloLensTest.target does not exist.
UATHelper: Packaging (HoloLens): Running AutomationTool...
UATHelper: Packaging (HoloLens): Parsing command line: -ScriptsForProject="C:/Users/sealfoss/Documents/Unreal Projects/HoloLensTest/HoloLensTest.uproject" BuildCookRun -nocompileeditor -installed -nop4 -project="C:/Users/sealfoss/Documents/Unreal Projects/HoloLensTest/HoloLensTest.uproject" -cook -stage -archive -archivedirectory=C:/Users/sealfoss/Documents/
UnrealBuilds/HoloLensTest -package -ue4exe="C:\Program Files\Epic Games\UE_4.26\Engine\Binaries\Win64\UE4Editor-Cmd.exe" -ddc=InstalledDerivedDataBackendGraph -pak -prereqs -nodebuginfo -targetplatform=HoloLens -build -target=HoloLensTest -clientconfig=Development -utf8output
UATHelper: Packaging (HoloLens): Setting up ProjectParams for C:\Users\sealfoss\Documents\Unreal Projects\HoloLensTest\HoloLensTest.uproject
UATHelper: Packaging (HoloLens): ********** BUILD COMMAND STARTED **********
UATHelper: Packaging (HoloLens): Running: C:\Program Files\Epic Games\UE_4.26\Engine\Binaries\DotNET\UnrealBuildTool.exe HoloLensTest HoloLens Development -Project="C:\Users\sealfoss\Documents\Unreal Projects\HoloLensTest\HoloLensTest.uproject"  "C:\Users\sealfoss\Documents\Unreal Projects\HoloLensTest\HoloLensTest.uproject" -NoUBTMakefiles  -remoteini="C:\U
sers\sealfoss\Documents\Unreal Projects\HoloLensTest" -Architecture=arm64 -Manifest="C:\Users\sealfoss\Documents\Unreal Projects\HoloLensTest\Intermediate\Build\Manifest.xml" -NoHotReload -log="C:\Users\sealfoss\AppData\Roaming\Unreal Engine\AutomationTool\Logs\C+Program+Files+Epic+Games+UE_4.26\UBT-HoloLensTest-HoloLens-Development.txt"
UATHelper: Packaging (HoloLens):   Using ARM64 architecture for deploying to HoloLens device
UATHelper: Packaging (HoloLens):   Building using Windows SDK version 10.0.18362.0 for HoloLens
UATHelper: Packaging (HoloLens):   Writing manifest to C:\Users\sealfoss\Documents\Unreal Projects\HoloLensTest\Intermediate\Build\Manifest.xml
UATHelper: Packaging (HoloLens):   Building HoloLensTest...
UATHelper: Packaging (HoloLens):   Building 2 actions with 32 processes...
UATHelper: Packaging (HoloLens):     [1/2] HoloLensTestarm64.exe
UATHelper: Packaging (HoloLens):     MixedRealityInteropHoloLens.lib(MixedRealityInterop.obj) : error LNK2038: mismatch detected for 'C++/WinRT version': value '2.0.201113.7' doesn't match value '2.0.200729.8' in PCH.MicrosoftOpenXR.h.obj
UATHelper: Packaging (HoloLens):     MixedRealityInteropHoloLens.lib(CameraImageCapture.obj) : error LNK2038: mismatch detected for 'C++/WinRT version': value '2.0.201113.7' doesn't match value '2.0.200729.8' in PCH.MicrosoftOpenXR.h.obj
UATHelper: Packaging (HoloLens):     MixedRealityInteropHoloLens.lib(AzureSpatialAnchors.obj) : error LNK2038: mismatch detected for 'C++/WinRT version': value '2.0.201113.7' doesn't match value '2.0.200729.8' in PCH.MicrosoftOpenXR.h.obj
UATHelper: Packaging (HoloLens):     MixedRealityInteropHoloLens.lib(SpatialAnchorHelper.obj) : error LNK2038: mismatch detected for 'C++/WinRT version': value '2.0.201113.7' doesn't match value '2.0.200729.8' in PCH.MicrosoftOpenXR.h.obj
UATHelper: Packaging (HoloLens):     MixedRealityInteropHoloLens.lib(HandMeshObserver.obj) : error LNK2038: mismatch detected for 'C++/WinRT version': value '2.0.201113.7' doesn't match value '2.0.200729.8' in PCH.MicrosoftOpenXR.h.obj
UATHelper: Packaging (HoloLens):     MixedRealityInteropHoloLens.lib(MeshObserver.obj) : error LNK2038: mismatch detected for 'C++/WinRT version': value '2.0.201113.7' doesn't match value '2.0.200729.8' in PCH.MicrosoftOpenXR.h.obj
UATHelper: Packaging (HoloLens):     MixedRealityInteropHoloLens.lib(SceneUnderstandingObserver.obj) : error LNK2038: mismatch detected for 'C++/WinRT version': value '2.0.201113.7' doesn't match value '2.0.200729.8' in PCH.MicrosoftOpenXR.h.obj
UATHelper: Packaging (HoloLens):     MixedRealityInteropHoloLens.lib(QRCodeObserver.obj) : error LNK2038: mismatch detected for 'C++/WinRT version': value '2.0.201113.7' doesn't match value '2.0.200729.8' in PCH.MicrosoftOpenXR.h.obj
UATHelper: Packaging (HoloLens):        Creating library C:\Users\sealfoss\Documents\Unreal Projects\HoloLensTest\Binaries\HoloLens\HoloLensTestarm64.lib and object C:\Users\sealfoss\Documents\Unreal Projects\HoloLensTest\Binaries\HoloLens\HoloLensTestarm64.exp
UATHelper: Packaging (HoloLens):     C:\Users\sealfoss\Documents\Unreal Projects\HoloLensTest\Binaries\HoloLens\HoloLensTestarm64.exe : fatal error LNK1319: 8 mismatches detected
UATHelper: Packaging (HoloLens): Took 7.6195669s to run UnrealBuildTool.exe, ExitCode=6
UATHelper: Packaging (HoloLens): UnrealBuildTool failed. See log for more details. (C:\Users\sealfoss\AppData\Roaming\Unreal Engine\AutomationTool\Logs\C+Program+Files+Epic+Games+UE_4.26\UBT-HoloLensTest-HoloLens-Development.txt)
UATHelper: Packaging (HoloLens): AutomationTool exiting with ExitCode=6 (6)
UATHelper: Packaging (HoloLens): BUILD FAILED
PackagingResults: Error: Unknown Error

Any help is appreciated. Thanks in advance.


text:
Q: Any way to get colored icons in alt-tab task switcher in KDE? In KDE, I use the "Layout based switcher" alt-tab task switcher, with the "Informative" layout. All the layouts that display both icons and text have the icons for all but the currently selected task grayed out.
Is there any way to have all icons displayed in color?
As the purpose of the task switcher is to switch to another task, it really makes no sense to have the icons for those tasks grayed out. All it does is to make it take longer to find the right icon as they look less familiar and much more similar to each other.

A: The short answer is no.  KDE 4.8.1 brought about this change to the task switcher, and it has really slowed me down.  The system administrator at my work inquired about it, after I complained, and the response back from the developers was "works for me, so it's not a problem".
This is what happens when "cosmetic" changes are made by people who do not actually use the functionality they are breaking.  It makes as much sense as graying-out all the applications in the main menu/task bar, except for the current one.  Please complain to whomever you can!

A: Here's a patch that will force the use of colored icons in the "compact" and "informative" task switcher.  It also changes the description font to normal, using bold only for the selected window.  It's based on this change: KDE  change 104187
Hope this helps!
--- /var/lib/editconf/originals//usr/share/kde4/apps/kwin/tabbox/compact.qml    2012-06-01 06:20:45.000000000 -0700
+++ /usr/share/kde4/apps/kwin/tabbox/compact.qml    2012-08-09 10:52:08.070420127 -0700
@@ -89,11 +89,11 @@
             id: delegateItem
             width: compactListView.width
             height: compactListView.rowHeight
             Image {
                 id: iconItem
-                source: "image://client/" + index + "/" + compactTabBox.imagePathPrefix + "-" + compactListView.imageId + (index == compactListView.currentIndex ? "/selected" : "/disabled")
+                source: "image://client/" + index + "/" + compactTabBox.imagePathPrefix + "-" + compactListView.imageId + (index == compactListView.currentIndex ? "/selected" : "/selected")
                 width: 16
                 height: 16
                 sourceSize {
                     width: 16
                     height: 16
@@ -107,11 +107,11 @@
             Text {
                 id: captionItem
                 horizontalAlignment: Text.AlignLeft
                 verticalAlignment: Text.AlignBottom
                 text: itemCaption(caption, minimized)
-                font.bold: true
+                font.bold: index == compactListView.currentIndex
                 font.italic: minimized
                 color: theme.textColor
                 elide: Text.ElideMiddle
                 anchors {
                     left: iconItem.right
--- /var/lib/editconf/originals//usr/share/kde4/apps/kwin/tabbox/informative.qml    2012-06-01 06:20:45.000000000 -0700
+++ /usr/share/kde4/apps/kwin/tabbox/informative.qml    2012-08-09 10:52:48.414420651 -0700
@@ -90,11 +90,11 @@
             id: delegateItem
             width: listView.width
             height: listView.rowHeight
             Image {
                 id: iconItem
-                source: "image://client/" + index + "/" + informativeTabBox.imagePathPrefix + "-" + listView.imageId + (index == listView.currentIndex ? "/selected" : "/disabled")
+                source: "image://client/" + index + "/" + informativeTabBox.imagePathPrefix + "-" + listView.imageId + (index == listView.currentIndex ? "/selected" : "/selected")
                 width: 32
                 height: 32
                 sourceSize {
                     width: 32
                     height: 32
@@ -107,11 +107,11 @@
             }
             Text {
                 id: captionItem
                 horizontalAlignment: Text.AlignHCenter
                 text: itemCaption(caption, minimized)
-                font.bold: true
+                font.bold: index == compactListView.currentIndex
                 font.italic: minimized
                 color: theme.textColor
                 elide: Text.ElideMiddle
                 anchors {
                     left: iconItem.right


text:
Q: Anyone used ConQAT with a VB.NET code base To quote from the ConQAT - Continuous Quality Assessment Toolkit website

Long-lived software systems are
  subject to gradual quality decay if no
  counter measures are taken. Continuous
  quality control counters this decay
  through an orchestrated application of
  constructive and analytic quality
  assurance techniques. The Continuous
  Quality Assessment Toolkit ConQAT
  provides the tool-support required to
  enact continuous quality control in
  practice. It supports the rapid
  development of quality dashboards that
  integrate diverse quality analysis
  methods and tools.

However before I spend lots of time looking at it, is it usefull for a VB.NET project?

A: yes. Many of the analyses of ConQAT can be applied to multiple languages. Its two most widely used analyses, namely clone detection and architecture analysis, can be performed for VB.NET.
We are currently working on the ConQAT 2.6 release. I will try to include VB.NET analyses in the ConQAT Examples. Let me know if you are interested to try it before the next release. I can provide configurations that work for VB.NET.
Best regards,
Elmar
P.S.: I am one of the maintainers of ConQAT.


text:
Q: Apache 2.4 PHP 7.4 Include and Require don't include PHP files, but others files types are correctly included I have a weird and quite difficult to understand problem
I have a micro PHP app that has index.php ad a couple of others files *.php that are included in the index.php, let's call the two to be included files include1.php and include2.php
Well, if I try to include include1.php and include2.php, they are NOT included and you get the PHP exception files not present in such path
But, listen listen, if I rename the two files include1.txt and include2.txt THEY ARE INCLUDED!!!
So thank you if you save me from this headache
Please note , the system is basically linux, but the linux of a Synology NAS with the webstation enabled and all the rest ... and since on the same NAS, I have installed PHPMyAdmin and it does work ... I'm pretty sure PHP does work correctly
I suspect about some security configuration issue or permission issue
Thank you for hints and tips

A: After having enabled all the available kinds of errors reporting,
I ended up to notice a MariaDB error
This for some reason was making consequences for the following includes.
Also note that on Synology, the connection string for MariaDB won't work with localhost, use 127.0.0.1 instead


text:
Q: Are non-pointer instance variables stored on the heap? The difference between stack and heap is well documented when in the context of a local function, but I'm curious about instance variables.
Since an instance variable needs to stick around until it is released, is it stored in the same type of memory regardless of whether it is created with new or not?
i.e.
Class A{
  SomeType s1;
  SomeType * s2;
 }

If these were automatic local variables, the difference between these two mechanisms is considerable. But as instance variables, they are more or less in the same place in memory, both on the heap?

A: A::s1 and A::s2 will be, by definition, stored in whatever way and place that an instance of A is created.  As for the location of the storage pointed to by A::s2, it could be anywhere.

A: Non pointer variables are defined in storage areas depending on how or where they are declared.
Myclass obj;

at function scope will be created on automatic storage while if created at global scope will be created with static storage duration.
In your example, both A::s1 and A::s2 will have the same storage area as the object to which they belong. However, since A::s2 is a pointer it might point to a object which might be placed in different storage area.
For example:
void doSomething()
{
    A obj;
    SomeType obj2;
    obj.s2 = &obj2;
}

A::s2 points to a object whose storage is same as obj, while:
void doSomething()
{
    A obj;
    SomeType *ptr = new SomeType;
    obj.s2 = ptr;
}

A::s2 points to a object which is dynamically allocated.
Note: Above code assumes A::s2 to be public for sake of simplicity.


text:
Q: Doubly Linked list in python Using Del I was analyzing a doubly linked list function that deletes a node. However Im a bit confused.
def remove( self, p ) :
        tmp = p.prev
        p.prev.next = p.next
        p.prev = tmp

Why is there a tmp = p.prev and p.prev = tmp. What is the purpose of those extra line? and finally, why is no nodes being deleted with "del"? shouldn't it be "del p" at the end of the code?
Thank you!

A: First, if this is the entire function, it's wrong, which is probably part of the reason you're having trouble understand it.
To remove a node from a doubly linked list, you need to do three things:

*

*Make the previous node point ahead at the next node, instead of the p node.

*Make the next node point back at the previous node, instead of the current one.

*Delete the current node.

Because Python is garbage-collected,1 step 3 happens automatically.2
And step 1 is taken care of by p.prev.next = p.next.
But step 2 doesn't happen anywhere. p.next.prev is still pointing at p, instead of at p.prev. This means that if you walk the list forward, p won't be part of it—but if you walk backward, it will. So p isn't actually removed.
Meanwhile, tmp = p.prev followed by p.prev = tmp doesn't do anything useful.3 And, whatever it was trying to do, you almost never need tmp like that in Python; you can swap values with just x, y = y, x instead of tmp = x; x = y; y = tmp.

So, what you actually want here is:
def remove(self, p):
    p.prev.next = p.next
    p.next.prev = p.prev

1. CPython, the reference interpreter for Python that you're probably using, does garbage collection through automated reference counting, with a cycle breaker that runs occasionally. Whether this counts as "real" garbage collection or not is a nice holy-war argument, but it doesn't matter here.
2. You just need to drop all references to the object, and it becomes garbage and gets cleaned up automatically. So, you need to remove the references from the next and previous nodes to p, which you're already doing. And you need to let p go away, but you don't need del p for that—it's a local variable; it goes away when you return from the function. After that, it's up to the caller of remove; if they don't keep any references to the node, the node is garbage.
3. It could do something useful, if we temporarily assigned a different value to p.prev and wanted to restore it at the end of the function. But that isn't happening here, and I don't think whoever wrote this code intended anything like that; I think they were trying to do some kind of swap.


text:
Q: Why my index of dataframe is changing when I use sub? I have two dataframes. They start at the beginning of December 2020 and end on the 12th of January 2021.
difference = e_forecasts.loc[:, e_forecasts.columns.str.contains('fc')]).sub(productions.loc[:, productions.columns.str.contains('fc')].iloc[:,0], axis = 0)

e_forecasts.head(5)

date                                   fc_fda_A                    fc_f240_A               ...                                                                        ...
2020-12-01 00:00:00                        8.40                         6.44                         6.27  ...                         3.71                        4.66                        5.05
2020-12-01 01:00:00                        7.86                         5.92                         4.32  ...                         0.78                        0.00                        0.00
2020-12-01 02:00:00                        8.53                         5.25                         5.63  ...                         0.00                        0.00                        0.00
2020-12-01 03:00:00                       10.62                         7.45                         5.88  ...                         0.00                        0.02                        0.20
2020-12-01 04:00:00                       11.61                         6.87                         6.43  ...                         1.21                        1.20                        0.74

productions.head(5)
                                    A                B                 C              D      E
date
2020-12-01 00:00:00               1.7             5.53             50.30             1.49                 0
2020-12-01 01:00:00               2.1            11.90             48.45             0.45                 1
2020-12-01 02:00:00               1.8             8.71             40.19             0.00                 0
2020-12-01 03:00:00               3.8            10.44             33.56             0.00                 0
2020-12-01 04:00:00               3.7             3.00             18.78             0.00                 2

difference:
                                       fc_fda_A                    fc_f240_A
date
2020-01-12 00:00:00                         NaN                          NaN                          NaN                          NaN                         NaN                         NaN
2020-01-12 01:00:00                         NaN                          NaN                          NaN                          NaN                         NaN                         NaN
2020-01-12 02:00:00                         NaN                          NaN                          NaN                          NaN                         NaN                         NaN
2020-01-12 03:00:00                         NaN                          NaN                          NaN                          NaN                         NaN                         NaN
2020-01-12 04:00:00                         NaN                          NaN                          NaN                          NaN                         NaN                         NaN
...                                         ...                          ...                          ...                          ...                         ...                         ...
2021-01-12 19:00:00                        2.27                         5.32                         6.47                         3.16                        1.58                        1.58
2021-01-12 20:00:00                       -2.62                         1.51                        -0.92                        -2.21                       -2.93                        1.50
2021-01-12 21:00:00                       -0.27                         0.87                        -0.18                        -0.77                       -0.62                       -0.62
2021-01-12 22:00:00                       19.02                        19.85                        19.37                        19.41                       22.02                       21.61
2021-01-12 23:00:00                       10.16                        11.48                        11.43                        13.97                       10.14                       10.14

When I print difference, the index of difference dataframe is changing. It starts from begining of the 2020 with NaN values. I dont understand what is the problem? Can anyone help me?

A: I think problem is not DatetimeIndex in both DataFrames:
e_forecasts.index = pd.to_datetime(e_forecasts.index)
productions.index = pd.to_datetime(productions.index)

Then solution should by simplier:
df1 = e_forecasts.filter(like='fc')
df2 = productions.filter(like='fc')

difference = df1.sub(df2.iloc[:,0], axis = 0)


text:
Q: Convert easting and northing to latitude longitude cordinates I have some easting and northing coordinates .. and I want to convert this coordinates to latitude longitude.. using java or android libraries.
any suggestions please

A: That is basically the reverse of projection. You need to know what projection your Eastings and Northings are in before you can do anything. Then you can apply the converse of the projection transformation to get Latitudes and Longitudes on a datum. You can either find the transformation (usually a fairly straightforward mathematical function, see the wikipedia link above) and implement it yourself, or use a 3rd-party library such as Geotools or GeoAPI.
See also these two useful pages about the often-used Spherical Mercator:
Spherical Mercator and Google Maps Tiles (Spherical Mercator section)


text:
Q: PHP: Undefined index I have probably made a very simple mistake with this, but I do not see how.. If any of you could help me, I would appreciate it lots.
This is my error:
Notice: Undefined index: admin in C:\xampp\htdocs\forums\classes\User.php on line 75
Here is User.php
public function hasPermission($key) {
    $group = $this->_db->get('groups', array('id', '=', $this->data()->group));

    if ($group->count()) {
        $permissions = json_decode($group->first()->permissions, true);

        if ($permissions[$key] == true) { <<< This is line 75 <<<
            return true;
        }
    }
    return false;
}

Here is where I use hasPermission()
if($user->hasPermission("admin")){
    echo "You are an administrator";
}

var_dump($key);:
string(5) "admin"

var_dump($permissions);
array(1) { ["admin"]=> int(1) }

var_dump($permissions[$key]); outputs:
NULL

A: Try to use this one:
if (isset($permissions[$key]) && $permissions[$key] == 1) {
   return true;
} else {
   return false;
}


text:
Q: What is the use of and how can one add favorites in TeXStudio side pane? I'm using TeXstudio. In the side pane where you can see structures and some symbols, there is tab called Favorites. What is it for? Can one add a command to it manually?

A: If you have symbols you use often, you can add them to the favorites, by right-clicking on a symbol in one of the other tabs:

Click that, and the symbol shows up in favorites:


text:
Q: How to send HTTP request using flow-framework I´m currentliy working in a project. I need to stablish conection with a API-REST (backend) that is built with Java.
The point is that as frontend, I have to use flow-framework. I know how to use Angular als frontend to send http request to backends with Laravel, Symfony or NodeJs..
I habe googled but I don´t find a clear example of how to do it..:((
Maybe could you help me..
Thanks a lot in advance..
Greetings :))


text:
Q: generated AngularJS controller usage Realized that to implement some front-end stuff in my project, it`s better to use a front-end framework, not just a pure JS. Choose AngularJS.
Trying to implement and generated code and stuck with it...
I`ve got this html code generated and and added to the page content on some action,
function Content(i){
    var html =
        '
'+
        '<button ng-click="click_btn()">Load Data!</button>'+
            '
'+
                '
Items List
'+
                '
'+
                    '
'+
                        '
 {{ element }} '
'+
                    '
'+
                '
'+
            '
'+
        '
';

        var ul = document.getElementById('FullList');
        ul.insertAdjacentHTML('beforeend', html);
        AddElementAngular(contentString);
}

And the problem is that AngularJS
 won't work here. can't get why, because code is successfully added to the page. I'm also tried to add click_btn() action and test the controller call on this action, but still doesn't work.
Here is the controller's code
angular.module('MainPage', [])
    .controller('Hello', function($scope, $http) {
        alert('jijij');
        $scope.click_btn = function() {
            alert('fsdfsdfsd');
        }

        $http.get('/api/getlist?groupID=2').
            success(function(data) {
                $scope.content = data;
            });
    });

The page is big to paste it here, but it starts with , so there shouldn't be a problem.
I'm inserted alerts to check, does the code is running. with the dynamic controller load - no. If i just insert controller's code directly in page content - everything works ok.
Controller inserted to the page dynamically only once.  If the function Content(i){} call made again - previous controller's code will be removed.
EDIT:
Found a way to inject generated controller to the scope, from here:
http://geevcookie.com/2014/01/compile-dynamic-html-with-angularjs/
function AddElementAngular(html){
    var $div = $(html);
    $(document.body).append($div);

    angular.element(document).injector().invoke(function($compile) {
        var scope = angular.element($div).scope();
        $compile($div)(scope);
    });
}

But still didn't work properly. Code in the controller is executed(
$http.get('/api/getlist?groupID=2').
    success(function(data) {
        alert(data);
        $scope.content = data;
    });

i get the [object][Object]... etc in alert. ), but the in-page
 {{ element }}
 doesn`t work for unknown reason. I just getting '{{ element }}' in HTML content.