text:
Q: Recommendation of OCR software to face this recognition case I have to recognise text in a picture like this:
Image to recognise
I have tried Tesseract, but I am not very happy with the results.
Could you recommend me any software that could be more accurate in "text recognition on image" instead of "text recognition on document"?
Thanks in advance

A: Don't expect the Tesseract to work out of the box. This image needs some work before it is put to Tesseract.
I would do following preprocessing:

*

*blur the image to remove some of the digital noise

*adaptive thresholding with suitable parameters

*correct image
colors to provide white background and black text

*

*this should be easy operations just invert the colors if necessary

*run Tesseract with correct language files (italian, I guess?)

These preprocessing steps are really easy to program by hand, but of course there is plenty of libs with this capabilities.
As a starting point see this: Preprocessing image for Tesseract OCR with OpenCV

A: I don't know of any ready made software that would do text extraction on your specific image without a lot of additional configurations, but you can probably improve your Tesseract results
You can try to treat the image so it's easier for Tesseract to recognize it, use tessedit_write_images true to see your image after Tesseract does it's automatic adjustments
It probably isn't the best so you can do the adjustments yourself with the many libraries/programs available, your goal should be to transform it to a black on white text image, with as little noise as possible
For this read: ImproveQuality
You can also try to train Tesseract for your specific data, but this will require a lot more work, and large amounts of training data, read: TrainingTesseract 4.0


text:
Q: Simple Prolog setof this is simple yet cannot seem to grasp it
I have these "colors"
color(blue).
color(red).
color(white).

using setof I need to get all possible combinations of these colors in a list
It would be great if you can provide a brief explanation. I tried this query
setof(X,color(X),Colors). which failed obviously
Thanks

A: I suppose you meant this with combinations:
?- setof((X,Y), (color(X), color(Y)), ColorsCombined).
ColorsCombined = [ (blue, blue), (blue, green), (blue, red), (green, blue), (green, green), (green, red), (red, blue), (red, green), (..., ...)].

Or did you mean the superset?
subset([Element|Set], [Element|Subset]):- subset(Set, Subset).
subset([_|Set], Subset):- subset(Set, Subset).
subset([], []).

superset(Set, Superset) :- setof(Subset, subset(Set, Subset), Superset).

This is the output:
 ?- superset([1,2,3], Superset).
Superset = [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]].

A: You mean like this ?
all_permutations(Permutations) :-

    % get all colors into a list
    setof(Color, color(Color), One_Color_List),

    % find all combinations using permutation/2 on One_Color_List
    setof(Permutation,
       permutation(One_Color_List, Permutation),
       Permutations).

Results:
?- all_permutations(X).
X = [[blue, red, white], [blue, white, red], [red, blue, white], [red, white, blue], [white, blue, red], [white, red, blue]].

The trick is to get the facts into a list - as you did, then use permutation/2 to generate all permutations of that list.
If that's what you wanted.. wasn't clear...

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I delete particular NSString from NSMutableArray Help me to sort-out my problem, I've been stuck over here.
I've also seen many questions similar to this, with same problem. But none-of them solved my problem. That's why I need to ask similar question on Stack.
I've NSMutableArray i.e NSMutableArray *arrNames = [[NSMutableArray alloc] initWithObjects:@"ABC", @"DEF", @"GHI", nil];
Now I want to delete GHI from this array. So I've tried this way, but it doesn't
 work-out. Please help me.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSMutableArray *arrDeletedGTINS = [[NSMutableArray alloc] init];
        arrDeletedGTINS = [userDefaults objectForKey:@"deletedArr"];

NSLog(@"%@", arrDeletedGTINS); will give this output ->

(
        00000000000017
    )
    if ([arrDeletedGTINS containsObject:@"00000000000017"]) {
        [arrDeletedGTINS removeObject:@"00000000000017"];
    }

    [userDefaults setObject:arrDeletedGTINS forKey:@"deletedArr"];
    [userDefaults synchronize];

If I'm going some-where wrong then please correct me. I'm learning iOS.
Please help me.

A: Try this.
You can use containsObject method in an NSMutableArray
if ([arrNames containsObject:@"GHI"]) {
    [arrNames removeObject:@"GHI"];
}

A: This line is your issue :
arrDeletedGTINS = [userDefaults objectForKey:@"deletedArr"];

NSUserDefault saves array as NSArray, not as NSMutableArray.
So replace the above line by :
arrDeletedGTINS = [[userDefaults objectForKey:@"deletedArr"] mutableCopy];


text:
Q: How to know when a user was last active? Trying to build an auto-logout feature, and have got a timer going but looking for a way to start/restart the timer based on user's last active time.
The scenario is that the user has been away from their keyboard for X amount of time, and we want to log them out.
Adding the code I've come up with since then:
// main.js
import React from 'react'
import { Admin } from 'react-admin'
import authProvider from '../../auth-provider'
import restClient from '../../rest-client'
import buildResources from './build-resources'
import { setLastActive } from './last-active'

const customReducers = {
  lastActive,
}

function lastActive() {
  const now = Date.now()
  setLastActive(now)

  return now
}

export const Main = () => (
  <Admin
    authProvider={authProvider}
    dataProvider={restClient}
    customReducers={customReducers}
  >
    {buildResources}
  </Admin>
)

// last-active.js
let lastActive

export const setLastActive = (timestamp = Date.now()) =>
  (lastActive = timestamp)

export const getLastActive = () => lastActive || null

It's not all the code, but enough to show the gist. I can know use the redux store, or the singleton to grab when they were last active. It's a bit flawed since most, not all actions go through the redux store.

A:
react-admin works well with API-structured Apps.

Based on that fact, am assuming your App consumes endpoints (a lot!!).
Here's a possible process to auto-logout a user.

*

*Set the token in authProvider.login method

*Within your authprovider.checkError method, use setTimeout method to clear the token. This timeout can be based on last CRUD method executed.

*Once the token is cleared, react-admin redirects the user to logout.Thus requiring the user to re-login.


text:
Q: How can I add files to rebol3 startup (in the compiled executable)? In os/host-main.c there's this line
 n = RL_Start((REBYTE *)(&Reb_Init_Code[0]), REB_INIT_SIZE, 0); // TRUE on halt

in include/host-init.h I found
const unsigned char Reb_Init_Code[REB_INIT_SIZE] = {
    "\x78\x9C\xD5\x1A\x59\x73\xDB\xC6\xB9\xCF\xFB\x2B\x56\xF0\x74\x2C"
... }

and then, there's tools/make-host-init.r which creates include/host-init.h and boot/host-init.r
I have added a file to the files list in make-host-init.r which just sets a word to a string, and prints the string. Then I have
make clean
make

but in the newly created r3 executable this seems not to be present (though I've seen that the files have been altered).
Is there anything else I need to do?

A: Two things:
If you are modifying the Rebol code, you need to run make prep as well because that runs all the Rebol scripts.
If you are adding a file, you probably need to add it to os/tools/file-base.r (and since it is a rebol file, run make prep afterwards.
You probably also want to remake the make file for you machine (make make OS_ID=X.X.X)


text:
Q: Exercises to see if certain series converge.
*

*Does the series $\sum \frac{2^k+1}{3^k}$ converge?

*Does the series $\sum (-1)^k\frac{1}{k^2}$ converge?

*Does the series $\sum \frac{2^k+2^{2k}}{4^k}$ converge?

*Does the series $\sum \frac{k!}{(2k)!}$ converge?

For the first question, do we use the comparison test comparing it to $\left(\frac{2}{3}\right)^k$???
For the second question, this series does converge. To prove this observe that this converges absolutely because
\begin{equation*}
\sum_{k=1}^{\infty} \left|(-1)^k\frac{1}{k^2}\right| = \sum_{k=1}^{\infty} \frac{1}{k^2}
\end{equation*}
converges. To see that this does converge, we can use the integral test.
The function $f:[1,\infty) \mapsto \mathbb{R}$ defined by $f(x) := \frac{1}{x^2}$ is continuous, non-negative and decreasing by examining the derivative $f'(x) = -\frac{2}{x^3} < 0$ for all $x\geq 1$. So we have
\begin{equation*}
\begin{split}
\int_{1}^{\infty} \frac{1}{x^2} \; dx &= \left[-\frac{1}{x}\right]_{1}^{\infty} \\
&= \lim_{a\to\infty} \left(-\frac{1}{a}+1\right) \\
&= 1
\end{split}
\end{equation*}
This integral converges so by the integral test $\sum_{k=1}^{\infty} \frac{1}{k^2}$ converges as well and hence, $\sum_{k=1}^{\infty} (-1)^k\frac{1}{k^2}$ converges.
For the third question, this series does NOT converge. To show that this series diverges, we just need to show that
\begin{equation*}
\lim_{k\to\infty} \frac{2^k+2^{2k}}{4^k} \neq 0
\end{equation*}
or doesn't exist. Well, for $k\geq 0$,
\begin{equation*}
\frac{2^k+2^{2k}}{4^k} = \frac{2^k+4^k}{4^k} = \left(\frac{1}{2}\right)^k+1.
\end{equation*}
Thus,
\begin{equation*}
\begin{split}
\lim_{k\to\infty} \frac{2^k+2^{2k}}{4^k} &= \lim_{k\to\infty} \left(\frac{1}{2}\right)^k+1 \\
&= 0+1 \\
&= 1 \neq 0.
\end{split}
\end{equation*}
For the fourth question, if we let $a_k = \frac{k!}{(2k)!}$ then using the ratio test we get
\begin{equation*}
\begin{split}
\lim_{k\to\infty} \left|\frac{a_{k+1}}{a_k}\right| &= \lim_{k\to\infty} \left|\frac{\frac{(k+1)!}{(2k+1)!}}{\frac{k!}{(2k)!}}\right| \\
&= \lim_{k\to\infty} \left|\frac{(k+1)!}{(2k+1)!}\times \frac{(2k)!}{k!}\right| \\
&= \lim_{k\to\infty} \left|\frac{(k+1)\times k\times (k-1)\times\ldots\times (2k)\times (2k-1)\times (2k-2)\times\ldots}{(2k+1)\times 2k\times (2k-1)\times\ldots\times k\times (k-1)\times (k-2)\times\ldots}\right| \\
&= \lim_{k\to\infty} \frac{k+1}{2k+1} \\
&= \lim_{k\to\infty} \frac{1+\frac{1}{k}}{2+\frac{1}{k}} \\
&= \frac{1}{2} < 1.
\end{split}
\end{equation*}
Hence, $\sum_{k=0}^{\infty} \frac{k!}{(2k)!}$ converges.

A: As regards the last one, this is an alternative way: for $k\geq 1$,
$$\frac{k!}{(2k)!}=\frac{1}{(2k)\cdot(2k-1)\cdots (k+1)}\leq \frac{1}{(2)\cdot(2)\cdots (2)}=\frac{1}{2^k}$$
and therefore the non-negative series $\sum \frac{k!}{(2k)!}$ converges by the comparison test.
Your answers for 2) and 3) are correct. For the first one,
$$\frac{2^k+1}{3^k}\leq \frac{2^k+2^k}{3^k}=2\left(\frac{2}{3}\right)^k$$
and use the comparison test, or you may note that
$$\sum \frac{2^k+1}{3^k}=\sum \left(\frac{2}{3}\right)^k+\sum \frac{1}{3^k}$$
which are both convergent.

