text:
Q: Github: How to embed a gist into README.md? Is it possible to embed gists into README.md file that resides in a GitHub repository?
Something like:

A: This is do-able in 2017 when using GitHub Pages and a Jekyll theme:
See https://gist.github.com/benbalter/5555251 from @benbalter
Simple as: {% gist 123456789 %}

A: No, sorry, that is not possible.  You will have to either have a link to it in your README.md or copy its contents.
Github Flavored Markdown will show you what you can put in your README.md file.

A: You can do it if you are using a markdown preprocessor such as Gitdown:
/**
 * Resolve Gist (https://gist.github.com/)
 *
 * @param {Object} config
 * @param {String} config.id Gist ID.
 * @param {String} config.fileName Gist file name. Default to gistfile1.txt.
 */
gitdown.registerHelper('gist', {
    compile: function (config) {
        config = config || {};
        config.fileName = config.fileName || 'gistfile1.txt';

        if (!config.id) {
            throw new Error('Gist ID must be provided.');
        }

        return new Promise(function (resolve) {
            var https = require('https');

            https.get({
                host: 'api.github.com',
                path: '/gists/' + config.id,
                headers: {
                    // User agent is required to communicate with Github API.
                    'user-agent': 'Gitdown – gist'
                }
            }, function(res) {
                var body = '';

                res.setEncoding('utf8');

                res.on('data', function (d) {
                    body += d;
                });

                res.on('end', function () {
                    var gist = JSON.parse(body);

                    if (!gist.files) {
                        throw new Error('Gist ("' + config.id + '") not found.');
                    }

                    if (!gist.files[config.fileName]) {
                        throw new Error('File ("' + config.fileName + '") is not part of the gist ("' + config.id + '").');
                    }

                    resolve(gist.files['gistfile1.txt'].content);
                });
            });
        });
    }
});

Then in your markdown your would reference the Gist using a JSON hook, e.g.
{"gitdown": "gist", "id": "d3e4212c799252bac5fa"}

This feature should become part of the Gitdown in a near future (there is an open issue, https://github.com/gajus/gitdown/issues/7).

A: Update : My answer works with github pages, built via jekyll. I use the script tags in markdown which is then processed by jekyll.
Since markdown supports html, one can simply use the
..and this is what you will get

A: Some people will end up here due to the fact that they want to use auto-generated gists to make their profile on github more interesting with activity box, productive box, etc. (list of this stuff).
However, you should note that these auto-generated gists should not be added to your profile dedicated README file but should be pinned using the "Customize your pins" option on your profile page.


text:
Q: Is there an ordinal setting in High Charts for Android / iOS? I've come up across an issue which I cannot seem to solve on Android and iOS.
I have a chart that plots data which has the x-axis as a date time. The issue I'm having is that the data I have only has data points during a working week (i.e. Monday - Friday), weekends result in no data.
Here's an example to highlight the issue I'm facing:

I'd like the points to be equally spaced and the periods without any data not to be shown as a gap.
After searching a bit I've found out that High Charts for web has an ordinal property which specifies the gap between each point. (Documentation).
I'm wondering whether there's a similar property in the High Charts for Android and iOS as I couldn't find any information regarding the ordinal property in either High Charts Android or iOS documentation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to prevent trigger from overwriting values that were explicitly set? I tried this but doesn't work because NEW.updated is never NULL (I suppose NEW gets populated by the values currently in the row in addition to the values in the update-statement?):
create temp table test (
    created  TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE FUNCTION update_timestamp() RETURNS TRIGGER AS
$$
BEGIN
    IF NEW.updated IS NOT NULL THEN
        NEW.updated := now();
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER asdf BEFORE UPDATE ON test
FOR EACH ROW EXECUTE PROCEDURE update_timestamp();

How can I make it set NEW.updated := now(); only when updated is not explicitly set in an update-statement? So that the trigger doesn't overwrite me when I want to set the updated column manually (eg. updated=updated).

A: OLD contains the current values in the table, NEW the values like they would be after the UPDATE.
If NEW.updated IS DISTINCT FROM OLD.updated, it is clear that updated must have been changed by the UPDATE statement (or a previous trigger).
If NEW.updated IS NOT DISTINCT FROM OLD.updated, you cannot know if updated was specified in the UPDATE statement or not — the UPDATE could have set updated to the same value that it had before.
So the best you can get is something like
IF NEW.updated IS NOT DISTINCT FROM OLD.updated THEN
   NEW.updated := current_timestamp;
END IF;

This will not do what you want if you have something like SET updated = updated, but there is no remedy for that.

A: No way to determine does some field was set in UPDATE query text. You may operate with NEW.updated and OLD.updated values only.
Actions table:
OLD.updated    NEW.updated    Action
------------------------------------
NULL           NULL           nothing
NULL           now()          nothing
NULL           NOT now()      nothing
now()          NULL           NEW.updated=OLD.updated
now()          now()          nothing
now()          NOT now()      ?
NOT now()      NULL           NEW.updated=OLD.updated
NOT now()      now()          NEW.updated=OLD.updated
NOT now()      NOT now()      NEW.updated=OLD.updated

And compacted form:
OLD.updated    NEW.updated    Action
------------------------------------
NULL           any value      nothing
NOT now()      any value      NEW.updated=OLD.updated
now()          NULL           NEW.updated=OLD.updated
now()          now()          nothing
now()          NOT now()      ?

Define the action unknown to me. Then convert this table to proper If-ElseIf-Else form...
PS. now() means that the difference between field value and current timestamp is negligible small.
--
UPDATE
The final expression will be like:
IF   (OLD.updated != NOW())
  OR (     (OLD.updated = NOW())
       AND (NEW.updated IS NULL)
     )
THEN SET NEW.updated=OLD.updated
ELSEIF     (OLD.updated = NOW())
       AND (NEW.updated != NOW())
THEN ?????
END IF;


text:
Q: Transforming some postgres table
I have some data table like the above left table and it is a snippet, so there are a lot more unique IDs.
I would like to write a postgres code to transform the table to something like the right.


text:
Q: How can I install npm for Opsworks Rails application layer on Ubuntu 12.04 On Ubuntu 12.04, if you install nodejs through the regular sources
apt-get install nodejs

You'll get an older version of nodejs (0.6) that does not contain npm. You can manually install the upstream version and then you will have npm.
Similarily, adding nodejs to OS packages on the Rails applicaiton Layer gives me the older version of node. How can I can install a nodejs with npm for a Rails application layer on OpsWorks?

A: You can use the OpsWorks nodejs cookbook. Make sure you add opsworks_cookbook to Custom Recipes -> Setup, on your Rails application layer. This forces your instance to install the nodejs cookbook on startup, like it would by default if this was a nodejs application layer. You don't need to add nodejs to your OS packages, since it is installed at the setup part of the lifecycle.
Then, in your stack's custom json, set the desired nodejs version :
{
  "opsworks_nodejs": {
    "version": "0.10.25"
  },
}


text:
Q: Do an action when the map is moved I would like to do an action when the map is moved, I tried this feature but it does not work:
func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
    let alert = UIAlertView()
    alert.title = "Hey"
    alert.message = "Map Move"
    alert.addButtonWithTitle("Working!!")
    alert.show()
}

A: Do you set mapView.delegate? If not so, regionWillChangeAnimated method is NOT called.
example.
override func viewDidLoad() {
    super.viewDidLoad()

    mapView.delegate = self
}

ref. My MKMapView sample code
https://github.com/koogawa/MKMapViewSample

A: In my code I have a very similar answer to the answer above but i add a self. first so it looks like this
self.mapView.delegate = self


text:
Q: C programming ++ operator Why does this code always produce x=2?
unsigned int x = 0;
x++ || x++ || x++ || x++ || ........;
printf("%d\n",x);

A: Because of short circuit in boolean expression evaluation and because || is a sequence point in C and C++.

A: || short-circuits. Evaluated from left, when a true value is found (non-zero) it stops evaluating, since the expression now is true and never can be false again.
First x++ evaluates to 0 (since it's post-increment), second to 1 which is true, and presto, you're done!

A: the 1st x++ changes x to 1 and returns 0
the 2nd x++ changes x to 2 and returns 1
at which point the or short circuits, returns true, and leaves x at 2.

A: When you're evaluating "a || b || c || d || e || ..." you can stop evaluating at the first non-zero value you find.
The first "x++" evaluates to 0, and increments x to 1, and evaluating the expression continues.  The second x++ is evaluated to 1, increments x to 2, and at that point, you need not look at the rest of the OR statement to know that it's going to be true, so you stop.

A: x++ || x++ || x++ || x++ || ........;

*

*First x++ evaluates to 0 first for the conditional check, followed by an increment. So, first condition fails, but x gets incremented to 1.

*Now the second x++ gets evaluated, which evaluates to 1 for the conditional check, and x gets incremented to 2. Since expression evaluates to 1 (true), there's no need to go further.

A: Because logical OR short-circuits when a true is found.
So the first x++ returns 0 (false) because it is post-increment.  (x = 1)
The second x++ returns 1 (true) - short-circuits.  (x = 2)
Prints x = 2;

A: Because of early out evaluation of comparisons.
This is the equivalent of
 0++ | 1++

The compiler quits comparing as soon as x==1, then it post increments, making x==2

A: Because the first "x++ || x++" evaluates to "true" (meaning it is non zero because "0 || 1" is true.  Since they are all logical OR operators the rest of the OR operations are ignored.
Mike

A: The || operator evaluates the left-hand expression, and if it is 0 (false), then it will evaluate the right-hand expression.  If the left hand side is not 0, then it will not evaluate the right hand side at all.
In the expression x++ || x++ || x++ || ..., the first x++ is evaluated; it evaluates to 0, and x is incremented to 1.  The second x++ is evaluated; it evaluates to 1, and x is incremented to 2.  Since the second x++ evaluated to a non-zero value, none of the remaining x++ expressions are evaluated.

A: trying replacing || with |.--
It is the short circuiting of logical operators.
It's the same reason when you do
if (returns_true() || returns_true()){ }

returns_true will only get called once.


text:
Q: State Not Getting Set As Required (React, Hooks) I am having trouble setting up a state of my component. Kindly check the details as below
Codesandbox link - https://codesandbox.io/s/goofy-glade-z32zp
This is my App Component containing 4 sub components
import React, { useState } from "react";
import "./App.css";
import RadioType from "./components/Radio/RadioQuestion";
import CheckBox from "./components/Checkbox/CheckBox";
import SelectType from "./components/SelectBox/Selectbox";
import Slider from "./components/Slider/slider";
import data from "./components/jsonData/data.json";
const App = (props) => {

  const [values, setValues] = useState();

  const setAnswerState = (details) => {
    let newState = [];
    if (values !== null && values !== undefined)
     newState = JSON.parse(JSON.stringify(values));
    if (newState === null || newState === undefined) {
      newState = [];
      newState.push(details);
    } else {
      if (
        newState.filter((x) => x.question_id === details.question_id).length ===
        0
      )
        newState.push(details);
      else {
        let indexOfFilteredObj = newState.indexOf(
          newState.filter((x) => x.question_id === details.question_id)[0]
        );
        newState[indexOfFilteredObj] = details;
      }
    }

    setValues(JSON.parse(JSON.stringify(newState)));
    console.log(values)
  };
  return (

      {JSON.stringify(values)}
      {data.map((v, i) => {
        return (

            {v.question_type === "radio" && (
              <RadioType details={v} onChange={setAnswerState} />
            )}
            {v.question_type === "checkbox" && (
              <CheckBox details={v} onChange={setAnswerState} />
            )}
            {v.question_type === "select" && (
              <SelectType details={v} onChange={setAnswerState} />
            )}
            {v.question_type === "slider" && (

                <Slider details={v} onChangeState={setAnswerState} />

            )}

        );
      })}

  );
};

export default App;

Checkbox
import React, { useState } from "react";
const CheckBox = (props) => {
  const { details, onChange } = props;
  const [checkedValues, setCheckedValues] = useState([]);
  const setGlobalState = (value) => {
    let answer = value;
    let stateObj = {
      question_id: details.questionId,
      answers: answer,
      question_type: "checkbox",
    };
    onChange(stateObj);
  };
  return (

{details.question}

        {details.answers === undefined
          ? null
          : details.answers.map((checkBoxAnswers, index) => {
              return (

                  <input
                    type="checkbox"
                    name={`checkbox_${details.questionId}`}
                    value={checkBoxAnswers}
                    onChange={(e) => {
                      let currentValues = checkedValues;

                      if (e.target.checked) currentValues.push(e.target.value);
                      else {
                        const index = currentValues.indexOf(e.target.value);

                        if (index > -1) {
                          currentValues.splice(index, 1);
                        }
                      }
                      setCheckedValues(currentValues);
                      setGlobalState(currentValues);
                    }}
                  />
                  {checkBoxAnswers}

              );
            })}

  );
};
export default CheckBox;

Radio
import React from "react";
const RadioType = (props) => {
  const { details, onChange } = props;
  const setGlobalState = (value) => {
    let answer = [value];
    let stateObj = {
      question_id: details.questionId,
      answers: answer,
      question_type: "radio",
    };

    onChange(stateObj);
  };

  return (

{details.question}

        {details.answers === undefined
          ? null
          : details.answers.map((radioQuestionAnswers, index) => {
              return (

                  <input
                    type="radio"
                    name={`radio_${details.questionId}`}
                    value={radioQuestionAnswers}
                    onChange={(e) => setGlobalState(e.target.value)}
                  />
                  {radioQuestionAnswers}

              );
            })}

  );
};
export default RadioType;

Select
import React from "react";
const SelectType = (props) => {
  const { details, onChange } = props;
  const setGlobalState = (value) => {
    let answer = [value];
    let stateObj = {
      question_id: details.questionId,
      answers: answer,
      question_type: "select",
    };
    onChange(stateObj);
  };

  return (
    <>

{details.question}

        <select
          name={`checkbox_${details.questionId}`}
          onChange={(e) => {
            setGlobalState(e.target.value);
          }}
        >
          {details.answers === undefined
            ? null
            : props.details.answers.map((selectAns, index) => {
                return (
                  <option key={index} value={selectAns}>
                    {selectAns}
                  </option>
                );
              })}
        </select>

    </>
  );
};
export default SelectType;

NouiSlider
import React from "react";
import Nouislider from "nouislider-react";
import "nouislider/distribute/nouislider.css";

const Slider = (props) => {
  const { details, onChangeState } = props;
  const setGlobalState = (value) => {
    let answer = [value];
    let stateObj = {
      question_id: details.questionId,
      answers: answer,
      question_type: "slider",
    };
    onChangeState(stateObj);
  };

  return (
    <>
      <Nouislider
        style={{ color: "red", width: "600px" }}
        start={[0]}
        pips={{ mode: "count", values: details.division }}
        clickablePips
        range={{
          min: details.range.min,
          max: details.range.max,
        }}
        onChange={(e) => {
          let valueOfSlider = parseFloat(e[0]);
          setGlobalState(valueOfSlider);
        }}
      />
    </>
  );
};
export default Slider;

Coming to the problem whenever I try to set state from the radio checkbox or select it does set the state and updates correctly via setAnswerState method that is passed as prop to child. Whenever I try to change the slider the setAnswerState gets values as undefined or null, so the complete state that is set by other child components is lost, I am not able to find the reason behind state lost.
Here is the sample data I used for testing
[
  {
    "question": "When was the Cilivar War?",
    "question_type": "radio",
    "answers": ["1877-1866", "1877-1872", "1877-1851", "1877-1880"],
    "questionId": "099011"
  },

  {
    "question": "World's Largest country by population?",
    "answers": ["China", "Canada", "United kingdom", "India"],
    "correctAns": "China",
    "question_type": "checkbox",
    "dependent_question_id": [
      {
        "question_id": "099011",
        "answers_to_match": [
          {
            "operator": "AND",
            "answers": ["1877-1866"]
          }
        ]
      }
    ],
    "questionId": "0990758"
  },
  {
    "question": "Where is the Tajmahal?",
    "answers": ["Agra", "Mumbai", "Pune", "Punjab"],
    "correctAns": "Agra",
    "question_type": "select",
    "dependent_question_id": [
      {
        "question_id": "099011",
        "answers_to_match": [
          {
            "operator": "AND",
            "answers": ["1877-1866"]
          }
        ]
      },
      {
        "question_id": "099078",
        "answers_to_match": [
          {
            "operator": "AND",
            "answers": ["Canada", "United kingdom"]
          }
        ]
      }
    ],
    "questionId": "099096"
  },
  {
    "questionId": "0002346",
    "question_type": "slider",
    "division": 5,
    "range":
      {
        "min": 0,
        "max": 100
      }

  }
]

A: Just add [] in useState() as shown below:
const [values, setValues] = useState([]);

And then update the setAnswerState method to:
const setAnswerState = (details) => {
  // below statement will handle both the cases:
  // updating an existing question as well as adding in a new question
  setValues((prevValues) => [
    ...prevValues.filter((x) => x.question_id !== details.question_id),
    { ...details }
  ]);
};

A: In your App Component, you need to add [] in useState() as
const [values, setValues] = useState([]);

and inside setAnswerState(), use the newState as the value of setValues().
setValues(newState)

not
setValues(JSON.parse(JSON.stringify(newState)));


text:
Q: How to prove $\lim\limits_{n\to\infty}\left(1+\frac{1}{n}\right)^n=\sum_{k=0}^{\infty}{\frac{1}{k!}}=:e$ I have already proven that $\left(1+\frac 1{n}\right)^n\leq \sum_{k=0}^{n}{\frac{1}{k!}}$ . Does that help me in any way? I am stumped...
Any suggestions/hints?

A: If $n,N\in\mathbb N$, with $n\geqslant N$, then\begin{align}\left(1+\frac1n\right)^n&=\sum_{k=0}^n\binom nk\frac1{n^k}\\&\geqslant\sum_{k=0}^N\binom nk\frac1{n^k}\\&=1+1+\frac{n-1}{2n}+\frac{(n-1)(n-2)}{3!n^2}+\cdots+\frac{(n-1)(n-2)\ldots\bigl(n-(N-1)\bigr)}{N!n^{N-1}}\\&=1+1+\frac1{2!}\left(1-\frac1n\right)+\frac1{3!}\left(1-\frac1n\right)\left(1-\frac2n\right)+\cdots\\&\phantom{=\ }+\frac1{N!}\left(1-\frac1n\right)\left(1-\frac2n\right)\cdots\left(1-\frac{N-1}n\right).\end{align}Therefore,\begin{align}\left(1+\frac1n\right)^n&\geqslant\lim_{n\to\infty}1+1+\cdots+\frac1{N!}\left(1-\frac1n\right)\left(1-\frac2n\right)+\frac1{2!}\left(1-\frac1n\right)\cdots\left(1-\frac{N-1}n\right)\\&=1+1+\frac1{2!}+\cdots+\frac1{N!}\end{align}and so$$\lim_{n\to\infty}\left(1+\frac1n\right)^n\geqslant1+1+\frac1{2!}+\cdots+\frac1{N!}.$$Since this takes place for every $N\in\mathbb N$,$$\lim_{n\to\infty}\left(1+\frac1n\right)^n\geqslant\sum_{k=0}^\infty\frac1{k!}.$$

A: I don't know if this is what you're looking for but:
let exp(x) be the function that satisfies the D.E.:
$$\frac{d}{dx}\exp(x) = \exp(x),\qquad \exp(0) = 1$$
hence if we do a Taylor expansion of this function we get:
$$\exp(x) = \sum_{k=0}^\infty{\frac{x}{k!}}$$
using the limit definition of the derivative with a constant to the power x:
$$\frac{d}{dx}\left(k^x\right) = \lim \limits_{h \to 0}\left(\frac{k^{x+h} - k^{x}}{h}\right) = \lim \limits_{h \to 0}\left(k^{x}\left(\frac{k^{h} - 1}{h}\right)\right) = T\cdot k^{x} $$
where $T = \lim \limits_{h \to 0}\left(\frac{k^{h} - 1}{h}\right)$ is constant with respect to x. Let e be the number such that $T = 1$, trivially, $e^x = \exp(x)$.
rearranging our formula for T:
$$\lim \limits_{h \to 0}\left[\frac{e^{h} - 1}{h}\right] = 1 \Rightarrow \lim \limits_{h \to 0}\left[e =\left(1+h\right)^\frac{1}{h}\right]$$
letting $u = \frac{1}{h}$:
$$e =\lim \limits_{u \to \infty}\left[\left(1+\frac{1}{u}\right)^u\right]$$
hence:
$$\lim \limits_{x \to \infty}\left[\left(1+\frac{1}{x}\right)^x\right]  = e = \exp(1) = \sum_{k=0}^\infty{\frac{1}{k!}}$$


text:
Q: Magento sitemap gets cut off I have a site with three languages and three sitemaps (one for each language).
Two of the languages have working sitemaps (spanish and arabic), but for some reason the english one gets cut off with the following error message:
XML Parsing Error: not well-formed
Location: https://firstaidvendor.com/sitemap/first_aid_vendor_english/sitemap.xml
Line Number 2, Column 664358:

A: There is a error in your data input.
Checked it, more specific in advanced-child-airway-management-torso-with-defibrillation-ecg-and-aed
It has a unsupported char in it. So fix your content and your problem is solved.
I guess it is a category.
Maybe something went wrong copy/pasting.


text:
Q: Real Analysis, Folland 3.4.26 This is the question: "If $\lambda$ and $\mu$ are positive, mutually singular Borel measures on $\mathbb{R}^n$ and $\lambda + \mu $ is regular, then so are $\lambda$ and $\mu$".
I need a solution for this problem. I can prove the first condition of regularity. Also, I can prove the second condition of regularity in borel sets such that $(\lambda+\mu)(E)< \infty$. How I can solve when $(\lambda+\mu)(E)=\infty$?

A: The finiteness of $\lambda$ and $\mu$ on compact sets is immediate from positivity and the corresponding property for $\lambda+\mu$. Let $E$ be a Borel set. By symmetry, it suffices to show that
$$
\lambda(E)=\inf \{\lambda(U): E \subset U, U \text { open }\}
$$
Let $G_{k}=[-k, k]^{n}$ so that $\mathbb{R}^{n}=\bigcup_{k} G_{k}$ and $(\lambda+\mu)\left(G_{k}\right)<\infty .$ Let
$\epsilon>0 .$ By the outer regularity of $\lambda+\mu$ we can find, for each $k$, an open $U_{k} \supset\left(E \cap G_{k}\right)$ with $(\lambda+\mu)\left(U_{k} \backslash\left(E \cap G_{k}\right)\right)<\epsilon 2^{-k}$
Letting $U=\bigcup_{k} U_{k}$, we then have $(\lambda+\mu)(U \backslash E) \leq \epsilon$ and so $\lambda(U \backslash E)<$
$\epsilon$, which gives what is needed, since $\epsilon$ was arbitrary.


text:
Q: How to get uid from ssh certificate attribute I'm working on deployment of ssh certificates instead of just public keys in my organisation. My goal is to keep uid the same for each user across the infrastructure and I think the best way to achieve that is to add uid as a certificate attribute (ssh certificates allow that). In my opinion it brings the following benefits:

*

*there's no need to sync local users db with remote database, so I can spin up a virtual machine and not to wait for my user to appear in the vm;

*it's more reliable as I don't need to keep a remote users db always up and ready for sync;

*should be easier to maintain as I don't need to configure NSS and use custom sync plugins;

I wonder is there any way to extract the attribute and use it in sshd for user login? Is there any way to create user runtime when sshd checks its certificate?


text:
Q: Confused between the isomorphism and continuity of $M_n\mathbb{R}$ with $\mathbb{R}^{n^2}$ I've managed to confuse myself while doing a few excercises in topology where I was asked to find the closure of a $M_2(\mathbb{R})$. The following are the questions I have.

*

*Is there a continuous map from $f:M_2(\mathbb{R}) \rightarrow \mathbb{R}^4$. Why is this map continuous? If so, how do I show in terms of topological spaces. That is if $U$ is an open set then $f^{-1}(U)$ is open.

*Continuity of topological maps doesn't a prior assume a metric right?

*I know the $\exists \, f$ such that $f:M_2(\mathbb{R}) \rightarrow \mathbb{R}^4$ is an isomorphism. But isomorphism tells nothing about the continuity between topological spaces right?
4.There is a statement as follows :

Consider $M_n(\mathbb{C})$ with the topology of $\mathbb{C}^{n^2} \cong \mathbb{R}^{2{n^2}}$. Let $D$ be the set of diagonalizable matrices.Find the closure $\bar{D}$ in $M_n(\mathbb{C})$

. I find this to an extremely vague statement. I am not able to understand what topology on $M_n(\mathbb{C})$ they are referring to. Yes, I agree that $M_n(\mathbb{C})$ is isomorphic to $\mathbb{C}^{n^2}$ and inturn isomorphic to $\mathbb{R}^{2{n^2}}$. But! How does that induce a topology on $M_n(\mathbb{C})$?

*Clearly, the isomorphism is inducing a topology which I dont see how. I've all these questioned jumbled up, unable to sort them systematically. Any help would be greatly appreciated!

Assuming that we know the topology om $\mathbb{R}^{2{n^2}}$ (AGAIN! what exactly is the topology on $\mathbb{R}^{2{n^2}}$ that we are assuming, is the box topology with standard basis?


text:
Q: Image quality gets low after cropping I am capturing an image using camera intent and send it to server. But the problem is when i crop this image its quality is reduced to great extent. It looks weird. I am using Samsung note 2 for testing but image quality is too poor after cropping. Can any one please share a Good cropping code that does not reduces its quality? This is my current Code to Crop an image.
public void performCrop(Uri picUri) {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        cropIntent.setDataAndType(picUri, "image/* ");
        cropIntent.putExtra("crop", "true");
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        cropIntent.putExtra("outputX", 200);
        cropIntent.putExtra("outputY", 200);
        cropIntent.putExtra("return-data", true);
        startActivityForResult(cropIntent, PIC_CROP);
    } catch (ActivityNotFoundException anfe) {

        String errorMessage = "Whoops - your device doesn't support the crop action!";
        toast(errorMessage);
    }

}

Thanks in advance.


text:
Q: c++ maximum std::string length is dictated by stack size or heap size? as asked in the question.
std::string myVar; the maximum character it can hold is dictated by stack or heap?
Thank you

A: By default, the memory allocated for std::string is allocated dynamically.
Note that std::string has a max_size() function returning the maximum number of character supported by the implementation. The usefulness of this is questionable, though, as it's a implementation maximum, and doesn't take into consideration other resources, like memory. Your real limit is much lower. (Try allocating 4GB of contiguous memory, or take into account memory exhaustion elsewhere.)

A: A std::string object will be allocated the same way an int or any other type must be: on the stack if it's a local variable, or it might be static, or on the heap if new std::string is used or new X where X contains the string etc..
But, that std::string object may contain at least a pointer to additional memory provided by the allocator with which basic_string<> was instantiated - for the std::string typedef that means heap-allocated memory.  Either directly in the original std::string object memory or in pointed-to heap you can expect to find:

*

*a string size member,

*possibly some manner of reference counter or links,

*the textual data the string stores (if any)

Some std::string implementations have "short string" optimisations where they pack strings of only a few characters directly into the string object itself (for memory efficiency, often using some kind of union with fields that are used for other purposes when the strings are longer).  But, for other string implementations, and even for those with short-string optimisations when dealing with strings that are too long to fit directly in the std::string object, they will have to follow pointers/references to the textual data which is stored in the allocator-provided (heap) memory.


text:
Q: In IE 11 javascript input event is not getting fired Am trying to capture the score 0 to 10 using range control. If there is no interaction done with range control then I need to disable the Next button. This is working fine in chrome,but in IE 11 below code is not getting invoked when range value is being changed. How to fix this?
$( 'input[type="range"]' ).on( 'input', function () {

    var control = $( this ),
        controlMin = control.attr( 'min' ),
        controlMax = control.attr( 'max' ),
        controlVal = control.val(),
        controlThumbWidth = control.data( 'thumbwidth' );

    var range = controlMax - controlMin;

    var position = ( ( controlVal - controlMin ) / range ) * 100;
    var positionOffset = Math.round( controlThumbWidth * position / 100 ) - ( controlThumbWidth / 2 );
    var output = control.next( 'output' );

    output
        .css( 'left', 'calc(' + position + '% - ' + positionOffset + 'px)' )
        .text( controlVal );

    $( this ).attr( "data-modified", "1" );

    $( "#next" ).removeAttr( "disabled" );

} );

A: I think IE11 is firing change-event, instead of input-event when range of range-input is changed.
Here's an interesting comparison


text:
Q: What scenarios would NativeOverlapped or System.Threading.Overlapped be useful in PFX IOTaskScheduler? I'm looking at the PFX team's Parallel Extensions Extras DLL and see an IOTaskScheduler that uses NativeOverlapped, and System.Threading.Overlapped methods.
Since there isn't much documentation on when each extension is useful, it is up to me to read the source code and determine when I should use a given function.
When would I use the IOTaskScheduler, or the NativeOverlapped feature?
(Direct link to source code)
(Documentation at bottom of this page)


text:
Q: Is this the right equation to compute the likelihood of a normal distribution at a point? This wiki gives this equation of maximization of the log-likelihood function.
${\displaystyle \ln {\mathcal {L}}(\mu ,\sigma ^{2})=\sum _{i=1}^{n}\ln f(x_{i}\mid \mu ,\sigma ^{2})=-{\frac {n}{2}}\ln(2\pi )-{\frac {n}{2}}\ln \sigma ^{2}-{\frac {1}{2\sigma ^{2}}}\sum _{i=1}^{n}(x_{i}-\mu )^{2}.}$
This post gives an python implementation for the equation
this python code is adapted from that post to compute the likelihood at a point.
def llnorm(par, data):
    mu, sigma = par
    ll = math.log(2*math.pi*(sigma**2))/2 + np.sum(((data-mu)**2)/(2 * (sigma**2)))
    return ll

this video gives the value of the likelihood of a normal distribution with $\mu = 32, \sigma = 2.5$ at $x=34$, which is approximately equal to 0.12
I put the params in to my function
llnorm([32,2.5],34)

and got 2.155, which is far from the example. Could someone help to analyze this?

A: What you are using is log-likelihood.
To compute likelihood, please use this


text:
Q: How can I speed up development builds while developing a linked package? (Ember/Broccoli) My Broccoli builds take up a LOT of time. ~30 seconds to build every time I change a line of js (I mean the incremental re-builds with dev server running, NOT a complete build).
Here's my situation. I have project A which is an ember addon to project B which I npm link in. As I'm developing project A, I am running ember server on project B.
EVERY SINGLE TIME that I make a change to a line of javascript in project A and rebuild, I see that the following files change in project B:
B/dist/assets/vendor.css
B/dist/assets/vendor.js
B/dist/assets/vendor.map
B/dist/assets/B.css
B/dist/assets/B.css.map

My concern is that, because I'm developing a linked package, my broccoli configuration is such that the entire node_modules is recombined into those vendor files.
Is there a way for me to configure ember/broccoli to use a separate file to compile A into and segregate it from the rest of vendor.js? B/dist/assets/A.min.css and B/dist/assets/A.min.js for example?
...or I'm a guessing at the cause of the problem incorrectly?
Thank you so much for your help in advance!
Edit: Here's some extra info as requested
Slowest Nodes (totalTime => 5% )              | Total (avg)
----------------------------------------------+---------------------
Concat (11)                                   | 39239ms (3567 ms)
RecastFilter (280)                            | 33127ms (118 ms)
Babel (233)                                   | 14099ms (60 ms)
EslintValidationFilter (5)                    | 12632ms (2526 ms)
LessCompiler (46)                             | 7191ms (156 ms)

Slowest Nodes (totalTime => 5% )              | Total (avg)
----------------------------------------------+---------------------
SourceMapConcat: Concat: Vendor /asset... (1) | 36270ms
LessCompiler (46)                             | 4029ms (87 ms)

Here's the index.js (Of project A):
const EngineAddon = require('ember-engines/lib/engine-addon');
const TreeMerger = require('broccoli-merge-trees');
const LessCompiler = require('broccoli-less-single');
const Funnel = require('broccoli-funnel');
const path = require('path');

module.exports = EngineAddon.extend({
  name: 'ember-engine-admin-ui',
  lazyLoading: false,

  treeForVendor(tree) {
    let addonTree = this.treeGenerator(path.resolve(this.root, this.options.trees.addon));
    let compiledLessTree = new LessCompiler(addonTree, 'styles/addon.less', `styles/${this.name}.css`);
    let sidebarCSSTree = new Funnel(path.dirname(require.resolve('sidebar-v2/css/leaflet-sidebar.css')), {
      files: ['leaflet-sidebar.css'],
      destDir: 'styles'
    });

    let sidebarJSTree = new Funnel(path.dirname(require.resolve('sidebar-v2/js/leaflet-sidebar.js')), {
      files: ['leaflet-sidebar.js'],
      destDir: 'js'
    });
    return new TreeMerger([tree, compiledLessTree, sidebarCSSTree, sidebarJSTree]);
  },

  included() {
    this._super.included.apply(this, arguments);
    this.import(`vendor/styles/${this.name}.css`);
    this.import('vendor/js/leaflet-sidebar.js');
    this.import('vendor/styles/leaflet-sidebar.css');
  },

  isDevelopingAddon() {
    return true;
  }
});


text:
Q: Are all quantum scalar fields related to the Klein-Gordon field? In the book "Quantum Field theory and the Standard Model" by Matthew Schwartz, the author states:

In quantum field theory, we generally work in the Heisenberg picture, where all time dependence is in operators such as $\phi$ and $a_p$. For free fields, the creation and annihilation operators for each momentum $\bf{p}$ in the quantum field are just those of a simple harmonic oscillator. These operators should satisfy $a_p(t) = e^{-i\omega_p t}a_p$ and $a_p^\dagger(t) = e^{i\omega_p t}a_p^\dagger$, where $a_p$ and $a_p^\dagger$ are time independent. Then we can define a quantum scalar field as
$$\phi_0({\bf{x}}, t)=\int \dfrac{d^3 p}{(2\pi)^3}\dfrac{1}{\sqrt{2\omega_p}}(a_p e^{-ipx}+a_p^\dagger e^{ipx})$$
with $p^\mu = (\omega_p, {\bf{p}})$ and $\omega_p = |{\bf{p}}|$.

Now I first thought the author was presenting the KG field as just one example. I also thought that this form of writing $\phi$ was only for the KG field, after all it was developed in order to make the field satisfy the massless KG equation.
By this statement, it seems that the author implies this is valid for all quantum scalar fields. Is this true? I mean, this exact same expansion, with creation and annihilation operators defined in a Fock Space, is valid for all quantum scalar fields?
If so, what distinguishes one field from the other?
And why it would be reasonable for this to be so general as that, if it was derived from a very simple case?

A: Note that the excerpt you cite says:

For free fields, the creation and annihilation operators for each momentum $\mathbf p$ in the quantum field are just those of a simple harmonic oscillator.

So the author is implying that all free, i.e. non-interacting, scalar fields are the same (apart from their mass), which is true because the differences between fields are down to their differing interactions.
The problem is that the states of an interacting field are not Fock states. Indeed we don't know what the states of an interacting field are since we cannot solve the equations for them and instead we have to fall back to using perturbation theory. That means we don't know what the creation and annihilation operators are either.

A: As John Rennie's answer noted, interacting cases such as $\phi^4$ theory don't have this form. You can show the integral representation you quoted implies $\hat{\phi}$ has zero vacuum expectation value, which should tell you the Highs field is something different; indeed, this is due to such a quartic potential term, which leads to a nonlinear differential equation whose solutions don't comprise a vector space. That somewhat scuppers the attempt to provide such an integral representation.
It's also worth noting that, in a general curved spacetime, scalar fields satisfying a homogeneous linear equation such as KG have an analogous integral representation in which the ladder operators' coefficients are the classical solutions, which cannot be expected to be $\exp\pm ip\cdot x$ in most spacetimes.


text:
Q: Accessing array element in Ember handlebars I have a simple array in the controller:
App.HomeController = Ember.Controller.extend({
    items: ['item1', 'item2', 'item3']
});

I would like to render the first element in the template; following instructions in other posts I'm doing:
{{items.[0]}}

Or this…
{{controller.items.[0]}}

…but the result is always nothing; am I doing anything wrong here?

A: You're doing nothing wrong. These should work (demo).
The problem lies somewhere else. Can't tell without more code.


text:
Q: In Vim, how do I delete everything but keep what is in double quotes? I have multiple lines of plain texts and each line is mixed with phrases with/without double quotes. I want to delete everything including quotes but keep what's in double quotes.
Example:
this is some test = "key.properties";
properties = "value.properties";

Result should be:
key.properties
value.properties

A: :%s/.*\"\(.*\)\".*/\1
Explanation
REPLACE, ANY_STRING, QUOTES, CAPTURE_ANY_STRING,   QUOTES,  ANY_STRING WITH
  :%s/     .*        \"      \(     .*     \)       \"         .* .    /\1

A: If your cursor is at the start of the line, you can do:
f"lyi"Vp

f"l move cursor to first " then left one more space
yi" yank everything within the "s to the anonymous register
Vp select the whole line in visual mode and paste the anonymous register over it
To apply to multiple lines, use the normal command.
:%normal 0f"lyi"Vp

: enter command mode
% set the range as the whole file
normal execute the following key strokes as if they were entered in normal mode
0 move cursor to start of line
f"lyi"Vp see above


text:
Q: How can I add errors to ModelState using the correct key in ASP.NET MVC? I want to perform some simple form validation in my controller.
Here's an excerpt from the controller action:
// other code

            if (!string.IsNullOrEmpty(editModel.NewPassword)
                && editModel.RepeatNewPassword != editModel.NewPassword)                {
                // problem line... How to I get the key from editModel?
                ModelState.AddModelError("", "The new password does not match the repeated password.")
            }

// other code

It appears that must use a string as the error's key. Is there a way i can generate the corect key from the model, or should I just check for what input name Html.PasswordFor(x => x.NewPassword) returns?

A: Not exactly what you are asking for, but will solve your problem:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class PropertiesMustMatchAttribute : ValidationAttribute
{
    #region [ Fields ]

    /// <summary>
    /// Defines the default error messsage
    /// </summary>
    private const string DefaultErrorMessage = "'{0}' and '{1}' do not match.";

    /// <summary>
    /// Defines a typeId
    /// </summary>
    private readonly object typeId = new object();

    #endregion

    #region [ Constructors ]

    /// <summary>
    /// Initializes a new instance of the PropertiesMustMatchAttribute class.
    /// </summary>
    /// <param name="originalProperty">The original property name</param>
    /// <param name="confirmProperty">The confirm (or match) property name</param>
    public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
        : base(DefaultErrorMessage)
    {
        this.OriginalProperty   = originalProperty;
        this.ConfirmProperty    = confirmProperty;
    }

    #endregion

    #region [ Properties ]

    /// <summary>
    /// Gets the confirm property name
    /// </summary>
    public string ConfirmProperty { get; private set; }

    /// <summary>
    /// Gets the original property name
    /// </summary>
    public string OriginalProperty { get; private set; }

    /// <summary>
    /// Gets a unique identifier for this <see cref="T:System.Attribute"/>.
    /// </summary>
    /// <returns>An <see cref="T:System.Object"/> that is a unique identifier for the attribute.</returns>
    /// <filterpriority>2</filterpriority>
    public override object TypeId
    {
        get
        {
            return this.typeId;
        }
    }

    #endregion

    #region [ Overrides ]

    /// <summary>
    /// Applies formatting to an error message, based on the data field where the error occurred.
    /// </summary>
    /// <returns>An instance of the formatted error message.</returns>
    /// <param name="name">The name to include in the formatted message.</param>
    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, this.OriginalProperty, this.ConfirmProperty);
    }

    /// <summary>
    /// Determines whether the specified value of the object is valid.
    /// </summary>
    /// <returns>true if the specified value is valid; otherwise, false.</returns>
    /// <param name="value">The value of the object to validate. </param>
    public override bool IsValid(object value)
    {
        var properties      = TypeDescriptor.GetProperties(value);
        var originalValue   = properties.Find(this.OriginalProperty, true /* ignoreCase */).GetValue(value);
        var confirmValue    = properties.Find(this.ConfirmProperty, true /* ignoreCase */).GetValue(value);
        return Equals(originalValue, confirmValue);
    }

    #endregion
}

And then:
[PropertiesMustMatch("NewPassword", "RepeatNewPassword ", ErrorMessage = "The new password and confirmation password do not match.")]
public class YourModel
{
     public string NewPassword {get;set;}
     public string RepeatNewPassword {get;set;}
}

A: Or in your ViewModel you can do this
    public class ClassName
    {
        public string Password { get; set; }

        [Compare("Password" , "Password Must Match")]
        public string ConfirmPassword { get; set; }
    }

this is new to mvc3 and you can implement your custom attribute like this fairly easy in mvc3
because IsValid now recives a ValidationContext parameter which contains information about the validation that is being performed like the type of the model and metadata associated with it so you can use reflection to get other properties and their value the CompareAttribute made use of this feature


text:
Q: While loop to join panda dataframes once again thank you in advance for any help you might be able to give me. I have a data set that has all values for devices on a fiber network, rolling down from a central node to a node's multiple amplifier,and finally to all addresses attached to that node.
The issue is that there can be multiple amps between the node and an address. I am trying to find which node each address is attached to. Each device(address, amp, node) has an ID, DEVICE_TYPE_DESC and a UPSTREAM_DEVICE_ID. So as an example:
 ID:1 DEVICE_TYPE_DESC:ADDRESS UPSTREAM_DEVICE_ID: 2
 ID:2 DEVICE_TYPE_DESC:AMP UPSTREAM_DEVICE_ID: 3
 ID:3 DEVICE_TYPE_DESC:AMP UPSTREAM_DEVICE_ID: 4
 .....
 ID:10 DEVICE_TYPE_DESC:NODE UPSTREAM_DEVICE_ID: 9

So I want to be able to join ID:1 to ID:10, but to do that I need to join to each and every amp in between. I'm new to python so I'm not sure if what I am trying to do is even possible, but I'm working on creating a while loop that will iteratively join to the device table again, and create a flag that will change to 1 when the join brings in the node, and stop when the sum of the node_flag=len(address_table).
I have written the code to manually join for the first round, and partially written what I think the general look of the while loop might look like. The main issue I am having is trying to figure out how to rename the columns in the right table each time, and then using that most recently appended 'upstream_device_id' to use as the left key for the next iteration of joining. ADD_DEV is a filtered table from DEVICE that contains only addresses. NO_ADD is a second filtered table from DEVICE that contains everything else except addresses
 add_dev.merge(
     no_add[["id","device_type","upstream_device_id"]],
     how="left",
     left_on="upstream_id",
     right_on="id"
 )
 add_dev["left_join"] = add_dev["upstream_device_id"]
 count = len(add_dev.index)
 x=0
 while count > 0:
   x=x+1

   add_dev.merge(
       no_add[["id","device_type","upstream_device_id"]].rename(
           index=str, columns={
               "id":"id_[x]",
               "device_type":"device_type_[x]",
               "upstream_device_id":"upstream_device_id_[x]"
           }),
           how="left",
           left_on="left_join",
           right_on="id_[x]"
       )

 add_dev["node_flag"]=np.where(add_dev["device_type_[x]"]=='node',1,0)
 add_dev["left_join"] = np.where(add_dev["node_flag"] == 1, 0, add_dev[upstream_device_id_[x]])

 count = len(add_dev.index)-add_dev["tap_flag"].sum()

So the final add_dev dataframe would have 'x'+1 number of id, device_type_id, and upstream_device_id columns. But I know that I can't rename the columns using [x] like I am doing above. Any thoughts and how I could get this to work?

A: Figured it out. Hopefully this will help anyone who has a similar issue as I did.
add_dev = device[device["device_type"]=="address"]

add_dev["join_left"]=add_dev["upstream_device_id"]

count = add_dev.shape[0]
x=0

while count>0:
  x+=1
  add_dev = add_dev.merge(
       no_add[["id","device_type","upstream_device_id"]].rename(
           index=str, columns={
               "id":"id_"+str(x),
               "device_type":"device_type_"+str(x),
               "upstream_device_id":"upstream_device_id_"+str(x)
           }),
     how="left",
     left_on="join_left",
     right_on="id_"+str(x)
  )

  add_dev["node_flag"]=np.where(add_dev["device_type_"+str(x)]=='node',1,0)
  add_dev["join_left"] = np.where(add_dev["node_flag"] == 1, -999, add_dev["upstream_device_id_"+str(x)])
  count = add_dev.shape[0]-add_dev["node_flag"].sum()


text:
Q: C: handling case...else What is the correct way to put an else clause in a switch statement? For example, instead of:
switch (input) {
    case (1):
        printf("yes!");
        break
    case (0):
        printf("no!");
        break;
   default:
        printf("invalid!");
}

To do something along the lines of (if possible):
switch (input) {
    case (1):
        printf("yes!");
    case (0):
        printf("no!");
   else:
        printf("invalid!");
}

I'm simply asking if there is a short-cut to not have to add a break after every case statement to act as-if it were the else part of an if statement.

A: The correct way is using default. Also ,you don't have to use break for non-default cases, only if you don't want execution to fall into the next case.


text:
Q: How to make this controller's class & constructor reusable? public class AccountsMstController : Controller
{
    private AccountsMstRepository _AccountsMstRepository;
    public ErpOneLogRepository _ErpOneLogRepository;
    private DeleteRecordRepository _DeleteRecordRepository;
    private IHttpContextAccessor _contextAccessor;
    private HttpContext _context;
    private string username;
    private IHostingEnvironment _env;
    private string user;
    private string dbname;
    public AccountsMstController(IHttpContextAccessor contextAccessor,
    IHostingEnvironment env)
    {
        _contextAccessor = contextAccessor;
        _context = _contextAccessor.HttpContext;
        username = _context.User.Identity.Name;
        _env = env;

        string[] Split = username.Split(new char[] { '@', '.' });
        dbname = Convert.ToString(Split[1]);
        user = Convert.ToString(Split[0]);
        _AccountsMstRepository = new AccountsMstRepository(dbname);
        _DeleteRecordRepository = new DeleteRecordRepository(dbname);
        _ErpOneLogRepository = new ErpOneLogRepository(dbname);
    }
 }

Trying to make this code reusable and can be called through function pointers as it is used in every Controller's class & constructors. I am trying to make this in a single method with can pass dynamic parameters and could be called from different classes.

A: I would start of with using an interface:
public interface IController {
    HttpContext Context{get; set; }
    string Username {get; set; }
    IHostingEnvironment Environment {get; set; }
    string User {get; set; }
    string DbName {get; set; }
    UnitOfWork ControllerWork {get; set;}
}

Assuming the repositories contain a DbContext object you could use the Repository - UnitOfWork pattern
public interface UnitOfWorkFactory {
    AccountsMstRepository AccountsMstRepository {get; set;}
    ErpOneLogRepository ErpOneLogRepository get; set;}
    DeleteRecordRepository DeleteRecordRepository {get; set;}
    DbContext DbContext {get; set;}

    // CRUD methods to update repository
}