A: For 1) use the fact that $\sum (\frac 2 3)^{k}$ and $\sum \frac1 {3^{k}}$ both converge.
Your answer for 2) and 3) are OK.
In 4) $a_{k+1}$ is not $\frac {(k+1)!} {(2k+1)!}$. It is $\frac {(k+1)!} {(2k+2)!}$. [You have to replace $k$ by $k+1$ in the formula for $a_k$]. But your approach is good and you will be able to complete it after making this correction.


text:
Q: How to do a Merge with JDBCTemplate, SQL Server, and expected output My query looks like this
MERGE dbo.myTable AS myt
USING (SELECT ? AS ID,
       ? AS Value) AS s
ON (s.id = myt.id)
WHEN MATCHED THEN
    UPDATE SET myt.ApprovalUserId = s.ApprovalUserId
WHEN NOT MATCHED THEN
    INSERT ( Value )
    VALUES  ( s.Value)
OUTPUT INSERTED.id;

My java code looks like this
jdbcTemplate.queryForInt(SQL, id, value);

But when I try to run I get
java.sql.SQLException: The executeQuery method must return a result set.

I would like to somehow extract the ID given by the merge "INSERTED.id".  Is there a JDBCTemplate method that I should be looking at? Or should I abandon merge and just do this with selects, updates, and locks?
I'm using Sql Server 2012, Java 6, and Spring jdbc 3.1.2.release

A: The final solution for me was to extend the JdbcTemplate class "StoredProcedure" and to throw my merge statement into a stored procedure.  The execute command returned all of the stored procedure results.


text:
Q: Css transition opacity tag I´m having trouble with animating a dropdown menu with css. I need it to work with css3 and not jQuery or javascript. I've added all the rules neccessary but still the opacity tag inside my tranistion tag in my css appears like a normal word and is not marked like the other tags and so the effect dont works.

body {
  background-color: rgb(20, 20, 20);
  margin: 0px;
}

.menu {
  height: 100vh;
  display: flex;
  align-items: center;
}

.menu-item {
  color: aliceblue;
  font-size: clamp(2rem, 7vw, 7rem);
  font-family: 'Orbitron', sans-serif;
  display: block;
  text-decoration: none;
  padding: clamp(0.25rem, 0.5vw, 1rem) 0rem;
  transition: opacity 400ms ease;
}

.menu-items {
  margin-left: 100px;
  position: relative;
  z-index: 2;
}

.menu-items:hover>.menu-item {
  opacity: 0.3;
}

.menu-items:hover>.menu-item:hover {
  opacity: 1;
}