public interface RepositoryFactory {
    DbContext context {get; set;}

    // CRUD methods to update repository
}

This way each different controller can implement the IController interface, so you can access the repositories on each controller using the intermediary UnitOfWork (you need to make a class that implements this)
If you want to make this even more reusable and you are using the Entity Framework you can use a BaseModel and implement the RepositoryFactory using basetype T, this way your UnitOfWorkFactory will not get cluttered. But for this, this is alright.
Here's a link on the pattern: microsoft-uow pattern implementation
Hoping to have answered your question.
Joachim.

A: How about using a BaseController class with constructor accepting IHttpContextAccessor and IHostingEnvironment and have all controllers inherit from it ?


text:
Q: ReadTheDocs: Publishing Pre-Built HTML Pages to ReadTheDocs I was trying to create documentation from python doc strings, and found pdoc. If you don't know, it creates html documentation from python doc strings. Since it generates .html files and not .rst, how do I publish those to ReadTheDocs or generate .rst files using pdoc?
Quick sidenote: I don't want to use sphinx since 1) the theme pdoc has is pretty cool and 2) I don't know how to generate documentation from docstrings using sphinx (all the tutorials I looked at didn't help).

A: Read the Docs released a beta feature some time ago that allows you to completely override the build process. This means that you can execute custom commands (e.g. pdoc) and output all the HTML to a particular directory (_readthedocs/html). Once the build is finished, Read the Docs will publish the content of that directory.
Check out the documentation at https://docs.readthedocs.io/en/stable/build-customization.html#override-the-build-process


text:
Q: Disabling the zoom/pan/scroll functions for the Webbrowser Control I have seen many posts about how it's impossible to disable the zoom/pan/scroll functions on the Web-browser control natively for Windows Phone 7. So what options do we have?

A: I did a little digging and I found a quick way to do so, so I thought I'd share it here.
It's not a quick few lines of code which is a shame but all of it is up on the web so it should be easy to implement. First you need the Linq ddl and this class here called LinqToVisualTree. Then you can use these in a WebBrowserHelper class where you just pass in your web browser when you create the webBrowserHelper and the rest is taken care of. You can even set whether or not you'd like the scrolling to be disabled.
One problem I found with this was that when I double tap on the web page it still zooms in sometimes. Does anyone know how this might be fixed? I'm sure there is a way to do it using the LinqToVisualTree but I can't figure it out.


text:
Q: What happens to a int i = Integer.parseInt(string) when there are no integers in string? Right now, I am making a simple tic-tac-toe project. I would like to know what happens to the integer i when:
string s = "hello"; //or something else, non integer

int i = Integer.parseInt(s);

What will i be equal to?

A: Integer.parseInt("hello") statement will throw an exception: java.lang.NumberFormatException

A: If the given string does not contain a parseable integer, a
NumberFormatException will be thrown.
For more information, see:  https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29


text:
Q: Do the synthetics/artificial persons in the Alien universe really eat? In both Ridley Scott's and James Cameron's Alien franchise films we see the synthetic Ash drinking a milk-like substance and artificial person Bishop eating some corn bread.
Do they actually process these substances and burn for fuel like humans or are they eating to 'fit in' with everyone else? I know no-one knew at the beginning Ash was a robot so the fitting in part is in regards to Bishop.

A: According to the Aliens: Colonial Marines Technical Manual, androids (sorry, 'synthetic people') are powered by a "25 kW hydrogen fuel cell". There's no indication that they need to eat for sustenance or gain any energy by doing so.

The modern synthetic is a highly complex machine: stronger, faster and better coordinated than an average human. The basic chassis is a carbon fiber skeleton with latchment points for the artificial musculature. The muscles are vat-grown silicone colloids powered either by pumped microhydraulics or electrical stimulation. Power for the android is supplied by a 25 kW hydrogen fuel cell with a life of approximately 400 days between refueling. As in a human, the skeletal structure is inherently unstable and is effectively suspended by the musculature. No limb locking, joint motorization or gyrostabilization is present as in other anthropomorphic frames such as powerloaders; instead, the muscles must work actively to keep the chassis standing upright while active feedback systems control its stability. Though the muscles can withstand considerable wear and tear, the lack of a self-repair facility means that they eventually lose their strength and become increasingly elastic over time. It is recommended that the muscle system be overhauled on a regular basis and individual elements replaced fully every two years. Muscle layout and operation, as with certain other internal functions, are homologous with those of the human body; indeed, military synthetics are designed to be virtually indistinguishable in appearance from a human.

You might also want to note that the plan diagram of its internal 'organs' is entirely lacking anything that resembles a digestive system aside from a small container that appears to attach to the penis (and presumably the anus) to allow it to store a small amount of food during chow-time and then excrete it convincingly, should the need arises.


text:
Q: How to get the Google ad manager impression of a placement using api (PHP)? I am able to connect with my ad manager account using Google Ad Manager API (https://github.com/googleads/googleads-php-lib/tree/master/examples/AdManager). I am getting data i.e all companies, all placement on my command line. But confused on getting impressions.

How to get an impression of a placement?

A: First, you will need a query. Using the UI is the easiest way to build a query, and see the results. Here's the guide from Google to create a query on the UI.
Then, you will save the query and follow the ReportService/RunSavedQuery.php example to download the impression report in your program.
Please note that the examples are removed every 4 quarters and replaced by newer examples. So, if the example link above doesn't work, the example might have been replaced with a newer one.
This question is not a PHP specific question. Indeed, it is a "how to use the product" question, and is best suitable to be answered on the Google Ad Manager product forum. If you raise a question on the forum, the support staff may get back to you on a secured channel to help you build the query.


text:
Q: C# how to check if adjacent values are greater or smaller in an array and allocate points based on values? I am trying to figure out how to assign points based on adjacent number values in an array. By default, each number is worth one point, and it increases in value if the adjacent numbers are lower than the current number.
For values at the start and the end of the array, the adjacent values are the end and start, so for numbers[0] adjacent values are numbers[5] && numbers[1] and for numbers[5] the values would be numbers[4] && numbers[0]. Consider it going in a circle.
As an example of numbers let's say we have int[] numbers = new int[] { 5, 6, 4, 2, 5, 6 }; after point allocation the output should be something like 1 3 2 1 2 3.
The issue I'm facing is that I don't know how to write the code in such a way that I don't get an error. And I would like to avoid using a lot of if nested functions. Managed to get it working like that but it looks horrible, so scrapped that and figured there must be a better way of doing this but I seem to be stuck...
        static int[] AssignPoints (int[] numbers) {
            int[] points = new int[numbers.Length];
            for (int i = 0; i < numbers.Length; i++) {
                points[i]++; //allocating initial point
                ???

            }

            return points;
        }

A:     static int[] AssignPoints (int[] numbers) {
       int[] points = new int[numbers.Length];
       for (int i = 0; i < numbers.Length; i++)
       {
         int prevIndex = (i-1 < 0 ? numbers.Length -1 : i-1);
         int nextIndex = (i+1 >= numbers.Length ? 0 : i + 1);

         if (numbers[i] > numbers[prevIndex])
            points[i]++;

         if (numbers[i] > numbers[nextIndex])
            points[i]++;
       }
       return points;
    }

A: A very explicit example:
static int[] AssignPoints (int[] numbers) {
    int[] points = new int[numbers.Length];
    for (int i = 0; i < numbers.Length; i++) {
        var leftIndex = i == 0 ? numbers.Length - 1 : i - 1;
        var rightIndex = i == numbers.Length - 1 ? 0 : i + 1;

        points[i] = 1
            + (numbers[i] > numbers[leftIndex] ? 1 : 0)
            + (numbers[i] > numbers[rightIndex] ? 1 : 0);
    }
    return points;
}

A:         static List<int> AssignPoints(List<int> numbers)
        {

            List<int> points =new List<int>(numbers.Capacity);
            int i = 0, point;

            foreach (int item in numbers)
            {
                point = 1;

                if(i != 0)
                    if (numbers[i - 1] < numbers[i]) point++;
                if(i != numbers.Capacity -1)
                    if (numbers[i + 1] < numbers[i]) point++;

                i++;
                points.Add(point);
            }

            return points;
        }


text:
Q: Prove that oscillation function is upper semicontinous Suppose $X$ is a Polish space and $Y$ a compact metrizable space. Denote $P_k(Y)$ to be the collection of all non-empty, compact subsets of $X$. Denote the Hausdorff metric $d_H : P_k(Y) \rightarrow P_k(Y)$ by $d_H(A,B) = \inf \{ \varepsilon > 0 : A \subseteq B_{\varepsilon} \text{ and } B \subseteq A_{\varepsilon}\}$ where $A_{\varepsilon}$ denotes the $\varepsilon$-ball around $A$.
Let $F : X \rightarrow P_k(Y)$ be a multifunction or set-valued mapping. For any closed set $P \subseteq X$, denote $F|_P$ as the restriction of $F$ to $P$, such that $P(x) = \emptyset$ for all $x \not\in P$ and $F|_P(x) = F(x)$ for all $ x \in P.$
Define the oscilation function of $F|_P$ at $x$ by $osc(F|_P)(x) = \inf_{V \in N(x)} \sup_{x_1, x_2 \in V \cap P}{d_H(F(x_1), F(x_2))}.$
Question: How to prove that $osc(F|_P)$ is an upper semicontinuous function?
Definition: A multifunction $F : X \rightarrow Y$ is an upper semicontinuous function if $\{ x \in X : F(x) \subseteq U\}$ is an open subset of $X$ for every $U \subseteq Y$ open.
Remark: The oscillation function $osc(F|_P)$ is a real-valued function. This question is motivated by this paper, page $73$, Theorem $18.$

A: (1) Assume that $x_n\rightarrow x$ and $g(y):={\rm osc}\ (F|P)(y)$
Then there are neighborhood $U_n$ of $x_n, y_n,\ z_n\in U_n$ and $\delta_n,\ \varepsilon_n\rightarrow 0$
 s.t. $$
 g(x_n) +\varepsilon_n >
 \sup_{ y,\ z\in U_n}\ d_H(F(y),F(z)) \geq g(x_n) $$
and $$  d_H(F(y_n),F(z_n)) \leq  \sup_{ y,\ z\in U_n}\ d_H(F(y),F(z)) <
 \delta_n + d_H (F(y_n), F(z_n)) $$
Hence $|d_H(F(y_n),F(z_n))
-g(x_n) |\leq \varepsilon_n+\delta_n$
(2) There is neighborhood $V_n$ of $x$ s.t. $g(x)=\lim_n\ \sup_{y,\
z\in V_n}\ d_H(F(y),F(z)) $
By re-indexing we can assume that $y_n,\ z_n\in V_n$ Hence $
g(x)\geq d_H(F(y_n),F(z_n))$ so that $$g(x)\geq \lim\ \sup_n\
d_H(F(y_n),F(z_n)) =\lim\ \sup_n\ g(x_n)$$


text:
Q: Some questions on probability spaces I wanted to double check if my thoughts were correct and would appreciate any tips/help/other ways of going about it.

*

*Let $\Omega = \mathbb{R}^{2}$ and let $\mathscr{F}=2^{\mathbb{R}^{2}}$. Is $\mathscr{F}$ a $\sigma$-field over $\Omega$?

Yes, $\mathbb{R}^{2} \in \mathscr{F}$ by definition of $\mathscr{F}$. Also, we can show it is closed under complements and under countable unions. Not part of the question, but would a probability space be possible using this $\Omega$ and $\mathscr{F}$?

*Let $\Omega=\{1,2,3,4,5,6\}$ and $\mathscr{F}=2^{\Omega}$. Suppose that P is some probability measure on $(\Omega, \mathscr{F})$, specified in some way, but simply unknown to us. Consider the set $S=\{\frac{n}{100}: n = 1,2,3, ..., 100\}$. Is it the case that there necessarily exists a number $p \in S$ such that no event in $\mathscr{F}$ has probability equal to $p$?

I am leaning towards yes. The collection $\mathscr{F}$ has $2^{6}=64$ elements and the cardinality of the set $S$ is $100$. Each element in the collection $\mathscr{F}$ has a defined probability, because it is a possible outcome. So there should be $64$ distinct values of $P(E)$, $E$ being an element of the collection $\mathscr{F}$. But since $|S|$ > $|\mathscr{F}|$ it has to be that there exists a number $p \in S$ such that no event in $\mathscr{F}$ has probability equal to $p$.

*Suppose $(\Omega, \mathscr{F}, P)$ is a probability space and that A and B are events in $\mathscr{F}$. Suppose further that $P(A)+P(B) \geq 1$. Must it be the case that either A or B occurs?

I am no too sure. Does "either A or B occurs" mean either A, or B, or both? How can the probability of two events be greater than 1? Unless you let $A=\Omega$ and $B$ be any other event with positive probability. But in that case, B is a proper subset of A so only A is really occurring? I am just very confused.

*Suppose $\Omega=\{a,b\}$. Let $\mathscr{F}=2^{\Omega}$. Show that there exist probability measures $P'$ and $P$ on $(\Omega, \mathscr{F})$ s.t $P(\{a\})=0.1$ and $P(\{a\})=0.7$.

You can choose $P'$ to be the function that takes $\{a\}$ to $0.1$ and $\{b\}$ to $0.9$, and choose $P$ to be the function that takes $\{a\}$ to $0.7$ and $\{b\}$ to $0.3$. Then just show that these functions satisfy Kolmogorov's 3 axioms?


text:
Q: Delete/Undeploy selected soa composite application deployed on SOA server How to Undeploy selected SOA composite applications from the SOA_server.
I have 70 application deployed on soa_server, few of them are important for future reference. I need help if we can undeploy the selected soa composite application from soa_server.
I have found a command using WLST on oracle site, if anyone can help on undeploying selected soa composite application in one go from soa_server1.
Thanks in advance

A: The use case you describe is suited to the use of SOA-Infra Partitions. Using partitions you can undeploy, retire, shutdown and startup all composites deployed to a partition as a group. To create a partition, in the EM FMC, go to soa-infra, then select Manage Partitions from the drop-down menu. Deploy the desired composites to this partition and then you can control them all at once.
This is how to manage a logical group of composites in "one go." Without the partition solution, you will need to script-undeploy each composite separately. These docs provide specific instructions.


text:
Q: Angular2 with Typescript - Error loading angular2/platform/browser I have spent way too much time on this, but I am stuck and can't figure out how to get Angular2 with Typescript to run.  I keep getting a 404 for the components:
Error loading http://localhost:5000/angular2/platform/browser as "angular2/platform/browser" from http://localhost:5000/appScripts/boot.js

Here is my folder structure:
My index.html is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Angular 2 with ASP.NET Core</title>
<!-- 1. Load libraries -->
<script src="libs/es6-shim/es6-shim.min.js"></script>
<script src="libs/zone.js/dist/zone.js"></script>
<script src="libs/reflect-metadata/Reflect.js"></script>
<script src="libs/systemjs/dist/system.src.js"></script>

<!-- 2. Configure SystemJS -->
<script src="./appScripts/config.js"></script>
<script>

    System.import('appScripts/boot')
          .then(null, console.error.bind(console));
</script>

</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>

The boot.ts:
 /// <reference path="../node_modules/angular2/typings/browser.d.ts" />
    import {bootstrap} from 'angular2/platform/browser'
    import {AppComponent} from './app'
    bootstrap(AppComponent);

The app.ts:
    /// <reference path="../typings/jquery/jquery.d.ts" />
    /// <reference path="../typings/angularjs/angular-route.d.ts" />
    /// <reference path="../typings/angularjs/angular.d.ts" />

    import {Component} from 'angular2/core';
    @Component({
    selector: 'my-app',
    template: 'My First Angular 2 App'
    })
    export class AppComponent { }

The config.js
(function (global) {

    // map tells the System loader where to look for things
    var map = {
        'app': 'appScripts', // 'dist',
        'rxjs': 'libs/rxjs',
        'angular2-in-memory-web-api': 'libs/angular2-in-memory-web-api',
        '@angular': 'libs/@angular'
    };

    // packages tells the System loader how to load when no filename and/or no extension
    var packages = {
        'app': { main: 'boot.js', defaultExtension: 'js' },
        'rxjs': { defaultExtension: 'js' },
        'angular2-in-memory-web-api': { defaultExtension: 'js' },
    };

    var packageNames = [
      '@angular/common',
      '@angular/compiler',
      '@angular/core',
      '@angular/http',
      '@angular/platform-browser',
      '@angular/platform-browser-dynamic',
      '@angular/router',
      '@angular/router-deprecated',
      '@angular/testing',
      '@angular/upgrade',
    ];

    // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
    packageNames.forEach(function (pkgName) {
        packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
    });

    var config = {
        map: map,
        packages: packages
    }

    // filterSystemConfig - index.html's chance to modify config before we register it.
    if (global.filterSystemConfig) { global.filterSystemConfig(config); }

    System.config(config);

})(this);

Here is more of the folder structure to give you a better idea of the project structure.

Here is my package.json
{
  "version": "1.0.0",
  "name": "ASP.NET",
  "private": true,
  "dependencies": {
    "@angular/common": "2.0.0-rc.1",
    "@angular/compiler": "2.0.0-rc.1",
    "@angular/core": "2.0.0-rc.1",
    "@angular/http": "2.0.0-rc.1",
    "@angular/platform-browser": "2.0.0-rc.1",
    "@angular/platform-browser-dynamic": "2.0.0-rc.1",
    "@angular/router": "2.0.0-rc.1",
    "@angular/router-deprecated": "2.0.0-rc.1",
    "@angular/upgrade": "2.0.0-rc.1",
    "systemjs": "0.19.27",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "angular2-in-memory-web-api": "0.0.7"
  },
  "devDependencies": {
    "gulp": "^3.9.0",
    "gulp-autoprefixer": "~3.1.0",
    "gulp-concat": "~2.6.0",
    "gulp-imagemin": "~2.4.0",
    "imagemin-pngquant": "~4.2.0",
    "jshint": "2.9.2",
    "gulp-jshint": "2.0.0",
    "jshint-stylish": "~2.1.0",
    "rimraf": "~2.5.1",
    "gulp-minify-css": "~1.2.4",
    "gulp-sass": "2.2.0",
    "gulp-uglify": "~1.5.1",
    "gulp-sourcemaps": "~1.6.0",
    "gulp-plumber": "1.1.0",
    "gulp-notify": "2.2.0",
    "beepbeep": "1.2.0",
    "gulp-rename": "1.2.2",
    "gulp-sourcemap": "1.0.1",
    "gulp-clean-css": "2.0.6",
    "main-bower-files": "2.13.0",
    "gulp-filter": "4.0.0",
    "typescript": "^1.8.10",
    "gulp-typescript": "^2.13.1",
    "live-server": "1.0.0",
    "typings": "^1.0.4",
    "gulp-tsc": "^1.1.5"
  }
}

Thank you in advance for your help and please let me know if I can provide some more details.

A: You're using rc.1 version of angular but trying to import beta version.
You need to use @angular/.. like this:
import { bootstrap } from '@angular/platform-browser-dynamic';

import { Component } from '@angular/core'; // instead of 'angular2/core'
....

For more details see also changelog https://github.com/angular/angular/blob/master/CHANGELOG.md#200-rc0-2016-05-02

To import various symbols please adjust the paths in the following
  way:

angular2/core -> @angular/core
angular2/compiler -> @angular/compiler
angular2/common -> @angular/common
angular2/platform/browser -> @angular/platform-browser + @angular/platform-browser-dynamic
angular2/platform/server -> @angular/platform-server
angular2/testing -> @angular/core/testing
angular2/upgrade -> @angular/upgrade
angular2/http -> @angular/http
angular2/router -> @angular/router-deprecated (from beta.17 for backwards compatibility)
new package: @angular/router - component router with several breaking changes


text:
Q: Can Timestamp be given as Input and display it as output in an Android application In my android application, can user be able to enter the timestamp manually and submit to the database and can the same timestamp be displayed as out put.I also need to display a blob time same way.Is it possible?
In this process
just like for retrieving a text,integer we use
object.getText()toString();

Integer.parseInt(object.getText()toString());

Is there anyway like that for TimeStamp and Blob ?
please do help
Thanks in advance

A: You'll need to use ContentProvider in order to save things to database. Take a look at this tutorial.
Android SQLite database and content provider - Tutorial
To let user enter the date manually, I'll recommend you to use DatePicker.


text:
Q: Bar chart does not appear with Chart.js I'm a beginner trying out Chart.js and I'm having trouble with getting my bar chart to appear. When I try and run this code all I get is a blank screen, any idea why?
<div id="chart">
<canvas id="myGraph" width="400" height="400"></canvas>
</div>

<script>
var myData = {
        labels: ["2000", "2001", "2002", "2003"],
        datasets: [{
        label: 'Test chart',
        data: [20, 50, 10, 12],
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
        ],
        borderWidth: 1
    }]
   },
});

var ctx = document.getElementById("myGraph").getContext("2d");
var debt = new Chart(ctx).Bar(myData);

</script>

A: You have several typos in your JSON literal.
I rewrote it like so (see here for the JSFiddle)
var config = {
        type: 'bar',
        data: {
        labels: ["2000", "2001", "2002", "2003"],
        datasets: [{
        label: 'Test chart',
        data: [20, 50, 10, 12],
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
        ],
        borderWidth: 1
    }]
  }
};
var ctx = document.getElementById("myGraph");
var debt = new Chart(ctx, config);


text:
Q: Microsoft Graph: is there a way to un-cancel a recurrence in a recurring event? A bit of context: we have a system which stores recurring events in the RRULE format and we have the EXDATE part which stores exceptions. Obviously we can add and remove exceptions for the whole serie by just adding/removing entries in the EXDATE section of it.
We wanna basically sync our system with an outlook calendar, but apparently in MS Graph there is no concept of an event with exceptions, or at least I could find anything similar. All I could do is to remove an occurrence from series, which is fine.
But the restoring doesn's seem to be supported at all. I am wondering if there is a way of restoring a deleted event? Or rather is there any better way than removing the whole serie and start over again?


text:
Q: pass array to a function I am getting results from rest service into one string, it contain a number(id) or multiple number(multiple id) seprated by commas.
Now i want to pass above id or multiple id into function as a parameter so it returns me rolename,  so how can i pass multiple id to functionin javascript....Kindly help as i am new to programming
var roleNamedata = 'javascript=xdmp.roleName(' + '"' + id+ '"' + ')';