.menu-background-pattern {
  height: 100vh;
  width: 100vw;
  background-image: radial-gradient( rgba(2255, 255, 255, 0.1) 9%, transparent 9%);
  background-position: 0% 0%;
  background-size: 12vmin 12vmin;
  position: absolute;
  left: 0px;
  top: 0px;
  z-index: 1;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Rahim's Portfolio Page</title>
  <link rel="stylesheet" href="style.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@600&display=swap" rel="stylesheet">

      Projects
      Resume
      Testemony
      Kontakt


text:
Q: Bootstrap 3 data-toggle icon change I have this code so far:
http://jsfiddle.net/4z6j454q/
$(document).ready(function(){
    $('li').each(function() {
      $(this).on('shown', function () {
         $(this).children().attr("src", "http://test.cz.vs1056.server4u.cz/images/right.jpg");
      });

      $(this).on('hidden', function () {
         $(this).children().attr("src", "http://test.cz.vs1056.server4u.cz/images/down.jpg");;
      });
    });
  });

I'm trying to display the arrow down or right depending whether the
* is collapsed or not, disregarding the src in the html now.
I'm not sure why my jQuery wont work. I search for all
* tags, then deciding if they are shown or hidder then editing the src of the child  tag
thanks for suggestions

A: DEMO: MY FIDDLE
The reason your'e not getting results when clicking is because of the follwoing problems:

*

*there are no click events being binded to the LI. currently you are just loading the images when the page loads.

*Your'e not specifying which element is hidden or shown. By adding the .next() your'e telling the DOM to look to the next element in the LI list, and see if its hidden.
I would try this:
$(document).ready(function(){
    function checkOnLoad(elem){
        if(elem.next().css("display") === "none"){
            elem.find('img').attr("src", "http://test.cz.vs1056.server4u.cz/images/right.jpg");
        } else {
            elem.find('img').attr("src", "http://test.cz.vs1056.server4u.cz/images/down.jpg");
        }
    }

    function checkOnClick(li_clicked){
        var id = li_clicked.attr("data-target");
         $(id).on('hidden.bs.collapse', function () {
             li_clicked.children('img').attr("src", "http://test.cz.vs1056.server4u.cz/images/right.jpg");
        })

         $(id).on('shown.bs.collapse', function () {
           li_clicked.children('img').attr("src", "http://test.cz.vs1056.server4u.cz/images/down.jpg");
        })
    }

    $('li').each(function() {
        checkOnLoad($(this));
    });

    $('li').click(function() {
        checkOnClick($(this));
    });
});

A: You need to listen for bootstrap's shown.bs.collapse and hidden.bs.collapse events rather than just 'shown' and 'hidden'.
Try like this:
$(document).ready(function(){
    $('li').each(function() {
        var li = $(this);
        li.on('shown.bs.collapse', function () {
           li.children().attr("src", "http://test.cz.vs1056.server4u.cz/images/right.jpg");
        });

        li.on('hidden.bs.collapse', function () {
           li.children().attr("src", "http://test.cz.vs1056.server4u.cz/images/down.jpg");;
        });
    });
});

A: This works, not sure why though.
$(document).ready(function(){
    function checkCollapsed(elem){
      if(elem.next().css("display") === "none"){
           elem.children().attr("src", "http://test.cz.vs1056.server4u.cz/images/right.jpg");;
      } else {
           elem.children().attr("src", "http://test.cz.vs1056.server4u.cz/images/down.jpg");
      }
    }

    function checkCollapsed2(elem){
      if(elem.next().css("display") === "none"){
           elem.children().attr("src", "http://test.cz.vs1056.server4u.cz/images/down.jpg");;
      } else {
           elem.children().attr("src", "http://test.cz.vs1056.server4u.cz/images/right.jpg");
      }
    }

    $('li').each(function() {
          checkCollapsed($(this));
    });

    $('li').click(function() {
           checkCollapsed2($(this));
    });
});


text:
Q: Weakly continuous convolution semigroup This is an exercise (1.4.2) from Applebaum's Levy Processes and Stochstic Calculus.
I want to show that a convolution semigroup is weakly continuous if and only if
\begin{equation}
    \lim_{s\searrow t} \int_{\mathbb{R}^d} f(y) p_s(dy) = \int_{\mathbb{R}^d} f(y) p_t(dy),
\end{equation}
for all bounded and continuous $f$ ($f \in C_b(\mathbb{R}^d)$), for all $t\geq 0$.
Definition: A convolution semigroup is a family of probability measures on $\mathbb{R}^d$, $(p_t; t\geq 0)$ with $p_0 = \delta_0$ and $p_s *p_t = p_{s+t}$. It is weakly continuous if
\begin{equation}
\lim_{t\searrow 0} \int_{\mathbb{R}^d} f(y) p_t(dy) = f(0),
\end{equation}
for all $f \in C_b(\mathbb{R}^d)$.
My attempt:
The if statement is obvious, just take $t=0$. For the only if: assume $(p_t)$ is a weakly continuous convolution semigroup and let $f \in C_b(\mathbb{R}^d)$ and $t\geq 0$, then
\begin{align}
    \lim_{s\searrow t} \int_{\mathbb{R}^d} f(y) p_s(dy) &= \lim_{s\searrow t} \int_{\mathbb{R}^d} f(y) (p_{t} * p_{s-t})(dy) \\
    &= \lim_{s\searrow t} \int_{\mathbb{R}^d} \int_{\mathbb{R}^d} f(x+z) p_{t}(dx) p_{s-t}(dz) \\
    &= \lim_{u\searrow 0} \int_{\mathbb{R}^d} \int_{\mathbb{R}^d} f(x+z) p_{t}(dx) p_{u}(dz),
\end{align}
If I can show that the integrand of the outer integral, $g(z):=\int_{\mathbb{R}^d} f(x+z) p_{t}(dx)$ is in $C_b(\mathbb{R}^d)$, i.e. continuous and bounded w.r.t. $z$, then the result follows from definition of weakly continuous. Boundedness of $g$ is easy to show:
\begin{align}
    \lvert g(z)\rvert &\leq \int_{\mathbb{R}^d} \lvert f(x+z)\rvert p_{t}(dx) \\
    &\leq M,
\end{align}
where $M\geq 0$ is the bound on $f$, and we use the fact that $p_t$ is a probability measure. For continuiuty of $g$, let $\varepsilon > 0$. Let $B \subset \mathbb{R}^d$ be a bounded set with measure $p_t(B) \geq 1 - \frac{\varepsilon}{4M}$. By continuity of $f$ and boundedness of $B$, we can find $\delta > 0$ such that $\lvert f(z) - f(y) \rvert < \frac{\varepsilon}{2}$ for any $z, y \in B$ with $0 \leq \lVert z - y \rVert < \delta$. Then, for $z, y \in \mathbb{R}^d$ with $\lVert z - y \rVert < \delta$,
\begin{align}
    \lvert \int_{\mathbb{R}^d} f(x+z) p_{t}(dx) - \int_{\mathbb{R}^d} f(x+y) p_{t}(dx)\rvert &\leq \int_{\mathbb{R}^d} \lvert f(x+z) - f(x+y) \rvert p_{t}(dx) \\
    &= \int_{B} \lvert f(x+z) - f(x+y) \rvert p_{t}(dx) + \int_{B^c} \lvert f(x+z) - f(x+y) \rvert p_{t}(dx) \\
&\leq \frac{\varepsilon}{2} + 2M \cdot \frac{\varepsilon}{4M} \\
&= \varepsilon
\end{align}
Since we have established $g \in C_b(\mathbb{R}^d)$, then
\begin{align}
\lim_{s\searrow t} \int_{\mathbb{R}^d} f(y) p_s(dy) &=\lim_{u\searrow 0} \int_{\mathbb{R}^d} g(z) p_{u}(dz) \\
 &= g(0) \\
&= \int_{\mathbb{R}^d} f(x) p_t(dx).
\end{align}
which is the desired result.
Is my proof correct?


text:
Q: Three.js - SSAO defect transparent area I've been trying to add SSAO into my game, per this SSAO EXAMPLE
Unfortunately, my transparent trees now defected:

Please advise on how to fix it.

A: This is not a defect, during the depth-Path, which you need to pass to the SSAO shader further on, transparency is not taken into account, thus your leave-defining planes get detected as planar geometry and get the appropriate outline.
Concerning a solution, I cannot really help you. What you can do is hide all the transparent stuff before rendering the depth pass but then, the AO-pass gets multiplied over it, so you just trade in a visual problem against another one. To really solve this, i think you need an additional Three.MaskPass, see here:
Rendering multiple scenes, with only 1 using SSAO [Three.js]
Hope this helps.

A: You could pass the texture into the normal/depth fragment shader and discard any fragments with an alpha < 0.5


text:
Q: aws ec2 and Django ALLOWED_HOSTS I have put in place my website using Django, on aws EC2, using Elastic Beanstalk. I have set the ALLOWED_HOSTS to ['www.mydomain.fr', '.mydomain.fr'], as recommanded on the Django website.
But I received a lot of alerts like :
Invalid HTTP_HOST header: 'ip-xxx-xx-xx-xxx.eu-west-1.compute.internal'. You may need to add u'ip-xxx-xx-xx-xxx.eu-west-1.compute.internal' to ALLOWED_HOSTS.
where ip-xxx-xx-xx-xxx.eu-west-1.compute.internal is my Private DNS?
Is it safe to add it to the ALLOWED_HOSTS, or could it lead to a security leak?
Thanks a lot

A: Yes, it's okay. But if you terminate the instance, you'll lose that address. So: you should endeavor to find a more flexible / dynamic way of addressing ALLOWED_HOSTS. You might want to try to set your instance's address as an environment variable.
Or, a less dynamic solution: you might also want to check into using an AWS Elastic IP. Although, this may not possible in a private subnet within a Virtual Private Cloud--although it doesn't sound like that's the case in your set-up.
Here's another option to explore...albeit you'll have to do some research as to whether or not this is secure. See how to fetch an instance's meta data from an AWS IP at this AWS page...
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html
And then leverage the AWS resource suggested above in your Django settings file like so...

# DJANGO PRODUCTION SETTINGS

import requests
from .base import *

########## ALLOWED_HOSTS
from requests.exceptions import ConnectionError

url = "http://169.254.169.254/latest/meta-data/public-ipv4"
try:
    r = requests.get(url)
    instance_ip = r.text
    ALLOWED_HOSTS += [instance_ip]
except ConnectionError:
    error_msg = "You can only run production settings on an AWS EC2 instance"
    raise ImproperlyConfigured(error_msg)
########## END ALLOWED_HOSTS

A: can u tell why ec2 is sending a request to django server . I have seen many answers to fix the ALLOWED_HOSTs issue but not understanding why is it coming or why ec2 ip is hitting it


text:
Q: ansible network parser for snow port-channel summary , NXOS command There are network parsers written by Ansible to process show command output properly.  Some of them they created are at
https://github.com/network-automation/ansible-network-parsers
I am looking for network-parser for the command and output like this. Let me know if you someone good at these can help. We need output with list of ports as written in the above GitHub commands. Thanks for your help. I tried few things. Getting lot of yaml errors.
sffc07ssw01# show port-channel summary

Flags:  D - Down        P - Up in port-channel (members)
        I - Individual  H - Hot-standby (LACP only)
        s - Suspended   r - Module-removed
        S - Switched    R - Routed
        U - Up (port-channel)
        M - Not in use. Min-links not met
--------------------------------------------------------------------------------
Group Port-       Type     Protocol  Member Ports
      Channel
--------------------------------------------------------------------------------
10    Po10(SD)    Eth      NONE      --
11    Po11(SU)    Eth      LACP      Eth1/1(P)    Eth1/2(P)
12    Po12(SU)    Eth      LACP      Eth1/3(P)    Eth1/4(P)
100   Po100(SD)   Eth      NONE      --
121   Po121(SD)   Eth      NONE      --
122   Po122(SD)   Eth      NONE      --
123   Po123(SD)   Eth      NONE      --
125   Po125(SD)   Eth      NONE      --

A: Ok, we don't have to write network parser for this. Someone can explain how network parser work, I would like to learn.
For nxos, When we use transport as cli, we receive the output above. But if we use transport as network_cli, then output will be already in dictionary format.
ok: [xyz.com] => {
    "pc_output": {
        "changed": false,
        "failed": false,
        "stdout": [
            {
                "TABLE_channel": {
                    "ROW_channel": [
                        {
                            "group": 10,
                            "layer": "S",
                            "port-channel": "port-channel10",
                            "prtcl": "NONE",
                            "status": "D",
                            "type": "Eth"
                        },
                        {
                            "TABLE_member": {
                                "ROW_member": [
                                    {
                                        "port": "Ethernet1/1",
                                        "port-status": "P"
                                    },
                                    {
                                        "port": "Ethernet1/2",
                                        "port-status": "P"

This is the way I processed it
```yml
item looks like this

interface_port_channel:
 - { interface: Ethernet 2/1, channel_group: 122, mode: active }
 - { interface: Ethernet 2/2, channel_group: 122, mode: active }

---
- name: Interface portchannel info
  debug: msg="args {{item}} "

- name: configure lacp trunk with the given interfaces
  nxos_config:
    lines:
      - conf t
      - interface {{item.interface}}
      - channel-group {{item.channel_group}} mode {{item.mode}}
      - exit
    provider: "{{ nxos_provider}}"

- name: "Get Port-channel summary"
  nxos_command: commands="show port-channel summary" provider="{{nxos_provider_network_cli}}"
  register: pc_output

- name: "Printing the port channel output"
  debug: var=pc_output

- set_fact: channel_group_info="{{run_pc}}"
  with_items: "{{pc_output.stdout[0].TABLE_channel.ROW_channel}}"
  when: item.channel_group == run_pc.group
  loop_control:
      loop_var: run_pc

- debug: var=channel_group_info

- assert:
    that:
        - channel_group_info is defined
        - channel_group_info.layer == 'S'
        - channel_group_info.status == 'U'
        - channel_group_info.prtcl == "LACP"
    success_msg: "Port is switched"
    fail_msg: "Please check channel_group_info above to make sure Status, protocol and type is correct"

- set_fact: ports_info="{{item}}"
  with_items: "{{channel_group_info.TABLE_member.ROW_member}}"
  when: item.port == ''.join(item.interface.split())

- debug: var=ports_info["port-status"]

- assert:
    that:
      - ports_info is defined
      - ports_info["port-status"] == 'P'


text:
Q: JSF error (java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config I am studying jsf tutorial.  But I can't run first page unfortunetly. I get this error. Although I added jstl dependency to my pom.xml , I get this error. I create maven project in eclipse.
java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config
    com.sun.faces.application.view.JspViewHandlingStrategy.executePageToBuildView(JspViewHandlingStrategy.java:344)
    com.sun.faces.application.view.JspViewHandlingStrategy.buildView(JspViewHandlingStrategy.java:153)
    com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:99)
    com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Also my pom.xml is
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>STUDY</groupId>
    <artifactId>jsf</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>jsf Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.faces</artifactId>
            <version>2.3.0-m03</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>jsf</finalName>
    </build>
</project>


text:
Q: Issue when trying to install "pytest-allure-adaptor" in PyCharm I am trying to generate XML allure reports through PyCharm on my pytest project. I have installed allure-pytest and required packages for the test cases to run. However when I try to install pytest-allure-adaptor from File -> Settings -> Project Interpreter I get the error as follows :
"error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/"
I have installed Visual C++ Redistributable for Visual Studio 2015 but it doesn't help. Please help me with a solution.
When I use pytest command to run my project I get the below error after install adaptor via pip install pytest-allure-adaptor :
Traceback (most recent call last):
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\geeth\AppData\Local\Programs\Python\Python38\Scripts\pytest.exe\__main__.py", line 9, in <module>
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\_pytest\config\__init__.py", line 105, in main
    config = _prepareconfig(args, plugins)
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\_pytest\config\__init__.py", line 257, in _prepareconfig
    return pluginmanager.hook.pytest_cmdline_parse(
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\pluggy\hooks.py", line 286, in __call__
    return self._hookexec(self, self.get_hookimpls(), kwargs)
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\pluggy\manager.py", line 93, in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\pluggy\manager.py", line 84, in <lambda>
    self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall(
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\pluggy\callers.py", line 203, in _multicall
    gen.send(outcome)
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\_pytest\helpconfig.py", line 90, in pytest_cmdline_parse
    config = outcome.get_result()
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\pluggy\callers.py", line 80, in get_result
    raise ex[1].with_traceback(ex[2])
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\pluggy\callers.py", line 187, in _multicall
    res = hook_impl.function(*args)
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\_pytest\config\__init__.py", line 836, in pytest_cmdline_parse
    self.parse(args)
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\_pytest\config\__init__.py", line 1044, in parse
    self._preparse(args, addopts=addopts)
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\_pytest\config\__init__.py", line 992, in _preparse
    self.pluginmanager.load_setuptools_entrypoints("pytest11")
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\pluggy\manager.py", line 299, in load_setuptools_entrypoints
    plugin = ep.load()
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\importlib\metadata.py", line 77, in load
    module = import_module(match.group('module'))
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\_pytest\assertion\rewrite.py", line 152, in exec_module
    exec(co, module.__dict__)
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\allure_pytest\plugin.py", line 3, in <module>
    import allure
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\_pytest\assertion\rewrite.py", line 152, in exec_module
    exec(co, module.__dict__)
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\allure\__init__.py", line 1, in <module>
    from allure.pytest_plugin import MASTER_HELPER
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\_pytest\assertion\rewrite.py", line 152, in exec_module
    exec(co, module.__dict__)
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\allure\pytest_plugin.py", line 9, in <module>
    from allure.common import AllureImpl, StepContext
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\_pytest\assertion\rewrite.py", line 152, in exec_module
    exec(co, module.__dict__)
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\allure\common.py", line 19, in <module>
    from allure.structure import Attach, TestStep, TestCase, TestSuite, Failure, Environment, EnvParameter
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\_pytest\assertion\rewrite.py", line 152, in exec_module
    exec(co, module.__dict__)
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\allure\structure.py", line 14, in <module>
    class Attach(xmlfied('attachment',
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\allure\rules.py", line 116, in xmlfied
    class MyImpl(namedlist('XMLFied', [(item[0], None) for item in items])):
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\namedlist.py", line 381, in namedlist
    type_dict = {'__init__': _make_fn('__init__', _nl_init, fields, defaults),
  File "c:\users\geeth\appdata\local\programs\python\python38\lib\site-packages\namedlist.py", line 180, in _make_fn
    code = compile(module_node, '<string>', 'exec')
TypeError: required field "posonlyargs" missing from arguments


text:
Q: removing number from notification icon I have a notification icon that has the number of notifications as below. I'm trying to remove the number upon clicking on the icon.

            Notifications {{count(auth()->user()->notifics)}}

Which is the easiest way to do it, Jquery, or there is an easier way in HTML ?

A: you can remove the span on click.

$(".glyphicon").on("click",function(){ $(".badge").remove(); });

Click on ICON below to remove the number

            (ICON) Notifications 10

A: I would create a JS that had an EventListener for every time you click the button, the number resets to 0.
Something similar to this:
var el = document.querySelector('.notification');

document.querySelector('button').addEventListener('click', function(){
    var count = Number(el.getAttribute('data-count')) || 0;
    el.setAttribute('data-count', count);
    el.classList.remove('notify');
    el.offsetWidth = el.offsetWidth;
    el.classList.add('notify');
    if(count === 0){
        el.classList.add('show-count');
    }
}, false);

A: Add an onclick in the link:

Then create a JS function that removes that number:
function removeNumber() {
  document.getElementsByClassName('badge')[0].innerHTML = '';
}

Or if you want to hide the full badge
function removeNumber() {
  document.getElementsByClassName('badge')[0].style.display = 'none';
}

I would suggest to avoid using JQuery for that kind of things which can be achieved easily with JS.


text:
Q: Kentico Page Wizard issues I am using the Kentico Page Wizard Manager to guide users through a particular page flow. All of my pages use the Portal Engine, and are configured to use the page nesting setting Use page template settings (All ancestor pages).  The ancestor pages do have Page Placeholder web parts in them, and are working correctly.
I have my page hierarchy set up like this:
A
   B
   C
   D
   E
F

Where B:E are underneath A, and F is the next sibling of A.
I have my Page Wizard Manager configured as the sole content web part on page A, and I have it Restrict step order set to Checked and Final step URL set to page F.  In the Navigation tab of A, I have it set to Redirect to first child.
I am having two issues:

*

*On pages B:E, I have Page Wizard Button parts to move users from one page to the next.  However, when visiting the pages, the buttons never show up to users.

*Page B is a login/register page. I am using a Logon mini form web part, and a Registration Form web part on this page.  I also added a Page wizard step action to skip this page if the current user is already authenticated.  This skip functionality doesn't ever seem to trigger, however the Logon mini form does correctly disappear when the user is logged in.  My step action settings are: Enabled=Checked, Action Type=Skip, Validate Step=Checked, Action Condition={% CurrentUser.IsAuthenticated #%}.

I've been referencing the documentation, and as far as I can tell, I am using all of these components correctly.
Any ideas on what could be causing these issues? It seems like none of the Page Wizard functionality is working at all.

A: If your buttons are on page A, they need to be moved to each step page i.e.: B, C, D, E, etc.
On your Page Wizard Step Action, uncheck the validation step box and set your condition to:
{% MembershipContext.AuthenticatedUser.IsAuthenticated %}
Also, make sure your Page Wizard Step Action web part is the last one on the page.
 This should resolve your issues.

A: Turned out to be a Page Template issue. All of my pages were using an ad-hoc instance of a common page template. This common page template was set to use a shared layout.
When I created a new Page Template specifically for this page that does not use a shared layout, all the Page Wizard functionality started working.


text:
Q: cannot implicitly convert type System.Collections.Generic.List I am trying to create a list of customer names that is fetched from a Json call but I get an error:

cannot implicitly convert type System.Collections.Generic.List<char>
  to System.Collections.Generic.List<string>

I am using these 2 classes:
Customers:
namespace eko_app
{
    static class Customers
    {
        public static List<CustomerResponse> GetCustomers(string customerURL)
        {
            List<CustomerResponse> customers = new List<CustomerResponse>();

            try
            {
                var w = new WebClient();
                var jsonData = string.Empty;

                // make the select products call
                jsonData = w.DownloadString(customerURL);

                if (!string.IsNullOrEmpty(jsonData))
                {
                    // deserialize the json to c# .net
                    var response = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonData);

                    if (response != null)
                    {
                        customers = response.response;
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return customers;
        }

        public class BusinessAssociate
        {
            public string business_associate_id { get; set; }
            public string created_by { get; set; }
            public DateTime created { get; set; }
            public DateTime modified { get; set; }
            public bool? deleted { get; set; }
            public string business_id { get; set; }
            public string identity_id { get; set; }
            public string associate_type { get; set; }
            public string name { get; set; }
        }

        public class Identity
        {
            public string identity_id { get; set; }
            public string created_by { get; set; }
            public DateTime created { get; set; }
            public DateTime modified { get; set; }
            public bool? deleted { get; set; }
            public string name { get; set; }
            public object identity_type { get; set; }
        }

        public class ChartOfAccount
        {
            public string chart_of_accounts_id { get; set; }
            public DateTime created { get; set; }
            public DateTime modified { get; set; }
            public string created_by { get; set; }
            public string deleted { get; set; }
            public string account_id { get; set; }
            public string account_name { get; set; }
            public string business_id { get; set; }
            public string account_category { get; set; }
            public string accounts_groups_id { get; set; }
            public string cash_equivalent { get; set; }
            public string acc_category { get; set; }
            public decimal? balance { get; set; }
            public decimal? credit_balance { get; set; }
            public decimal? debit_balance { get; set; }
            public decimal? absolute_balance { get; set; }
            public string balance_type { get; set; }
            public decimal? raw_balance { get; set; }
            public string extended_name { get; set; }
            public string normal_balance_type { get; set; }
        }

        public class CustomerResponse
        {
            public BusinessAssociate BusinessAssociate { get; set; }
            public Identity Identity { get; set; }
            public ChartOfAccount ChartOfAccount { get; set; }
        }

        public class Messages
        {
            public string msgs { get; set; }
            public string errs { get; set; }
        }

        public class RootObject
        {
            public List<CustomerResponse> response { get; set; }
            public Messages messages { get; set; }
        }
    }
}

HomeForm:
 private void GetCustomerNameList()
        {
            // get customers
            customerURL = "https://eko-app.com/BusinessAssociate/list_associates/1/sessionId:" + sessionID + ".json";

            var customers = Customers.GetCustomers(customerURL);

            List<string> customerNames = new List<string>();

            foreach (var c in customers)
            {
                customerNames = c.BusinessAssociate.name.ToList(); <--------error thrown here
            }
        }

The error is thrown at customerNames = c.BusinessAssociate.name.ToList(); on the HomeForm.
What am I doing wrong in creating a list of customer names?

A: I think you wanted to add all Customer.BusinessAssociate names to list:
foreach (var c in customers)
{
    customerNames.Add(c.BusinessAssociate.name);
}

What you originally written converted each name string to char list.

A: You're assigning a list of chars (string) into a list of strings.
Try something like this outside of the foreach loop:
customerNames = customers.Select(x => x.BusinessAssociate.name).ToList();

This also makes the initialization of cutomerNames redundant.

A: Instead of foreach use:
customerNames = customers.Select(c => c.BusinessAssociate.name).ToList();


text:
Q: Number of critical points of the sum of a function and a linear function I have a question. Let $f(x)$ be a function from $\mathbb{R}^n \to \mathbb{R}$, with $M$ critical points $(x^{(1)}, \dots, x^{(M)})$ that solve $\nabla f (x) = 0$. We now sum to $f$ a linear function (geometrically, an hyperplane) $h(x) = \sum_i k_i x_i$, and we call the sum $g(x) = f(x) + h(x)$.
Can we say something about the critical points of $g(x)$ in terms of the critical points of $f(x)$? My guess is that $g(x)$ still has $M$ critical points $\forall \,(f(x), h(x))$, but I could not find a simple proof or a simple counter example. Of course, the positions of the critical points is affected by $h(x)$.
EDIT: Now I understand that my guess is not true for general $f$. It seems that the provided counterexamples are based on one of these $2$ ingredients:

*

*The expansion of $f$ around a critical point has no $2^{nd}$ order term;

*The gradient of $f$ cannot take arbitrary values.

Is it possible to find a counterexample that does not rely on these $2$ ingredients? Maybe my guess is true for a limited class of $f$s
EDIT 2: As pointed out in one of the comments, the function $f(x) = x^3 + \epsilon x$ does not have a high order critical point for $\epsilon \neq 0$, but still when you add a linear function $h$ the number of its critical points can change.
The question now is: is there a class of $f$s for which my guess is true?
For example, let's say we consider functions that are a sum of a convex function and a quadratic form, and then we add $h(x)$: is the number of critical points of $f$ and $g$ always the same in this case?

A: Consider this example: $f(x,y) = \frac 13(x^3+y^3)$, $h(x,y)=x-y$. Although $f(x,y)$ has one critical point, $g(x,y)=f(x,y)+h(x,y)$ does not have critical points.

A: The number of critical points of $g$ can be less than, equal to, or larger than the number of critical points of $f$.
Example in one dimension: $f(x) = x^3$ has exactly one critical point. $g(x) = x^3+ ax$ has no critical points if $a> 0$, one critical point if $a=0$, and two critical points if $a< 0$.
Another example: $f(x) = \sin(x)$ has infinitely many critical points, but $f(x) +2x$ has no critical points at all.


text:
Q: Decorations using \draw inside axis environment I'm trying to draw vectors normal to curved surface using pgfplots. Here's my MWE and result:
\documentclass[tikz,margin=5pt]{standalone}

\usetikzlibrary{decorations.markings}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\tikzset{test/.style={
    postaction={decorate},
    decoration={
        markings,
        mark=between positions 0.0 and 0.1 step 0.01
        with { \draw[-latex] (0,0) -- (0,-5); }
        }
    }
}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
    xmin=0, ymin=0, xmax=50, ymax=50,
    unit vector ratio*=1 1 1]
\addplot[smooth cycle, test] coordinates {
    (0.0, 0.0)
    (20.0, 15.0)
    (40.0, 30.0)
    (0.0, 40.0)};
\end{axis};

\end{tikzpicture}

\end{document}

If I however change axis limits, for example setting
\begin{axis}[
    xmin=-20, ymin=0, xmax=50, ymax=50,
    unit vector ratio*=1 1 1]

I get the following output:

I also get similar behavior by setting some data coordinates to negative values, for example
\addplot[smooth cycle, test] coordinates {
    (0.0, 0.0)
    (20.0, 15.0)
    (40.0, 30.0)
    (-20.0, 40.0)};

The question is how to properly use \draw to decorate inside pgfplots axis environment?

A: The coordinates in the decoration settings need a relative coordinate system, axis direction cs (or rel axis cs). The default coordinate system are absolute coordinates with  axis cs.
\draw[-latex] (axis direction cs:0,0) -- (axis direction cs:0,-5);

Full example:
\documentclass[tikz,margin=5pt]{standalone}

\usetikzlibrary{decorations.markings}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\tikzset{test/.style={
    postaction={decorate},
    decoration={
        markings,
        mark=between positions 0.0 and 0.1 step 0.01
        with {
          \draw[-latex] (axis direction cs:0,0) -- (axis direction cs:0,-5);
        }
    }
}}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
    xmin=-20, ymin=-5, xmax=50, ymax=50,
    % xmin=0, ymin=0, xmax=50, ymax=50,
    unit vector ratio*=1 1 1]
\addplot[smooth cycle, test] coordinates {
    (0.0, 0.0)
    (20.0, 15.0)
    (40.0, 30.0)
    (0.0, 40.0)};
\end{axis};

\end{tikzpicture}
\end{document}


text:
Q: При запросе к MSSQL выдает ошибку Я начинающий программист.
При выполнении command2.ExecuteNonQuery(); падает в ошибку:

Activated  Event   Time    Duration    Thread
  Exception: Exception thrown: 'System.InvalidOperationException' in System.Data.dll ("Существует >назначенный этой команде Command открытый DataReader, который требуется предварительно закрыть.").

try
{
    using (SqlCommand com = new SqlCommand($"select name from Table ", sqlcon))
    {
        com.CommandTimeout = 60;
        using (SqlDataReader sqlReader = com.ExecuteReader())
        {
            while (sqlReader.Read())
            {
                tblInfo2.NAME = (sqlReader[1]).ToString();
                tblInfo2.RO2 = ((int)sqlReader[0]).ToString();

                if (current_table == tblInfo2.NAME || Local_RO != tblInfo2.RO2)
                {

                        SqlCommand command2 = new SqlCommand(zapro, sqlcon);
                        SqlParameter tblParam = new SqlParameter("@id_table", tblInfo2.ID);
                        SqlParameter wroParam = new SqlParameter("@wro", Local_RO);
                        command2.Parameters.Add(tblParam);
                        command2.Parameters.Add(roParam);
                        command2.ExecuteNonQuery();

                }
                break;
            }
        }
    }
}
catch (Exception ex)
{

}

A: Скорее всего у Вас один и тот же sqlcon используется для нескольких ридеров. Создайте новый SqlConnection, например:
try
{
       using (SqlCommand com = new SqlCommand($"select name from Table ", conn))
       {
          ...
         using (SqlConnection conn = new SqlConnection("Ваша строка подключения"))
         {
            conn.Open();
            SqlCommand command2 = new SqlCommand(zapro, conn);
            ...
         }
       }
}
catch (Exception ex) { }


text:
Q: Python how to change colour of individual square of grid on mouse click How do I change the color of an individual square of the grid. This grid is drawn over an image. I calculated the center point of each square of the grid. When a user clicks on a specific square of the grid, I get the centroid of that square (already implemented). How can I change the color of the square of the grid. I have centroid of the clicked square in variable "closest_centroid".
# Get closes centroid
def closest_node(node, nodes):
    nodes = np.asarray(nodes)
    dist = np.sum((nodes - node)**2, axis=1)
    return np.argmin(dist)

# print co-ordinate function
def get_coords(event):

    mouse_xy = (event.x, event.y)
    closest_centroid = centers[closest_node(mouse_xy, centers)]
    print(closest_centroid)

My idea is to change the color of pixels of an image contained in the clicked square of the grid.
My libraries are:
import math
from Tkinter import *
from PIL import Image, ImageDraw
import numpy as np

A: You already did the hard work so you just need a simple function like the following:
def change_color(center):
    step = step_size/2
    center_x, center_y = center
    canvas.create_rectangle(
       [
            center_x - step,
            center_y - step,
            center_x + step,
            center_y + step
       ],
       fill='red'
    )

Rather than printing the centroid, you'd just call this function at that point.
John showed in his full code (removed in an edit) that canvas was already setup to draw the grid. To setup canvas John did:
filename = ImageTk.PhotoImage(img)
canvas = tk.Canvas(root,height=img.size[0],width=img.size[0])
canvas.image = filename
canvas.create_image(0,0,anchor='nw',image=filename)
canvas.pack()

Also he has step_size as:
step_size = int(img.width / step_count)

If the image isn't square, you'll need a step_size_x and a step_size_y


text:
Q: Read a file (with a sparse matrix) and generate CSR I need to read a square matrix that is in a .txt file and store it in the CSR format. I know how to read the matrix, but I haven't been able to come with an idea on how to make the CSR.
This is the code to read the matrix:
#include<stdio.h>
#include<string.h>
int main(){
  FILE *f;
  int i,j,n;
  float x;
  f=fopen("file.txt","r");
  if(f=NULL){
  printf(\n No file found \n");
  }
  fscanf(f,"%d",&n);
  for(i=0;i<n;i++){
     for(j=0;j<n;j++){
        fscan(f,"%f",&x);
        printf("\n element (%d,%d) = %f",i,j,x); //this is just to see that the matrix looks like I want it to be, it's not part of CSR problem
     }
  }
  return 0;
}

Any suggestions?

A: Let's interpret the CSR (or CRS, for "compressed row storage") structure as a structure of three arrays:
struct csr {
    size_t row_count;
    size_t *row_indices;
    float *values;
    size_t *column_indices;
};

Here, values and column_indices should point to arrays of the same size (alternatively, you could structure them as one array of int-double pairs), and row_indices should point to an array of indices into these two arrays. (Actually, we're going to take some liberties with row_indices; rather than pointing at the first column/value of a row, we're going to point one past the last column/value of the row.)
Your *.txt file format seems to contain a square matrix, and starts with a size parameter (n).
struct csr your_csr;
size_t n;

fscanf(f, "%d", &n);
your_csr.row_count = n;

After reading this n, we can allocate row_indices. Unfortunately, we don't know how many nonzero values there will be in the matrix. For now, this simple implementation will just allocate n x n elements, and a more conservative approach is left as an exercise to the reader.
your_csr.row_indices     = calloc(n, sizeof(your_csr.row_indices[0]));
your_csr.values          = calloc(n * n, sizeof(your_csr.values[0]));
your_csr.column_indices  = calloc(n * n, sizeof(your_csr.column_indices[0]));

Now that we have our memory in place, let's deal with the matrix data.
size_t pair_index = 0;

for (size_t row_index = 0; row_index < n; row_index++) {
    for (size_t column_index = 0; column_index < n; column_index++) {
        float value;
        fscanf(f, "%f", &value);

For every non-zero value you read, you're going to write what you know into your values and column_indices array
        if (value != 0.0) {
            your_csr.values[pair_index] = value;
            your_csr.column_indices[pair_index] = column_index;
            pair_index++;
        }
    }

After you've read a row, you're going to write down where the row ends.
    your_csr.row_indices[row_index] = pair_index;
}

Now, your_csr contains all the data you need to know about the matrix:

*

*your_csr.row_count contains the number of rows in the matrix.

*The length of the other two arrays is your_csr.row_indices[your_csr.row_count - 1].

*If you want to know in which column your_csr.values[x] belongs, look at your_csr.column_indices[x].

*The (non-zero) values of the first row (let's call it row 0; mathematicians would disagree, but zero-based indices are great for programming) can be found in your_csr.values[x], where 0 <= x && x < your_csr.row_indices[0].

*The values of any other row r can be found your_csr.values[x], where your_csr.values[r - 1] <= x && x < your_csr.row_indices[r].


text:
Q: Get current product id inside a function I have a custom plugin to generate pdf of my products. I am calling this function inside the plugin to get all the gallery images of a product.
 function print_gallery_pdf(){
    $product_id = 33910;
    $gallery_image;
    $link = array();
    $get_product = new WC_Product($product_id);
    $attachment_ids = $product->get_gallery_image_ids();
    foreach ($attachment_ids as $attachment_id){
        $gallery_image = wp_get_attachment_image($attachment_id, medium);
        array_push($link, $gallery_image);
    }
    return $link;
}

This function works perfectly when the id of the product is fixed, but whenever I try to get the ID dynamically is stops working. My dynamic function is:
function print_gallery_pdf(){
    global $product;
    $gallery_image;
    $link = array();
    $attachment_ids = $product->get_gallery_image_ids();
    foreach ($attachment_ids as $attachment_id){
        $gallery_image = wp_get_attachment_image($attachment_id, medium);
        array_push($link, $gallery_image);
    }
    return $link;
}

It should work because I have seen people using this function but it doesn't work for me and I am unable to identify the issue.

A: Shouldn't you pass the ID as an argument for the function?


text:
Q: Mixin question for ModelAdmin I'm overriding a ModelAdmin method thus:
def response_change(self, request, obj):
    # alter redirect location if 'source' is found in GET
    response = super(JobOptions, self).response_change(request, obj)
    source = request.GET.get('source', None)
    if source:
        response['location'] = source
    return response

Rather than repeat this on every model I'd like to make it a mixin.
If I do:
def RedirectMixin(admin.ModelAdmin)

and then:
def MyModel(admin.ModelAdmin, RedirectMixin)

then I get a MRO error.
However if RedirectMixin doesn't inherit from admin.ModelAdmin then the method doesn't get called.
An additional problem is how to generalise the super() call so it doesn't have the superclass hard-coded in.

A: Firstly, I presume you mean class rather than def in your examples.
Anyway, the right way to use a Mixin is to use it first in the list of classes to inherit. So:
class RedirectMixin(object):

and
class MyModelAdmin(RedirectMixin, admin.ModelAdmin):

This is because Python looks through all parent classes in order of declaration to find the method, and calls the first one it finds.
As for super, this shouldn't be mentioning the superclass at all - that's the whole point of it. It should reference the current class:
return super(MyModelAdmin, self).__init__(self, *args, **kwargs)

or whatever.
Edit after comments Yes, the mixin should refer to its own class in the super call. Consider the following:
In [1]: class BaseClass(object):
   ...:     def my_function(self):
   ...:         print 'base my_function'
   ...:

In [2]: class Mixin(object):
   ...:     def my_function(self):
   ...:         print 'mixin my_function'
   ...:         super(Mixin, self).my_function()
   ...:

In [3]: class MyDerivedClass(Mixin, BaseClass):
   ...:     pass
   ...:

Now if you instantiate the subclass and call its my_function method, the MRO will happen as you expect, even though Mixin doesn't inherit from BaseClass:
In [4]: m=MyDerivedClass()

In [5]: m.my_function()
mixin my_function
base my_function

The error you mention comes if you fail to make Mixin a descendant of object - if you don't, it's an old-style class, which doesn't support the use of super.


text:
Q: @Around Aspect in Spring AOP throwing Null Pointer Exception Can someone help me out figuring why my @Around advice throws a Null Pointer Exception here. I have made sure that my advice returns an Object same as the method to proceed, yet I am getting the exception.
@Aspect
public class BasicAuthAspect
{

    @Around("execution(* *..impl.PreferenceImpl.*(..))")
    public Object auth(ProceedingJoinPoint joinPoint) {
        log.debug("Inside Basic Auth check method..");
        ServletRequestAttributes requestAttributes=null;
        requestAttributes=(ServletRequestAttributes)
      RequestContextHolder.getRequestAttributes();
        if(requestAttributes!=null){
        request =requestAttributes.getRequest();

         Object[] signatureArgs = joinPoint.getArgs();
            try {
                return (Response) joinPoint.proceed(signatureArgs);
            } catch (Throwable e) {
                return Response.status(HttpStatus.SC_UNAUTHORIZED).build();
            }
    }

        }
        else{
            return Response.status(HttpStatus.SC_UNAUTHORIZED).build();
        }

      }

}

Here is my method to proceed(PreferenceImpl.java):
@Override
    public Response postPreferences( String preference) {

        String responseReturned=searchDAO.postPreference( XSSUtils.normalize(preference));
        if(responseReturned!=null)
        response=Response.status("success").build();
        else
        response=Response.status("failure").build();
        return response;
        }

Here goes the error log:
java.lang.NullPointerException
    at java.lang.String.<init>(String.java:556)[:1.7.0_80]
    at org.apache.cxf.transport.http.AbstractHTTPDestination.getAuthorizationPolicyFromMessage(AbstractHTTPDestination.java:163)[173:org.apache.cxf.cxf-rt-transports-http:2.7.3]
    at org.apache.cxf.transport.http.AbstractHTTPDestination.setupMessage(AbstractHTTPDestination.java:349)[173:org.apache.cxf.cxf-rt-transports-http:2.7.3]
    at org.apache.cxf.transport.http.AbstractHTTPDestination.setupMessage(AbstractHTTPDestination.java:258)[173:org.apache.cxf.cxf-rt-transports-http:2.7.3]
    at org.apache.cxf.transport.http_jetty.JettyHTTPDestination.serviceRequest(JettyHTTPDestination.java:345)[179:org.apache.cxf.cxf-rt-transports-http-jetty:2.7.3]
    at org.apache.cxf.transport.http_jetty.JettyHTTPDestination.doService(JettyHTTPDestination.java:319)[179:org.apache.cxf.cxf-rt-transports-http-jetty:2.7.3]
    at org.apache.cxf.transport.http_jetty.JettyHTTPHandler.handle(JettyHTTPHandler.java:72)[179:org.apache.cxf.cxf-rt-transports-http-jetty:2.7.3]
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1040)[79:org.eclipse.jetty.server:7.6.8.v20121106]
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:976)[79:org.eclipse.jetty.server:7.6.8.v20121106]

A: You could have several problems here:

*

*Your pointcut intercepts all PreferenceImpl methods, but it seems you only want to catch a single one. I suggest you make the pointcut more specific.

*You are assuming return type Response in the advice method, but your pointcut assumes * and the advice method itself returns Object, so theoretically another method could return another type and the cast would fail (see first problem).

*You are trying to provide arguments to proceed(), but that is actually not necessary. So just remove the getArgs() stuff, you do not need it.
If despite my hints you still have problems, let me know and I can provide some sample code. BTW, maybe you want to read a basic Spring AOP tutorial. :-)


text:
Q: How can I make in-app purchases with a different Apple ID than the app was purchased with? I have three children with three iPods and recently gave them all their own Apple ID accounts so that their iTunes money would be separate. However, now they cannot buy apps to add on to their games because the games were bought on our original Apple account.
How can I get the purchase to go through?

A: Purchasing from one account and then using another for in-app purchase (IAP) isn't currently possible.
Since each application is digitally signed when you download it from the App Store - you are tied to using the same account for in-app purchases as for the initial purchase.
If it is a free app, you could back up the device to iCloud, delete the app, re-purchase the app under the correct account and then restore the device from the backup. If you are not worried about saving game state, you can skip the backup and the restore steps.
If the app is not free, then you are faced with deciding to buy the in-app purchase from the original account or re-buying the app on the correct account.

A: You can log in and out of iTunes app store with different Apple IDs on the same device. I do it all the time with grandkids.
Administer account, hide purchases, browse store, all of it. In-app purchases should be no different. Just take care to log kids out of app store, and password your device!


text:
Q: Ruby: iterating over a hash and formatting the display Say I have a hash like so:
top_billed = { ghostbusters: 'Bill Murray', star_wars: 'Harrison Ford' }

What would be the best way to format it in a nice, human-readable way?
For example if you called a method on the hash and it displayed the hash as a capitalized list, minus underscores.

*

*"Ghostbusters: Bill Murray

*Star Wars: Harrison Ford

I guess iterating over the array and using gsub to remove underscores then capitalizing might work, but I was wondering whether there was anything more elegant.
Thanks

A: Here is a recursive solution:
top_billed = { ghostbusters: { my_name: 'Bill Murray', my_age: 29 }, star_wars: { my_name: 'Harrison Ford' }, something_esle: 'Its Name'}

def print_well(key, value, indent)
  key = key.to_s.split('_').map(&:capitalize).join(' ')
  if Hash === value
    puts "#{key}: "
    value.each do |k, v|
      print_well k, v, indent + 1
    end
  else
    puts "#{' '*indent}#{key}: #{value}"
  end
end

def print_hash hash, indent=0
  hash.each do |key, value|
    print_well key, value, indent
  end
end

print_hash top_billed

A: Manually:
top_billed.each do |k, v|
  puts k.to_s.gsub("_", " ") + ": " + v
end

if you are using Rails or ActiveSupport, you can also use the "humanize" method (on a String).


text:
Q: Calculate the p.m.f. of a non-monotonous function of a random variable I've been trying to prove the following and I'm really stuck.
Consider $N\sim \mathrm{Geometric}\left(p\right)$, and let $X=(-1)^N$. Show that the probability mass function of $X$ is given by
$$
p_X\left(k\right) =
\begin{cases}
\frac{1}{2-p}, \qquad k=1,\\
\frac{1-p}{2-p},\qquad k=-1.
\end{cases}
$$
I've managed to compute the expected value of $X$, $\mathbb{E}\left[X\right] = \frac{p}{2-p}$, and the variance as well, $\mathrm{Var}\left(X\right) = \frac{4\left(1-p\right)}{\left(2-p\right)^2}$. But I don't know if these values are helpful or not.
I am looking for hints. Thank you very much in advance.

A: $X=-1$ when $N$ is odd and $1$ when $N$ is even. $N$ is odd if it is $1,3,5,\dots=2k-1$ for a $k \in \mathbb{N}$. So using the geometric PMF:
$$P[N \text{ is odd }]=\sum_{k=1}^\infty (1-p)^{2k-2} p.$$
Now this is a geometric sum (after you factor out some terms). (I hope my convention for the geometric distribution coincides with yours...)


text:
Q: Spring Boot: Mocking SOAP Web Service I was wondering what the best practise to mock SOAP web services in spring boot is in order to run integration tests. All I could find on the spring website was https://spring.io/guides/gs/consuming-web-service/. Do we have to create a schema/wsdl for something as simple as mocking a dependency?
To mock a REST service, all we have to do is add the @RestController annotation to our mock service for it to boot. I was looking for a solution as lightweight.
Note: I'm currently using REST Assured for integration testing.
Thanks!

A: I used WireMock to mock an external SOAP server dependency.
The test class itself used the @SpringBootTest annotation to make sure I have a similar context to the real environment.
private WireMockServer wireMockServer = new WireMockServer(wireMockConfig().port(8089));

@Autowired
SoapClient soapClient;

@Test
@DisplayName("Retrieve SOAP message")
void retrieveMessage() {
    wireMockServer.start();
    WireMock.configureFor("localhost", 8089);
    WireMock.reset();
    stubFor(post(urlEqualTo("/ECPEndpointService"))
            .willReturn(
                    aResponse()
                            .withStatus(200)
                            .withHeader("Content-Type",
                                    "Multipart/Related; boundary=\"----=_Part_112_400566523.1602581633780\"; type=\"application/xop+xml\"; start-info=\"application/soap+xml\"")
                            .withBodyFile("RawMessage.xml")
            )
    );
    soapClient.retrieveActivations();
    wireMockServer.stop();
}

The content of the RawMessage.xml is the message response. In my case it was a multipart message (simplified):
------=_Part_112_400566523.1602581633780
Content-Type: application/xop+xml; charset=utf-8; type="application/soap+xml"

<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
    <env:Header/>
    <env:Body>
        <ns5:ReceiveMessageResponse xmlns:ns3="http://mades.entsoe.eu/" xmlns:ns4="http://mades.entsoe.eu/2/" xmlns:ns5="http://ecp.entso-e.eu/" xmlns:ns6="http://ecp.entsoe.eu/endpoint">
        <receivedMessage>
            ...
        </receivedMessage>
        <remainingMessagesCount>0</remainingMessagesCount>
        </ns5:ReceiveMessageResponse>
    </env:Body>
</env:Envelope>
------=_Part_112_400566523.1602581633780
Content-Type: application/octet-stream
Content-ID: <7a2f354f-dc52-406b-a4b1-9d89aa29cb2d@null>
Content-Transfer-Encoding: binary

<?xml version="1.0" encoding="UTF-8"?>
<edx:Message
    xmlns:edx="http://edx.entsoe.eu/internal/messaging/message"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <edxMetadata>
        ...
    </edxMetadata>
    <content v="PEFjdGl2YXRpb25"/>

</edx:Message>
------=_Part_112_400566523.1602581633780--

This setup allowed me to simulate a real call as much as possible.

A: Try this template:
import org.junit.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.xml.transform.StringSource;
import org.springframework.ws.test.client.MockWebServiceServer;
import static org.springframework.ws.test.client.RequestMatchers.*;
import static org.springframework.ws.test.client.ResponseCreators.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("applicationContext.xml")
public class MyWebServiceClientIntegrationTest {

    // MyWebServiceClient extends WebServiceGatewaySupport, and is configured in applicationContext.xml
    @Autowired
    private MyWebServiceClient client;

    private MockWebServiceServer mockServer;

    @Before
    public void createServer() throws Exception {
        mockServer = MockWebServiceServer.createServer(client);
    }

    @Test
    public void getCustomerCount() throws Exception {
        Source expectedRequestPayload = new StringSource("some expected xml");
        Source responsePayload = new StringSource("some payload xml");

        mockServer.expect(payload(expectedRequestPayload)).andRespond(withPayload(responsePayload));

        // client.getCustomerCount() uses the WebServiceTemplate
        int customerCount = client.getCustomerCount();
        assertEquals(10, response.getCustomerCount());

        mockServer.verify();
    }
}

A: The easiest way is mock the bean responsible to do the integration with the Soap Web Service.
Per example, if you have a SoapWebService that make this communication using Soap with another Web Service, you can use the @MockBean annotation on your test and mock the return. Example:
@SpringBootTest
@WebAppConfiguration
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class YourControllerIT {

    @MockBean
    private SoapWebService soapWebService ;

    @Before
    public void setup() {
        when(soapWebService.soapCall(
                any(), anyLong())).thenReturn("mockedInformation");
    }

    @Test
    public void addPerson() {
         MvcResult mvcResult = mockMvc.perform(post("/api/persons")
                .accept("application/json")
                .header("Content-Type", "application/json")
                .content(jsonContent))
                .andExpect(status().isCreated())
                .andReturn();
    }
}


text:
Q: How to import main.xsd into child.xsd and validate child.xml against child.xsd in android? I have 2 xsd files, one is main and other is child which includes main.xsd, now I have child.xml which I need to validate against child.xml and it should give me error in ide but it being validated against main.xsd only.
main.xsd
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:simpleType name="numeric_0-3">
        <xs:restriction base="xs:integer">
            <xs:minInclusive value="0" />
            <xs:maxInclusive value="3" />
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="numeric_0-60">
        <xs:restriction base="xs:integer">
            <xs:minInclusive value="0" />
            <xs:maxInclusive value="60" />
        </xs:restriction>
    </xs:simpleType>

<xs:element name="paymentSwitch_nii" default="001" type="numeric_0-3">
        <xs:annotation>
            <xs:documentation>Acquirer Network Identifier (NII)</xs:documentation>
        </xs:annotation>
    </xs:element>
<xs:element name="bin_eftpos" type="numeric_0-60">
        <xs:annotation>
            <xs:documentation>Efpos bin number</xs:documentation>
        </xs:annotation>
    </xs:element>

<xs:element name="parameter" type="main_override" />
    <xs:complexType name="main_override">
     <xs:all>
        <xs:element minOccurs='0' ref="paymentSwitch_nii" />
        <xs:element minOccurs='0' ref="bin_eftpos" />
     </xs:all>
     </xs:complexType>
</xs:schema>

child.xsd
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:include schemaLocation="../../../payment/src/main/assets/overrideparams.xsd" />

    <xs:element name="parameter">
        <xs:complexType>
            <xs:all>
                <xs:element minOccurs="1" name="main_override" type="main_override"/>
                <xs:element minOccurs='1' ref="offlineTransactionCeilingLimitCentsContact" />
                ......
            </xs:all>
        </xs:complexType>
    </xs:element>

    <xs:element name="offlineTransactionCeilingLimitCentsContact" type="numeric_0-999999999">
        <xs:annotation>
            <xs:documentation>Maximum allowed transaction value in offline mode for Contact/Insert
                transactions
            </xs:documentation>
        </xs:annotation>
.....
</xs:schema>

child.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parameter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:nonamespaceSchemaLocation="overrideparams.xsd">
.......
</parameter>

Is there something wrong with schema location or include xsd?


text:
Q: How to return a value in a JS asynchronous callback function - gapi I am using google's api client in my application. I have a function called initialize that uses gapi.load to authenticate my credentials and load the youtube api.
gapi.load takes a callback function which is where I authenticate and loadYoutubeApi, asynchronously. I want to know, when I run the initialize function, when these asynchronous functions have completed. Is there a way for me to return a value in this asynchronous callback function so that I know, when invoking initialize, that these asynchronous tasks have completed? Thanks!
const apiKey = 'my-api-key';
const clientId = 'my-client-id';

const authenticate = async () => {
  const { gapi } = window;
  try {
    await gapi.auth2.init({ clientId });
    console.log('authenticated');
  } catch (error) {
    throw Error(`Error authenticating gapi client: ${error}`);
  }
};

const loadYoutubeApi = async () => {
  const { gapi } = window;
  gapi.client.setApiKey(apiKey);
  try {
    await gapi.client.load('https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest');
    console.log('youtube api loaded');
  } catch (error) {
    throw Error(`Error loading youtube gapi client: ${error}`);
  }
};

const initialize = async () => {
  const { gapi } = window;
  const isInitialized = await gapi.load('client:auth2', async () => {
    try {
      await authenticate();
      await loadYoutubeApi();
      return true;
    } catch (error) {
      throw Error(`Error initializing gapi client: ${error}`);
    }
  });
  console.log(isInitialized); // expects `true` but am getting `undefined`
};

initialize();

A: You can wrap gapi.load part in a promise like this:
const initialize = async () => {
  const { gapi } = window;
  await new Promise((resolve, reject) => {
    gapi.load('client:auth2', async () => {
      try {
        await authenticate();
        await loadYoutubeApi();
        resolve();
      } catch (error) {
        throw Error(`Error initializing gapi client: ${error}`);
      }
    });
  });
  return true;
};

initialize(); // returns 'true' when done.

A: Wrap the load in a Promise so that you can await it like the rest of your code.
try {
  await new Promise((resolve,reject) => {
    gapi.load('client:auth2', resolve);
  });
  await authenticate();
  await loadYoutubeApi();
} catch (error) {
  throw Error(`Error initializing gapi client: ${error}`);
}
//is Initialized


text:
Q: Json string cutsoff after # symbol in angularjs am using AngularJs service to call my MVC controller method and sending parameters along with it. this is my angular service Url and model
var transData = {
    Address: $scope.user.address,
    Comments: $scope.user.comments,
    Password: $scope.password,
    Id: $scope.id
};`

'../transaction/UpdateData?transModelData=' + angular.toJson(transData)
this is my MVC Action method
public void UpdateData(string transModelData = null)
My problem is occuring when i use special character # in my password field.
Json string is cuts off after the password like below
{"Address":"address","Password":"qwerty123
but the actual json string should be like
{"Address":"address","Password":"qwerty123#","StudentId":"12"}
can anyone help me out to overcome this issue, thanks


text:
Q: cordova build --> both debug and release builds are working. But when I do `zipalign` it fails to install on my device I have created an application using angular and processed it using Cordova.
Now, when I use cordova build android or cordova build --release android I get the desired result i.e. the app is running on my device, even after signing it (with my.keystore) using the below
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my.keystore  name1.apk alias

it works fine till here, but when I attempt to zipAlign the same using
./zipalign -f -v 4 app-release.apk app-final.apk

it shows Verification successful, then when I try to install it prompts--> app not installed on my device.
What is possibly wrong here?
Below are the steps in sequence.

*

*put the angular dist build in www folder.

*generate keystore using

keytool -genkey -v -keystore <keystorename> -alias <aliasname> -keyalg RSA -keysize 2048 -validity 10000

*add keystore && build.json with keystore password.

*run cordova build --release android --> produces app-release.apk

*then using zipAlign in buildtools

./zipalign -f -v 4 app-release.apk app-final.apk

Also in play console while uploading the generated .apk. I'm getting following:
You uploaded an APK with an invalid signature (learn more about signing). Error from apksigner: ERROR (Jar signer CERT.RSA): JAR signature META-INF/CERT.SF indicates the APK is signed using APK Signature Scheme v2 but no such signature was found. Signature stripped?

A: If you have landed here .. my issue was resolved importing the project to Android studio and generating build from there.
check the referenced question --> Error while trying to upload APK to Google Play

A: I think you are missing some steps.
If you are using build.json, you have to build APK using this script.
cordova build android --release --buildConfig=build.json

or after cordova build android --release, sign your app using jarsigner.


text:
Q: instruction to enable ftp_ssl_connect on a LAMP stack I'm trying to work with ftp_ssl_connect function (on LAMP Stack) for connecting to ftps (not sftp) site(s). I check for openssl instillation, and is available. I un-commented extension=php_openssl.dll, and that gave me the following error.
Error Message:
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/php_openssl.dll' - /usr/lib64/php/modules/php_openssl.dll: cannot open shared object file: No such file or directory in Unknown on line 0
SSL not working
when I comment out extension=php_openssl.dll, I get the error message SSL not working.
How do I enable SSL or make SSL work?

A: The L in LAMP means Linux, and the .dll files are for Windows. You need to install php_openssl package from yum or apt or ports or whatever your linux distro uses. You might just need to find the line in either php.ini or extensions.ini for openssl.so and uncomment that.


text:
Q: hide Post Author badge in comments I'm using WordPress Customizr Theme, the Classical version. This theme seems to create a blue "Post Author" badge in comments. I found this, but solutions don't seem to work:
https://presscustomizr.com/snippet/remove-post-meta-details/
I also tried this…
.comment-meta cite.fn {
    display: none; !important;
}

…but it also hides the Author's name (which I don't want).
You can see example page here:
https://www.lifeleap.org/psychic-project/target-1a-discussion/
Any suggestions on how to just hide the "Post Author" badge in the comments? I was desperatly hoping to find a CSS solution instead of hacking the theme files.
Thanks for any help

A: Use this CSS to hide only the badge:
.comment-meta cite.fn > span {
    display: none;
}

That badge is inside the span (the author name is not), so this selector will only hide the span, i.e. the badge


text:
Q: Duplicate a file in python I'm trying to duplicate a file in python.
Going through shutil, I've only found solutions to copy and move the files but I need to duplicate a file to rename and keep the original.
    photos54_TempString = "photos54/thumb-" + artistName + "_54.jpg"
    photos54_NewString = "quickManik_Music/" + songID + "-" +
    artistName + "_54.jpg"

    copyfile(photos54_TempString, photos54_NewString)

A: Use the function shutil.copyfile.
Here's an example, using the terminal and the Python interpreter:
$ cd /tmp
$ touch myfile
$ python3
Python 3.5.3 (default, May 10 2017, 15:05:55)
[GCC 6.3.1 20161221 (Red Hat 6.3.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import shutil
>>> shutil.copyfile('myfile', 'mysecondfile')
'mysecondfile'
>>>
$ ls my*
myfile  mysecondfile


text:
Q: Seg Fault resulting from push_back call on vector (threads linux) So what I'm trying to do is write a program that creates a series of child threads that take the arguments using the pthread_create method and uses the parameter passed in to do more manipulation and so on. The parameter I'm trying to pass in is a vector argument called reduce_args_. this is the header information for the struct ReduceVector.
typedef vector<string> StringVector;

// a data structure to maintain info for the reduce task
struct ReduceArg
{
  ReduceArg (void);  // constructor
  ~ReduceArg (void); // destructor

  pthread_t tid;  // thread id of the reduce thread
  StringVector files_to_reduce; // set of files for reduce task
};

// more typedefs
typedef vector<ReduceArg *> ReduceVector;

now the issues comes when I call push_back here:
for(int i = 0; i < num_reduce_threads_ ; i++){
            reduce_args_.push_back(phold);
        int count = 0;
        for(ShuffleSet::iterator it = shuffle_set_.begin(); it!=shuffle_set_.end(); ++it){
            string line = *it;
            string space = " ";
            string file = line.substr(0, line.find(space)) + ".txt";

            if (count < num_reduce_threads_){
                cout << reduce_args_[i+1];
                (reduce_args_[i+1] -> files_to_reduce)[count] = file;
                            //(reduce_args_[i+1] -> files_to_reduce).push_back(file);
             }
             count++;
            //cout << ((reduce_args_.back())->files_to_reduce).back()<< endl;
    }
}

both of those push_back methods cause a seg fault. the shuffle set is just a set and is outputting strings. and as noted in the .h file, the files_to_reduce is a string vector. So what I'm trying to do is access the files_to_reduce and push_back a string onto it, but each time I get a seg fault. The reduce_args_ obj is declared as below:
ReduceArg* plhold;
    reduce_args_.push_back(plhold);
    ((reduce_args_.back()) -> files_to_reduce).push_back("hello");
    for (int i = 0; i < this->num_reduce_threads_; ++i) {
      // create a placeholder reduce argument and store it in our vector
      (reduce_args_.push_back(plhold));
    }

thanks for the help!!

A: This:
ReduceArg* plhold;
reduce_args_.push_back(plhold);

Unless you've hidden some important code, you're pushing an uninitialised pointer, so the next line will cause chaos.
Possibly you meant this?
ReduceArg* plhold(new ReduceArg);

..but I suspect you haven't properly thought about the object lifetimes and ownership of the object whose address you are storing in the vector.
In general, avoid pointers unless you know exactly what you're doing, and why. The code as posted doesn't need them, and I would recommend you just use something like this:
typedef vector<ReduceArg> ReduceVector;

....
reduce_args_.push_back(ReduceArg());
reduce_args_.back().files_to_reduce.push_back("hello");
for (int i = 0; i < num_reduce_threads_; ++i) {
  // create a placeholder reduce argument and store it in our vector
  (reduce_args_.push_back(ReduceArg());
}


text:
Q: Is a normal line to a constant function defined? This is probably more so an attempt to clarify definitions rather than prove anything, but my question is roughly as follows: in $2D$ space, the naive way to define a normal line to some function $f(x)$ at a given point is through perpendicularity to the tangent line at that point. Algebraically, this is expressed as the negative reciprocal of the slope of the tangent line. But since the slope of a constant function is always $0$, such a reciprocal is clearly undefined. Now, mathematically that makes sense because this normal line wouldn't be a function, but graphically it doesn't, as it's really easy to draw a line perpendicular to a constant function at any given point. So, my first question is whether there exists a way to deal with such an object in a formal manner? And secondly, does the normal even have to be a function in the rigorous sense? I'm not well-versed in formal geometry, so I'm not sure what alternative definitions exist that could bridge this gap between mathematical definitions and graphical intuition.

A: A normal is a straight line and a straight line needn't be described by a function.
$$x=x_0$$ is the equation of a vertical line.

By the way, a curve needn't be described by a function either.
$$(x-x_0)^2+(y-y_0)^2=r^2$$ is the equation of a circle.


text:
Q: nodejs - Sequelize destroy not working I am running into issues while trying to delete a row from a table. In general, the row is not being deleted even though the console logs show that Sequelize is executing a DELETE query.
My code:
await UserItem.destroy({
  where: {
    userSteamId,
    assetId
  }
});

And the console log shows:
Executing (default): DELETE FROM `user_item` WHERE `user_steam_id` = '76561198056233432' AND `asset_id` = '1881811583708444794'

If I copy and paste the query and execute it in the MySQL terminal it works like a charm. Any ideas/suggestions why this is happening?


text:
Q: Error while converting Bitmaps to AVI using Accord.Video.VFW.dll While converting Bitmaps to AVi with Accord.Video.VFW.dll, i use this code:
AVIWriter writer = new AVIWriter();
// create new AVI file and open it
writer.Open( "test.avi", 320, 240 );
// create frame image
Bitmap image = new Bitmap( 320, 240 );

for ( int i = 0; i < 240; i++ )
{
    // update image
    image.SetPixel( i, i, Color.Red );
    // add the image as a new frame of video file
    writer.AddFrame( image );
}
writer.Close( );

In line
writer.AddFrame( image );

Always getting error:
Exception thrown: 'System.OverflowException' in Accord.Video.VFW.dll

A: You need to check "preferably 32 bit" in the build menu in the project properties


text:
Q: Wrapping Margin Notes I'm writing a small list of things and want to insert a small kind of box into the margin on right side of the list.
I'd like it to behave more or less like this:
If it fits into the margin fine.
If not, occupy some space for normal text, while still sitting mainly in the margin
If not, wrap into the (list) text (as far as i could gather this is the crux)
Or look for a place where there are short list items, since theres alot of wasted space there
Does there exist some kind of solution for this?
\marginpar only uses the margin which is too little space
\wrapfigure does exactly what I want, but won't work at all for lists (i can't even force the position, it just sits where it wants no matter what I enforce)
Due to my limited knowledge, the only thing I can think of that could be possible is somehow placing a minipage at a specified position on the page and then manually making sure that nothing overlaps, but I don't know how to do that, or if that works


text:
Q: What is difference between these two Where conditions? I have a project using NHibernate. I wrote a query by QueryOver.
var q = SessionInstance.QueryOver<Person>();
list<Person> TypeList = new list<Person>();

What is difference between these two Where conditions?
q = q.Where(Restrictions.Or(Restrictions.On<Person>(p => p.PersonType).IsNull, Restrictions.On<Person>(p => p.PersonType).IsIn(TypeList)));

and
q = q.Where(p => p.PersonType == null || p.PersonType.IsIn(TypeList));

A: The second version is more OO, while the first is basically functional programing.
In the first version you create an object that can return true or false for any given Person object. During creation of the object all you are telling it is what to look for (null value for instance) and where (in the propery PersonType in this case).
The second version might actually make you think there's no object to be mentioned (We're talking C#, so everything's an object). All you are doing is sending the body of a function to the Where method.
In both cases the Where method will run the same way - for every person, send it as an argument to the given object. The difference is how the object works. While the delegate/lambda moves the instruction pointer to wherever the method body is stored (not exactly...this is still not assembly, but kind'a), the OO solution starts to check it's internal state to apply a condition (like activating the lambda you sent it to extract PersonType from a Person). It then asks the question you told it to ("IsNull"), and returns the answer.
These are just two ways of saying the same thing, I know (that's why you're getting the same result), but the difference is where is the control and where is the data.
The OO version separates the control from the data and hides implementation by working using an interface (you just tell it what you want and where to find the data, but not how to use it to create the answer).
The functional approach asks you to provide the complete implementation and just lets you run (something like: "you handle the data, the extraction, the control and just about what ever you want...You'll probably do it better anyways").
Hope that clears it up


text:
Q: Python Dict() sorting according to datetime I have one file with so many values those are as below
{'Name':'xyz','Date':'Thu Jun 26 13:14:17 +0000 2008'}
{'Name':'xyz','Date':'Thu Jun 19 13:14:17 +0000 2009'}
{'Name':'xyz','Date':'Thu Jun 26 13:15:17 +0000 2008'}

How to sort these values according to date and time?

A: If the file has these one per line, you'll need to convert to real dicts, e.g. with json.loads or ast.literal_eval, then sort:
import json
import datetime

def parse_date(datestr):
    return datetime.datetime.strptime(datestr, '%a %b %m %H:%M:%S %z %Y')

with open(myfilename) as f:
    mydicts = map(json.loads, filter(str.strip, f))
    # This sorts on date value, but leaves them as original str
    # in dict, can convert ahead of time if you want, or not, as you please
    sorteddicts = sorted(mydicts, key=lambda d: parse_date(d['Date'])]

A: You can use dateutil.parser for parsing dates and add the proper key in the sort function.

This works -
In [20]: from dateutil.parser import parse

In [21]: l = [{'Name':'xyz','Date':'Thu Jun 26 13:14:17 +0000 2008'},
{'Name':'xyz','Date':'Thu Jun 19 13:14:17 +0000 2009'},
{'Name':'xyz','Date':'Thu Jun 26 13:15:17 +0000 2008'}]

In [22]: sorted(l, key=lambda x: parse(x['Date']))
Out[22]:
[{'Date': 'Thu Jun 26 13:14:17 +0000 2008', 'Name': 'xyz'},
 {'Date': 'Thu Jun 26 13:15:17 +0000 2008', 'Name': 'xyz'},
 {'Date': 'Thu Jun 19 13:14:17 +0000 2009', 'Name': 'xyz'}]

A: You could use email package from stdlib, to parse the date format into "seconds since the Epoch":
>>> from email.utils import parsedate_tz, mktime_tz
>>> mktime_tz(parsedate_tz('Thu Jun 26 13:14:17 +0000 2008'))
1214486057

It is easy to sort dicts by Date field:
>>> sorted(dicts, key=lambda d: mktime_tz(parsedate_tz(d['Date'])))
[{'Date': 'Thu Jun 26 13:14:17 +0000 2008', 'Name': 'xyz'},
 {'Date': 'Thu Jun 26 13:15:17 +0000 2008', 'Name': 'xyz'},
 {'Date': 'Thu Jun 19 13:14:17 +0000 2009', 'Name': 'xyz'}]

To load json objects from the file, you could use code from @ShadowRanger's answer.


text:
Q: Wordpress custom post template page/2 loop not working I have a loop in the sidebar of a custom template and it works perfectly when the page is loaded. The page is -
http://ere.doneready.com/senior-consultants
However the loop (which shows the list of names) does not work when I click the "next" button i.e. this page -
http://ere.doneready.com/senior-consultants/page/2/
Can anyone help? The following is the code I use -

    <form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">

<?php _e( 'SEARCH' ); ?>

        <input class="search-box" type="text" name="s" id="s" />
        <input type="image" name="submit" id="searchsubmit" SRC="http://www.doneready.com/ere/wp-content/themes/ere/images/search_button.png" HEIGHT="17" WIDTH="20" BORDER="0" ALT="Submit Form">
    </form>

Directors

Finance & Admin

Senior Consultants

<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args=array(
   'post_type'=>'staff',
   'posts_per_page' => 99,
   'paged'=>$paged,
   'staff_categories'=>'Senior Consultants'
);
$temp1 = $wp_query;
$wp_query= null;
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
?>

<a href ="<?php the_permalink(); ?>">
<?php echo esc_html( get_post_meta( get_the_ID(), 'staff_short_name', true ) ); ?>

<?php
endwhile; endif;
/* PageNavi at Bottom */
$wp_query = null;
$wp_query = $temp1;
wp_reset_query();
?>

Consultants

Technical Support

A: Welcome to StackOverflow, try to search the archives at least semi-extensively first because many variations of this question exist. Here's a link to my answer to a very similar question, it worked for me, it might work for you:
Making a single page blog in WordPress

A: Solved. I used a new loop and the code looks like this now -

    <form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">

<?php _e( 'SEARCH' ); ?>

        <input class="search-box" type="text" name="s" id="s" />
        <input type="image" name="submit" id="searchsubmit" SRC="http://www.doneready.com/ere/wp-content/themes/ere/images/search_button.png" HEIGHT="17" WIDTH="20" BORDER="0" ALT="Submit Form">
    </form>

Directors

Senior Consultants

<?php
$args = array( 'post_type' => 'staff', 'staff_categories'=>'Senior Consultants', 'posts_per_page' => 50 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>

<a href ="<?php the_permalink(); ?>">
<?php echo esc_html( get_post_meta( get_the_ID(), 'staff_short_name', true ) ); ?>

<?php
endwhile;
?>
<?php
wp_reset_query();
?>

Consultants

Technical Support
Finance & Admin