how can i  pass array to above function,  and how to convert string into array

A: the following code will help u to convert a comma separated string into an array,
var string = "1,2,3,4,5";
var array = string.split(","); // string to array conversion
function takesArray(a) { // taking an array as parameter
    console.log(a);
}
takesArray(array); // passing array as argument

A: use Array.forEach
var a = ['a', 'b', 'c'];

a.forEach(function(element) {
    console.log(element);
});

// a
// b
// c

or Array.map
    var a = ['a', 'b', 'c'];
a.map(function(element) {
    console.log(element);
});

// a
// b
// c

console.log() will print value into developers tools console (on chrome hit F12)


text:
Q: Boundedness of set with function on prime divisors Let $P(n)$ denote the product of the prime divisors of $n$, e.g., $P(100)=2\times 5=10$. Define $$A=\{\frac{a}{P(ab(a-b))} \mid a,b\in\mathbb{Z}^+, a>b\}.$$ Is $A$ bounded or not?
To make the value $\frac{a}{P(ab(a-b))}$ high, we can choose $a$ to be a perfect power, such as $a=2^n$, and $b$ can be some constant. This would suffice if $a-b$ consists of only small prime factors for some large $n$.

A: Take $a=2\cdot 3^n,$ $b=3^n.$ Then the term becomes $3^{n-1}.$
[I assume from your example $P$ only is product of the distinct primes dividing $n,$ and note with these choices $P(ab(a-b))=2\cdot 3.$]


text:
Q: Customized facebook login page Can we customize facebook login/authentication page?
I want to use my own customized pop up for receiving 'Email' and 'Password' input from user so that it is consistent with the GUI of my application. Is there a facebook API to which I can pass the Email/Password details received from user?

A: Looking at https://developers.facebook.com/docs/reference/api/user/#permissions  you cannot "create" new permissions. This has to go through Facebook so they know what permissions have been granted. This ensures that you're not just granting permissions on behalf of a user without them having actively granted them. This therefore stands to reason that you cannot style their page.
Alternatively, you could just make sure users register via an account on your site (You want a password so I assume you don't mean their facebook password) and then ask them to connect their facebook account to it. You would need to ask for their email in your form, get them to login, then connect via facebook and associate their facebook id with their account on your site.


text:
Q: freebsd postfix python policyd-spf ip addres validation error I recently encountered a problem on my freebsd postfix mail server with the packet py27-postfix-policyd-spf-python-1.3.2_1
My maillogs where full with the following messages:
policyd-spf[16637]: ERROR: 127.0.0.0/8 in skip_addresses not IP network.  Message: '11.22.33.44' does not appear to be an IPv4 or IPv6 address. Did you pass in a bytes (str in Python 2) instead of a unicode object?. Aborting white list processing.

Switching to python 3 as suggested by other people did NOT work (neither changing the shebang, nor starting it via python3 directly

A: The solution to my Problem was (for now) to add the following lines to the function _cidrmatch in /usr/local/bin/policyd-spf
def _cidrmatch(ip, netwrk)
  netwrk = unicode(netwrk)
  ip = unicode(ip)
  try:
    address = ipaddress.ip_address(ip)

This is done so that the python module ipaddr only has to deal with unicode string (as requested by the error message)
switching to python3 as suggested by other posts on the web did not work for me (maybe some missing dependencies?)
This post also helped me a lot
https://stackoverflow.com/questions/30389019/valueerror-10-0-0-0-24-does-not-appear-to-be-an-ipv4-or-ipv6-network
BUT KEEP IN MIND: this fix will be GONE after the packet gets an update, so this is just intended as a helpful note to someone running into the same problem as I did!
So if anybody has a real solution, let us know :)


text:
Q: how to filter with having clause in window function over avg? I created a fiddle http://sqlfiddle.com/#!17/f882b/23.
It has table 'scots' with name, age, country, weight.
select name, weight, country,
avg(weight) over (order by name) as avg_weight_over_computed
from scots
-- group by country
having avg_weight_over_computed > 76
order by name

This above not working with "having" clause. I want to filter  those avg_weights > 76. How to do this?

A: In this case, the HAVING could be converted to a where clause in a subquery?
SELECT * FROM
(
  select
    name,
    weight,
    country,
    avg(weight) over (order by name) as avg_weight_over_computed
  from
      scots
)
AS X
where
  avg_weight_over_computed > 76


text:
Q: Invoke UI from pseudo console We have some UI test cases which we are currently invoking manually on our Linux machine (with Gnome enabled).
We login to the machine and run the below command:
java -jar test_case.jar

to invoke the test case. This opens the browser and performs the application test, and then writes the logs and quits.
Now  I am planning to automate this in a Jenkins Pipeline Job.
But I am not sure what would be the right way to do this,
because I believe Jenkins Pipeline Job gets executed in a pseudo terminal,
whereas I believe the above command should be executed in a Gnome console.
Is there a way to automate this scenario?

A: Xvfb (X Virtual Frame Buffer) can be used for this purpose. It allows you to have a display that exists only in-memory, so that tests/operations with graphical dependencies can be completed without actually using a GUI.
On CentOS, you can install Xvfb from the core CentOS repository with yum:
yum install xorg-x11-server-Xvfb

Once Xvfb is installed, prefix your command with xvfb-run to use it:
xvfb-run java -jar test_case.jar

xvfb-run is a wrapper command that does a few useful things. First, it initializes an Xvfb display and passes it to your command for execution. Once the command runs to completion, the display is also gracefully shut down.


text:
Q: Deserialize a Byte Array created in C# in Python I have a 2D jagged double array in C# which I converts to a byte array like this:
byte[][][] byteArray = new byte[10][][];

I am saving the byte array as a binary file in this way:
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
{
   formatter.Serialize(stream, byteArray);
}

Now, I need to read the file in python in order to re-build there the 2D double array...
I was trying to use numpy.fromfile() and would like to know how this should be done.

A: From what I can tell, BinaryFormatter and numpy.fromfile() are not made to cross platforms, let alone languages. It will be easier to use a format that is more cross-platform, like JSON. The portion of converting the double to a byte[] might also have issues, e.g. because of endianness. If the performance and data requirements aren't really an issue, it'd be easier to not complicate things.
This example uses Json.NET for the C#:
double[][] myArray = // whatever

var path = // whatever
using (StreamWriter file = File.CreateText(path))
{
    JsonSerializer serializer = new JsonSerializer();
    serializer.Serialize(file, myArray);
}

And then in the Python all you have to do is something like:
import numpy
import json
path = # whatever
with open(path) as f:
    myArray = numpy.array(json.load(f))
# we now have the array! e.g.
print(myArray.dtype) # float64
print(myArray[0][0]) # 0.79449418131


text:
Q: Bootstrap overriding with bootstrap-rails gem with less Im trying to change the bg colour of the .well.
I have to override because @import "twitter/bootstrap/bootstrap"; brings the css in from the twitter-bootstrap-rails gem, so I can't edit the raw bootstrap file.
Is there a way to override it using less without doing something like:
.well {
    background: red;
}

(Because this way there are two .well definitions given to the browser - this one above and the original from bootstrap)
It looks like bootstrap does have a way of overriding: for instance to change the body's background I can use @bodyBackground. But i'm not sure what the definitions are for the .well which isn't as well documented.

A: They aren't using any variables like @bodyBackround inside the .well definition (wells.less). So this nice and easy solution is no option for you.


text:
Q: Mixitup library - Do not run sort on non target elements I am using mixItUp library to sort and filter elements.
In my project i have non target elements in between the target elements which are being sorted as well.
i am trying to sort only the target ones!
For example:
mixitup('#mix-wrapper', {
  load: {
    sort: 'order:asc'
  },
  animation: {
    effects: 'fade rotateZ(-180deg)',
    duration: 700
  },
  classNames: {
    block: 'programs',
    elementFilter: 'filter-btn',
    elementSort: 'sort-btn'
  },
  selectors: {
    target: '.mix-target'
  }
});

Informatics(G)

Criminology(P)

Sociology(U)

Greek(U)

i am non target element and i want to stay here!

Astrophysics(P)

Nursing(U)

Mathematics(U)

Nanoscience(G)

i am another non target element and i want to stay here as well!

Pathology(P)

Management(G)

Pubpc Health(P)

Is it possible ?


text:
Q: Room-runtime: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.7.1, expected version is 1.5.1.: Hello I get an error after adding Room dependencies and changing the Kotlin version doesn't seem to fix the issue.
error:
/Users/Erin/.gradle/caches/transforms-3/c3d04919ade1d841f45db1aa77dde355/transformed/room-runtime-2.4.3-api.jar!/META-INF/room-runtime_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.7.1, expected version is 1.5.1.

build.gradle(:app)
dependencies{
    def room_version = "2.4.3"

        //room dependencies
implementation("androidx.room:room-runtime:$room_version")
annotationProcessor("androidx.room:room-compiler:$room_version")
// To use Kotlin annotation processing tool (kapt)
kapt("androidx.room:room-compiler:$room_version")
implementation("androidx.room:room-ktx:$room_version")

}

build.gradle(:project)
buildscript {
    ext {
        compose_version = '1.1.0-beta01'
    }

    dependencies {
        classpath("com.google.dagger:hilt-android-gradle-plugin:2.42")
    }
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.2.1' apply false
    id 'com.android.library' version '7.2.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.5.31' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

A: Update your Kotlin version to 1.6.10
id 'org.jetbrains.kotlin.android' version '1.5.31' apply false


text:
Q: Trying to calculate the Pixastic color adjust values from a hex or RGB color I've inherited a small web application that has a feature where the user can select a color from a dropdown, then a portion of an image is colorized.
The colorization happens via a Javascript library called Pixastic.
Pixastic loads an image into a canvas element, the processes the image using its Pixastic coloradjust function.
In my case, the image being processed is a transparent PNG with black/gray outlines. The end result is that only the black/gray outlines get colorized.
But here's the tricky part.
The Pixastic coloradjust function doesn't just take a hex or RGB color. It takes a set of adjustment parementers which adjust the red, green, and blue channels. Each adjustment value can be a decimal number from -1 to 1.
The coloradjust function basically works like this:

*

*Let r be the red channel adjustment value.

*Multiple r * 255 and let the result be redVal

*Loop over each pixel in the image

*Add redVal to the red value of the pixel (redPixel)

*If redVal + redPixel < 0, then set the pixel to 0

*If redVal + redPixel > 255, then set the pixel to 255

*Otherwise, set the pixel to redVal + redPixel
*Do the same thing for the green and blue channels.

If it helps, here's the actual code of the coloradjust function.
I have a list of existing colors and adjustment values.
My task is to add some new colors to the app but I'm completely stuck on figuring out how to calculate the color adjustment values for PIxastic given a hex color.
There doesn't seem to be any correlation between the existing hex colors and adjustment values so I'm afraid the existing adjustment values were someone figured out manually.
Here are a few example colors from the existing system:

*

*#603314

*

*Red color adjust -0.1

*Green color adjust -0.5

*Blue color adjust -0.3

*#82bad4

*

*Red color adjust 0.2

*Green color adjust 0.4

*Blue color adjust 0.4
Given all of the above, how can I figure out the color adjustment values for a new hex color like #cc9e3c?

A: I've taken a shot at creating some functions to return red, green and blue scale, the way the problem is described. However, none of my calculations match the examples, so I am guessing that I do not understand the question fully. Nonetheless...
function redScale(colorInput) {return parseInt(colorInput.substring(1,3),16)/255 * 2 - 1;}
function grnScale(colorInput) {return parseInt(colorInput.substring(3,5),16)/255 * 2 - 1;}
function bluScale(colorInput) {return parseInt(colorInput.substring(5,7),16)/255 * 2 - 1;}

The substring method grabs the two digit hex value from the colorInput string. After I have the two-digit hex string, I convert it to decimal using parseInt. Divide it by 255, to get it to a scale from 0 to 1. Since the scale goes from -1 to 1 (a length of 2), you multiply it by 2 (to get a scale of 0 to 2), and then subtract 1, yielding a scale of -1 to 1. */
var colorInput = "#603314";

rCS = redScale(colorInput);
gCS = grnScale(colorInput);
bCS = bluScale(colorInput);
document.write("input: " + colorInput + "
red: "+rCS+"
","green: " + gCS + "
" + "blue: " + bCS + "

");

colorInput = "#82bad4";

rCS = redScale(colorInput);
gCS = grnScale(colorInput);
bCS = bluScale(colorInput);
document.write("input: " + colorInput + "
red: "+rCS+"
","green: " + gCS + "
" + "blue: " + bCS + "

");

colorInput = "cc9e3c";
rCS = redScale(colorInput);
gCS = grnScale(colorInput);
bCS = bluScale(colorInput);

document.write("input: " + colorInput + "
red: "+rCS+"
","green: " + gCS + "
" + "blue: " + bCS);


text:
Q: Android drawer not for navigation I wish to know if it is possible to do something. I know this is not the purpose of a drawer, but I have to use it something else than navigation in my case.
For example, it want to display some text, with drag and drop, the user can delete text or add new text with a button in it.
I can't display this text outside of this drawer because of UI.
I think it's not possible (I find nothing to do or talk about it on internet), if you can confirm this to me, it will be helpfull.
If you think it's possible, do you have any idea where to start ?
And, can I use a short video instead of an icon for an item ?
Thanks for your answer.

A: The DrawerLayout is just a different type of ViewGroup. You can place anything you want within it.


text:
Q: Making your own cusctom workflow developed in visual studio 2010 available in sharepoint designer 2010 Well my requirement is :
Need to develop a custom workflow,the workflow should take properties like site url, list names etc., From the client.
I am able to develop the workflow, but i need to make it available in designer. I tried the method mentioned here:
http://www.chaholl.com/archive/2010/03/13/make-a-custom-activity-available-to-sharepoint-designer-2010.aspx.
1)I have created the required action file.
2)deployed(copy-pasted) dll into gac.
3)made safe-control and authorized type entries in web.config of the corresponding web application(on which my site collection exists)
But it is not helping me out.after following the steps given,when i try to open any workflow in designer,it gives an error saying it cannot find an action(assembly) with xyz name.

A: If I understand correctly, you built an entire workflow and am trying to make it available to SharePoint Designer.  The guide you are following deals with custom "Actions".  Actions are a sub part of a workflow.  This may explain why your deployment isn't working, because you're trying to deploy a workflow as an action.
If you could provide more information about your steps, we could try and figure it out.
Thanks
C
http://www.cjvandyk.com/blog


text:
Q: WPF ComboBox using shortcut keys for selecting items I have a combo box in WPF that uses the following data template.  With help from the forum I was able to get this to display and behave properly.
When the drop down is open I would like the user to be able to type a letter and have the drop down skip to that selection.  I have seen this implemented two ways, one where it bascially captures the keyboard input in a text box in the combo box and selects based on what the user has typed.  This allows the user to wait and type more text that gets add to the criteria.  The other is where the keyboard input doesn't appear to get captured anywhere, if yo type a letter, wait a couple seconds and type another letter it takes you to the selection starting with the second letter you typed.  If you want to type multiple letters of the search criteria you have to type them quickly together.
I'd be happy with either approach.  They can only select an item though that is in the list, so I don't really like the idea of putting an edit control on the combo box where they can type in whatever they want.  I could do this and than validate their input, but would rather force them to select something that is in the list.
In this case it is a list of system colors, which is over 140 of them, so having a way to quickly get around the list is what I need.
Here is my data template that I am using.
    <DataTemplate x:Key="ColorSelectionComboBox" DataType="ComboBox">
        <StackPanel Orientation="Horizontal">
            <Rectangle Width="16" Height="16" Margin="0,2,4,2">
                <Rectangle.Fill>
                    <SolidColorBrush Color="{Binding Color}"/>
                </Rectangle.Fill>
            </Rectangle>
            <TextBlock Text="{Binding Name}"/>
        </StackPanel>
    </DataTemplate>

Any ideas are appreciated.

A: ComboBox has built-in support for incremental search using the keyboard. I haven't actually used it (so I'm no good for help with advanced troubleshooting) but I know it's there.
It looks like you need to set the ComboBox's IsTextSearchEnabled property to true, and then set the TextSearch.TextPath attached property to the binding path of the text you want to search on (probably "Name" to correspond with your TextBlock text).


text:
Q: 1980's Transistor ID & Silkscreen (German Automotive) From the circuit board of a 1985 Volkswagen engine control unit...
I can't find the device itself based on the markings. Does the silkscreen help?

A: Hmmm, actually it looks like this must be it:
http://www.datasheetspdf.com/PDF/BCX58/127619/1
Based on that datasheet, the silkscreen is indicating E - B - C (left to right).
Is that marking still in use today?


text:
Q: Firebase authentication only converts Facebook and Email auth to Google auth, But Not vice versa I knew it is raised already, but i want to clear and sum it up.
I use FireBase authentication to allow the following Sign Up:

*

*Facebook

*Google

*Email

When signed up with Email, but later decide you want to change credential to Facebook (Having the same email) You receive an error. Same issue from Google to Facebook.
The Error:

An account already exists with the same email address but different
  sign-in credentials. Sign in using a provider associated with this
  email address.

However, if you Logged with Facebook or Email you CAN change your credential to Google.
Theoretically you can allow multiple accounts with the same email:

However, it means (from what i understood) Firebase auth will generate a unique UserID for each additional credential which means that if you use UserID to track data of user (messages, score, etc..) you need somehow track all UserIDs from all credentials. This can ruin one of Firebase authentication purposes.
If you decide to go this way, you will need to link the accounts using LinkWithCredentialAsync. As i understood this can be ONLY be done if you are LOGGED IN with your other credential.
I rising this because i was disappointed to discover this only after implementing Firebase.
The solution from this thread Stackoverflow thread is creative (see pupadupa scheme), but i do not want to go this way.
If someone can add on to this and found some sort of solution, please post it.


text:
Q: PayPal Rest API - Sandbox Recurring Subscription Webhook Notifications I am implementing recurring subscriptions using the Paypal Rest API. In Sandbox mode, I subscribed to all Webhook events, with the the target in mind that I will receive notifications such as when the plan and agreement are created, as well as when the recurring billing takes place. Whilst I am receiving the notifications for the plan and agreement, I am not receiving any notifications for the daily billing that is supposed to take place. The 'payment_definitions' section of the: Billing Plan created notification can be seen below. It clearly states that the frequency is: Day and frequency_interval is 1.
"payment_definitions": [
{
    "name": "Standard Plan",
     "type": "REGULAR",
     "frequency": "Day",
     "frequency_interval": "1",
     "amount": {
         "currency": "EUR",
         "value": "40"
     },
     "cycles": "11",
     "charge_models": [],
     "id": "PD-01A711327R015545F37WM7QI"
}
],

I was under the impression that a notification such PAYMENT.SALE.COMPLETED can and should be used in the Webhook listener to extend the user's subscription on a monthly basis (I am using 'DAY' frequency just for testing purposes, for the time being).
Is this the way it should work? Perhaps, there should be no Webhook notification when the scheduled billing takes place? Perhaps such a model is what should be used: a yearly subscription is given, and if no cancelled notification takes place it is simply left to run out its course?
Or does it just not work in Sandbox, perhaps? Note than in the Webhook logs within the PayPal developer, the only notifications present are related to Billing Plan Created and Billing Subscription Created. There are several instances done on the 17th and 19th April, so there should have been at least 4 notifications of daily billing ever since.