text:
Q: Optimizing web page for different resolution monitors I have been working on a site, found here, and it looks fine on my monitor (1440 x 900) however it looks very plain when displayed on an oversized monitor. I give the outer box an absolute height and width and this is obviously the reasoning for my issue but what could I do to fix this problem when the images are all a fixed height and width?
I read somewhere that I could do a check to see what dimensions the monitor is on page load - would anyone recommend this?
On a larger monitor there is a lot of blank space to the left and right, and also below the outer box.
thank you for any help!
-Evan

A: You can do it using two ways:

*

*CSS 3 Media Queries

*Fluid Layout

Since you said you will be supporting IE too, CSS 3 Media queries won't be working below IE 9, so lets use fluid layout. For this, you can do a few stuffs:
CSS Changes
#full-height-template-container {width: 1225px;}
#navigation-menu-container {width: 149px;}
#static-frontpage-padding {width: 855px;}

Replace it to:
#full-height-template-container {width: 90%;}
#navigation-menu-container {width: 20%;}
#static-frontpage-padding {width: 80%;}

A few adjustments might be necessary.
CSS 3 Media Queries
Media queries are one of the most exciting aspects about CSS today. They will allow us to change our layouts to suit the exact need of different devices – without changing the content.
Example & Demo for CSS 3 Media Queries
HTML Markup
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Media query Resolution Dependent Layout</title>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <link rel="stylesheet" type="text/css" href="stylesheets/master.css" />

        Site name

Link 1

Link 2

Link 3

            Main heading here

            Lorem ipsum dolor sit amet consect etuer adipi scing elit sed diam nonummy nibh euismod tinunt ut laoreet dolore magna aliquam erat volut. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.

            Related info

            Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

CSS code
/* ----------------------------
simple reset
---------------------------- */

html, body, ul, ol, li, form, fieldset, legend
{
    margin: 0;
    padding: 0;
}

h1, h2, h3, h4, h5, h6, p { margin-top: 0; }
fieldset,img { border: 0; }
legend { color: #000; }
li { list-style: none; }
sup { vertical-align: text-top; }
sub { vertical-align: text-bottom; }

table
{
    border-collapse: collapse;
    border-spacing: 0;
}

caption, th, td
{
    text-align: left;
    vertical-align: top;
    font-weight: normal;
}

input, textarea, select
{
    font-size: 110%;
    line-height: 1.1;
}

abbr, acronym
{
    border-bottom: .1em dotted;
    cursor: help;
}

body
{
    margin: 20px;
    color: #000;
    background: #fff;
    font: 90%/1.3 "DejaVu Sans", "URW Gothic L", "Helvetica Neue", Helvetica, Arial, "Microsoft Sans Serif", sans-serif;
}

#container
{
    float: left;
    width: 1000px;
    background: #bbb;
}

#nav
{
    float: left;
    width: 200px;
    background: lime;
}

#content
{
    float: left;
    width: 550px;
    margin: 0 0 0 25px;
    background: yellow;
}

#extras
{
    float: right;
    width: 200px;
    background: gray;
}

.feature-image
{
    float: right;
    margin: 0 0 10px 10px;
}

@media screen and (max-width:999px)
{
    #container { width: 800px; }

    #extras
    {
        clear: left;
        float: none;
        margin: 0 0 0 225px;
        width: 550px;
    }
}

@media screen and (max-width:480px)
{
    #container { width: 400px; }

    #nav
    {
        float: none;
        width: auto;
    }

    #content
    {
        float: none;
        width: auto;
        margin: 0;
    }

    #extras
    {
        float: none;
        width: auto;
        margin: 0;
    }

    .feature-image { display: none; }
}

Demo
You can find a working demo at CSS3 Media query layout example. Enjoy!


text:
Q: Random Forest partial plot for a binary predictor I'm not sure how to interpret a partial dependence plot for a categorical variable. For instance, the partial dependence (command partialPlot from the randomForest package) for a binary predictor would give two values, one for each category.
How exactly do you interpret those values? The documentation of partialPlot is quite cryptic in this respect.
My confusion arises, I guess because I'm thinking in terms of a logistic regression, where with a dummy coding system you in general obtain the log-odds of the variable of interest against the baseline category.

A: In general partial plots are the average of a series of hypothetical predictions.
For continuous variables, partialPlot selects a series of n.pt values along the variable of interest. It creates a test data set identical to the training data, and sequentially sets the variable of interest for all observations to a selected value. It then takes the average value of the predicted response for each test set and plots the results against the select value. For a binary categorical predictor, this process would result in only two values.
It is helpful to use partial plots in combination with variable dependence and interpret them together. The variable dependence figure is generated by plotting the forest predicted value against the variable of interest for each observation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to name processes and insert values in respective process as named in UNIX I need to create processes using fork and assign respective values to them according to their names/labels. And then transfer the values using pipes() in C language. My question is, is there a way to name processes?

A: Each process has an unique identifier, PID. In Linux (as well as in all POSIXy and Unix systems) these identifiers are positive integers, with 1 being special, init.
(By unique, above, I mean that every active (running) process and zombie process have their own PID, and no two share the same PID. However, old PIDs are eventually reused, sometimes within seconds; it depends on the system. Do not expect the PID of a dead process to stay unused!)
When you fork a child process, fork() returns (pid_t)0 in the child process, and the child process PID in the parent process. By storing the PIDs of the child processes you create in an array, the parent process can tell which child is which.
Each process can always call getpid() to find out what it's own PID is.
A process can also call getppid() to find out the PID of their parent process (the PID of the process that called fork() that created this process). However, if the real parent has already died/exited, getppid() will return 1. (This is also half of the reason we have an init process. The init process is responsible for exactly two things: being the parent of orphan processes, and reaping them when they die; and to start all the other processes when the operating system boots up.)
Neither getpid() or getppid() can ever fail; you can rely on them to always return the respective PIDs.
Overall, this kind of design is extremely common in practice. All daemons that use multiple processes to do their work, do basically exactly this. It means this exercise is relevant in practice, too.


text:
Q: Mode Text 2nd most common text value IFERROR(INDEX($I$7:$I,MODE(IF($I$7:$I<>"",MATCH($I$7:$I,$I$7:$I,0)))),"No data")
With this formula, which calculates the most common text value, I need to have the 2nd most common.
Column I content:

Apple
Orange
Apple
Apple
Orange

In this example, I need to get Orange. How is that possible? I can't figure how.

A: A PivotTable might suit:

and copes with ties for rank.

A: You can extract the most frequent item in the list with an array formula.
=INDEX(MyList,MATCH(MAX(COUNTIF(MyList,MyList)),COUNTIF(MyList,MyList),0))

Note that an array formula must be confirmed with Shift+Ctl+Enter instead of the customary singular Enter required for normal formulas. When entered wrongly it will display a #NUM! error.
For simplicity's sake I have used a named range MyList in the formula. However, if you prefer, you can replace the name with something like $I$7:$I$1000.
To extract the second-most frequent expression in the list you could use a formula constructed analogue to the above.
=INDEX(MyList,MATCH(LARGE(COUNTIF(MyList,MyList),MAX(COUNTIF(MyList,MyList))+1),COUNTIF(MyList,MyList),0))

This formula is built on the logic that n equals the highest number of occurrences. Therefore the second highest must rank as n + 1, being MAX(COUNTIF(MyList,MyList))+1) in the above formula. By the same method the third ranked could be extracted.
You can embed these formulas in an IFERROR() function.

A: I found this on Mr Excel
Return most common, 2nd most common, 3rd most common, etc. text string in an array
Spreadsheet Formulas
Cell ___ Formula 'Notice that the cells are B2, D2, E2. Column C is blank
B2  =IF(A2="","",IF(COUNTIF(A$2:A2,A2)=COUNTIF($A$2:$A$100,A2),COUNTIF($A$2:$A$100,A2)+(ROW()/1000),""))
D2  =IF(ROWS($1:1)>COUNT(B:B),"",INDEX(A:A,MATCH(LARGE(B:B,ROWS($1:1)),B:B,0)))
E2  =IF(D2="","",COUNTIF($A$2:$A$100,D2))

Results
___ A ________ B ___C ___D _________E
1   Data Set:___Helper ____ Name ____   Occurrences
2   Harmon      _____________ Williams ______4
3   Smith       _______________ Smith ________3
4   Smith       _______________ Harmon  ______2
5   Harmon_____    2.005
6   Williams
7   Williams
8   Smith   _______3.008
9   Williams
10  Williams    ____4.010

A: you can try to tie this all together in a single formula but it's simpler and more agile in a spreadsheet environment to just break out the problem in a few separate steps.
take a given column of values you're wanting to count/rank - i'll call it RankList in examples below.
if you're not setting named ranges (do yourself a favor and use named ranges) you'll want this to be your column range - i.e. A:A
now in another column use
=unique(RankList)

there's your list of unique values, now we just need to count the instances of each unique value in the original RankList - this is simple - in the next column over simply use
=countif(RankList,B1)

B1 above represents the cell adjacent to the formula, wherever that might be on your sheet. now autofill the formula in with the relative cell value for each item. now all of your items are counted by instance.
now we want to sort them by value, highest to lowest. create another named range, selecting the two columns containing the =unique(RankList) and =countif(RankList,B1) formulas that were just created, i'll refer to it as UniqueCount
use the following
=sort(UniqueCount, 2, false)

that's it. again you can accomplish this by stacking formulas like in the above examples, but in practice i've found that you won't know what you'll want to do additionally with your data/sheet later on. keeping it broken up in discrete steps like this makes it much easier to make adjustments.


text:
Q: unable load python package when executing python script from c# Hi i'm new to python and ironPython, I'm trying to execute the python script from c#, i can execute the script from python Interactive window succesfully but i'm unable execute the script from c#. i can execute the python script from c# which basic functionalities but i can't execute my script because my uses some package's like numpy, keras, tensorflow, sk-learn, pandas, etc., i'm getting error like this
Traceback (most recent call last):
File "C:\Users\amarn\Downloads\Projects\AI_Score\Ai_Score\AI_Score.py", line 1, in <module>
import keras
File "C:\Users\amarn\Anaconda3\lib\site-packages\keras\__init__.py", line 3, in <module>
from . import utils
File "C:\Users\amarn\Anaconda3\lib\site-packages\keras\utils\__init__.py", line 2, in <module>
from . import np_utils
File "C:\Users\amarn\Anaconda3\lib\site-packages\keras\utils\np_utils.py", line 6, in <module>
import numpy as np
File "C:\Users\amarn\Anaconda3\lib\site-packages\numpy\__init__.py", line 140, in <module>
from . import _distributor_init
File "C:\Users\amarn\Anaconda3\lib\site-packages\numpy\_distributor_init.py", line 34, in <module>
from . import _mklinit
ImportError: DLL load failed: The specified module could not be found.

so can anyone help me what i have to do and also i want to know why these package not loading python.exe which is executing from c# code.
This is my C# code:
public static void RunPythonScript()
    {
        try
        {
            ProcessStartInfo pythonInfo = new ProcessStartInfo();
            pythonInfo.FileName = @"C:\Users\amarn\Anaconda3\python.exe";
            var file1 = "C:/Users/amarn/source/repos/IBBI Crawling And Ai_Score/IBBI Crawling/bin/Debug/InsolvencyCompany_20190627T181821.xlsx".Replace(" ","%20");
            string PredictFile_file2 = "C:/Users/amarn/source/repos/IBBI Crawling And Ai_Score/IBBI Crawling/bin/Debug/InsolvencyCompany_Predict_20190627T181821.xlsx".Replace(" ", "%20");
            var script = string.Format(@"C:\Users\amarn\Downloads\Projects\AI_Score\AI_Score\AI_Score.py {0} {1}", file1, PredictFile_file2);
            pythonInfo.Arguments = script;

            pythonInfo.UseShellExecute = false;
            pythonInfo.CreateNoWindow = true;
            pythonInfo.RedirectStandardOutput = true;
            pythonInfo.RedirectStandardInput = false;
            pythonInfo.RedirectStandardError = true;

            using (Process process = new Process())
            {
                process.StartInfo = pythonInfo;
                process.Start();
                process.WaitForExit();

                var errors = process.StandardError.ReadToEnd();
                var results = process.StandardOutput.ReadToEnd();
                if (!string.IsNullOrEmpty(errors))
                {
                    Console.WriteLine("Erros: " + errors);
                }
                Console.WriteLine("Result: \n" + results);

            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }


text:
Q: Java contains vs anyMatch behaviour If I have a Name object and have an ArrayList of type Name (names), and I want to ascertain whether my list of names contains a given Name object (n), I could do it two ways:
boolean exists = names.contains(n);

or
boolean exists = names.stream().anyMatch(x -> x.equals(n));

I was considering if these two would behave the same and then thought about what happens if n was assigned null?
For contains, as I understand, if the argument is null, then it returns true if the list contains null. How would I achieve this anyMatch - would it be by using Objects.equals(x, n)?
If that is how it works, then which approach is more efficient - is it anyMatch as it can take advantage of laziness and parallelism?

A: The problem with the stream-based version is that if the collection (and thus its stream) contains null elements, then the predicate will throw a NullPointerException when it tries to call equals on this null object.
This could be avoided with
boolean exists = names.stream().anyMatch(x -> Objects.equals(x, n));

But there is no practical advantage to be expected for the stream-based solution in this case. Parallelism might bring an advantage for really large lists, but one should not casually throw in some parallel() here and there assuming that it may make things faster. First, you should clearly identify the actual bottlenecks.
And in terms of readability, I'd prefer the first, classical solution here. If you want to check whether the list of names.contains(aParticularValue), you should do this - it just reads like prose and makes the intent clear.

EDIT

Another advantage of the contains approach was mentioned in the comments and in the other answer, and that may be worth mentioning here: If the type of the names collection is later changed, for example, to be a HashSet, then you'll get the faster contains-check (with O(1) instead of O(n)) for free - without changing any other part of the code. The stream-based solution would then still have to iterate over all elements, and this could have a significantly lower performance.

A: They should provide the same result if hashCode() and equals() are written in reasonable way.
But the performance may be completely different. For Lists it wouldn't matter that much but for HashSet contains() will use hashCode() to locate the element and it will be done (most probably) in constant time. While with the second solution it will loop over all items and call a function so will be done in linear time.
If n is null, actually doesn't matter as usually equals() methods are aware of null arguments.


text:
Q: Populate Email Body from Lightning component using Lightning for Gmail I am using Lightning for Gmail extension provided by salesforce. Just developed a custom component for it, now i want to populate gmail compose email body as it is done through Email Template component. Is there any api or interface in lightning for it. So far i already implemented clients:availableForMailAppAppPage,clients:hasItemContext interfaces to get people,messagebody etc. just want to set message body now.

A: I see that we cant edit outlook fields (to,cc, subject, body) from component and it is still in salesforce roadmap.
Let me know if you found a workaround


text:
Q: How to prove this function related to absolute distance is a positive definite kernel? Prove $$K(x,y)=\frac{1}{1+||x-y||}$$ is a kernel for $x,y\in\mathbb{R}^d$.
I think one might use the fact $$K(x,y)=\int_0^{+\infty} e^{-t\left(1+||x-y||\right)}dt$$ like what we did in proving Hilbert matrix is positive definite. How do we proceed from here?

A: Let $X=(x_i)_{1\leq i\leq n} \in \cal{M}_{n,1}(\mathbb{R})$ and denote $A$ the $n \times n$ matrix having for coefficients $K(c_i,c_j)$ where $\{c_1, \dots, c_n\} \in \mathbb R^d$ are distinct. We have
$$\begin{aligned}
{}^tXAX&=\sum_{1\leq i,j\leq n}\frac{x_ix_j}{1 + \Vert c_i - c_j \Vert}\\
&=\sum_{1\leq i,j\leq n}x_ix_j\int_0^\infty e^{-t\left(1+\Vert c_i - c_j \Vert\right)}dt\\
&=\int_0^\infty \left(\sum_{i=1}^nx_ie^{-\frac{t}{2}\left(1+\Vert c_i - c_j \Vert\right)}\right)^2dt>0
\end{aligned}
$$ for $X\neq0$, giving the announced result since

*

*$A$ is symmetric,

*the $c_i$ distinct,

*$(e^{\alpha x})_{\alpha \in \mathbb R}$ is a family of independent functions of $\mathcal C([0,\infty), \mathbb R)$, hence $t \mapsto \sum_{i=1}^nx_ie^{-\frac{t}{2}\left(1+\Vert c_i - c_j \Vert\right)}$ is a continuous function not always vanishing,

*the integral of a non negative continuous not always vanishing function is positive.


text:
Q: Is there any alternative way to simulate a continuous time model instead of discrete? Normally I use the exponential matrix method to turn continuous time model to discrete time model. In this case, it's SS-models:
$$\dot x = Ax + Bu + Eu \\ y = Cx + Du$$
$$\begin{bmatrix}
A_d & B_d &E_d \\
0 &I  &I
\end{bmatrix} = e^{\begin{bmatrix}
A & B & E\\
0 & 0 & 0
\end{bmatrix}}T_s$$
Where $T_s$ is the sampling time.
But I have a problem with it comes to this and it's because of the simulation of nonlinear systems.
If I have a nonlinear model:
$$\dot x = f(x, u)$$
And I want to linearize it in the state $x_0 = 0$. I know that it will be nothing left of the dynamics. Assume that we linearize at the initial state and we have some damping in our system, then the damping factor is going to be zero.
I going to do nonlinear numerical simulation of a discrete system. So my procedure is going to be:

*

*Linearize the system in state $x$. E.g If we have the damping $Bx_2^2$ the it would be linearized to $2Bx_2$.

*Turn it to discrete

*Do the simulation and find state $x$

*Jump to stage 1.

A lot of times, my simulation breaks. To do a simulation, I need to linearize the system first and then turn it to a discrete form, as I have been learned.
Question:
Is there any simpler way to simulate a nonlinear continuous time model?
Is there an alternative way to turn the model to discrete?
Nonlinear simulation seems to be so sensitive to against everything.
EDIT:
Here is the code. Assume that you know A, B and sample time h.
% Compute sizes
a1 = size(A,2) + size(B,2) - size(A,1);
b1 = size(A,2);
a2 = size(A,2) + size(B,2) - size(B,1);
b2 = size(B,2);
% Compute square matrix
M = [A B; zeros(a1, b1)  zeros(a2, b2)];
M = expm(M*h);
% Find the discrete matrecies
Ad = M(1:size(A,1), 1:size(A,2));
Bd = M(1:size(B,1), (size(A,2) + 1):(size(A,2) + size(B,2)));


text:
Q: Iframe with ruby in rails I am used geocoder gem
How can i put iframe insted of image_tag ?
 <%= image_tag "http://maps.google.com/maps/api/staticmap?size=450x300&sensor=false&zoom=16&markers=#{@presale.latitude}%2C#{@presale.longitude}", width: "300", height:"200" %>

I want the same code but with iframe please help me

A: try this one
<%= content_tag(:iframe,'', width: 300, height: 200, src: "http://maps.google.com/maps/api/staticmap?size=450x300&sensor=false&zoom=16&markers=#{@presale.latitude}%2C#{@presale.longitude}") %>


text:
Q: Call to xindy failed due to double path on windows I have a problem with makeglossaries after installing MikTex on my windows10 machine. pdflatex and biber work perfectly fine, yet when calling makeglossaries it fails with the following error message:
$makeglossaries Main
makeglossaries version 4.36 (2018-03-07)
added glossary type 'main' (glg,gls,glo)
xindy  -L english -C duden-utf8 -I xindy -M "Main" -t "Main.glg" -o "Main.gls" "                                                                       Main.glo"
/d/local/thesis/C:/Program Files/MiKTeX2.9/scripts/xindy/../../xindy                                                                       /modules: No such file or directory at C:\Program Files\MiKTeX2.9\scripts\xindy\                                                                       xindy.pl line 402.

***Call to xindy failed***

Check 'Main.glg' for details

I checked out wolfie's Answer but find that this was already implemented in the xindy script.
The error seems to be that the path is concatenated in the $real_cmd variable in the script on line 372.
Any ideas on how to fix this?
Here is a striped down version of my latex setup:
Main.tex:
\documentclass[
 11pt,
   english,
   a4paper,
   DIV=11,
   listof=numbered,
]{scrreprt}

% -------------------------------------------------------------------------
\setlength{\parskip}{0.75em}
\usepackage{geometry}
\geometry{bindingoffset=0.5cm,hmarginratio=3:4, bottom=4.5cm}

\widowpenalty10000
\clubpenalty10000

%---- PACKAGES ----
%\usepackage{hyperref}
\usepackage[hidelinks]{hyperref}

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage[T1]{fontenc}
\usepackage{textcomp}
\usepackage{lmodern}
\usepackage{pdfpages}
\pdfminorversion=7
\usepackage{graphicx}

\usepackage{tabularx}
\usepackage{hhline}
\renewcommand\arraystretch{1.1}
\makeatletter
\newcommand{\thickhline}{
    \noalign {\ifnum 0=`}\fi \hrule height 1pt
    \futurelet \reserved@a \@xhline
}
\makeatother

\def\hyph{-\penalty0\hskip0pt\relax}

\usepackage{xcolor}

\definecolor{bostonuniversityred}{rgb}{0.8, 0.0, 0.0}

% This is the interesting part I guess -------------------------------
\usepackage[section=section,numberedsection=autolabel,toc,nonumberlist,xindy]{glossaries}
\GlsSetXdyCodePage{duden-utf8}
\makeglossaries
\input{glossary.tex}
% -----------------------------------------------------------------

\usepackage[chapter]{minted}
\usepackage{scrhack}
\usepackage{listings}

\renewcommand{\listingscaption}{Code Snippets}
\renewcommand{\listoflistingscaption}{List of Code Snippet}

\usepackage[german=quotes]{csquotes}
\MakeOuterQuote{"}

%---- BIBLIOGRAPHY ---
\usepackage[block=ragged,backend=biber,bibstyle=ieee]{biblatex}
\addbibresource{Bibliography.bib}

\makeatletter
\def\blx@maxline{77}
\makeatother

\begin{document}

         \gls{someEntry}
         \gls{someEntry2}

    \newpage
    \printglossary[title=Glossary]
\end{document}

glossary.tex:
\newglossaryentry{someEntry}{
    name={Some Entry},
    description={Some Description}
}
\newglossaryentry{someEntry2}{
    name={Some Entry 2},
    description={Some Description 2}
}

In the resulting pdf File the name is visible, so it read the glossary file correctly, but was not able to print it due to the makeglossaries command failing.

A: I digged a bit deeper and found a partial solution. Since I don't have enough karma yet, I cannot post this as comments though (and I am not sure it would be the right way).
xindy.pl line 372 reads:
our $real_cmd = Cwd::realpath($0);

If I add
print "real_cmd: $real_cmd\n";

after that, it prints
real_cmd: /c/Users/username/Desktop/TeX/auxdir/C:/Program Files/MiKTeX 2.9/scripts/xindy/xindy.pl

which is wrong.
Putting these lines into a test file named test_Cwd.pl:
#!/usr/bin/perl -w
use Cwd;
our $real_cmd = Cwd::realpath($0);
print "real_cmd: $real_cmd\n";

Output with windows paths:
$ C:\\Users\\username\\Desktop\\test_Cwd.pl
real_cmd: /c/Users/username/Desktop/C:/Users/username/Desktop/test_Cwd.pl

Output with emulated unix paths on Windows:
$ /c/Users/username/Desktop/test_Cwd.pl
real_cmd: /c/Users/username/Desktop/test_Cwd.pl

This difference in behavior of perl is know and described in https://stackoverflow.com/a/46773471.
Possible solutions:

*

*Fix C:\Program Files\MiKTeX 2.9\miktex\bin\x64\xindy.exe to execute perl with /c/Program\ Files/MiKTeX\ 2.9/scripts/xindy/xindy.pl on msys. I don't know how to do this as I am unable to find the package providing xindy.exe.

*Fix C:/Program Files/MiKTeX 2.9/scripts/xindy/xindy.pl to convert the Windows-style path to a Unix-style path (dirty hack, done below)

*Fix the perl interpreter's Cwd package to convert Windows-style paths to Unix-style paths (general solution, may break other code)

Msys and Cygwin also have the cygpath utility which does help creating a workaround:
You'll need to fix platform detection in xindy.pl first, see https://sourceforge.net/p/xindy/feature-requests/47/.
Then replace xindy.pl line 372, which looks like this
our $real_cmd = Cwd::realpath($0);

by
our $real_cmd = "";
if ( $is_w32 ) {
    our $cygpath_cmdline = "cygpath \"$0\"";
    our $unixified_cmd_path = `$cygpath_cmdline`;
    $unixified_cmd_path =~ s/\r//g;
    $unixified_cmd_path =~ s/\n//g;
    our $real_cmd = Cwd::realpath($unixified_cmd_path);
} else {
    our $real_cmd = Cwd::realpath($0);
}

But then xindy-lisp.exe will fail reading the tempdir filename:
*** - PARSE-NAMESTRING: syntax error in filename
  "\"/c/Users/username/Desktop/TeX/auxdir/FVWzOBrFBF\"" at position 0

This file does exist, but xindy-lisp.exe seems to expect the filename without \" but with single double quotes instead. Manually editing the commandline and removing \" gets me further. When parsing the temporary file and reading other paths from there, it fails again.
I am using perl from git-bash (msys, 64Bit) with MiKTeX 64Bit on Windows 7. All software is updated to its latest version afaik, except maybe perl.
$ perl --version

This is perl 5, version 26, subversion 1 (v5.26.1) built for x86_64-
msys-thread-multi

PS: my perl code may be bad style as I am new to perl. Suggestions are welcome!


text:
Q: Create a service inside Thread or Thread inside Service What is recommended to do for networking job that should fetch and update new data? I see different answers on that issue.
To create a Service that will run inside a new Thread that should make all the network job OR to create a new Thread that will start a Service inside that Thread?

A: You can't make a Service that runs inside a Thread, so that possibility is impossible.  You need a Thread (or AsyncTask) to do any network request.  If you want the app to continue to do network requests even if the current Activity is finished, then yes you need to create that Thread (or AsyncTask) in a Service.

A: In android all The network operations are to be done within a thread. Even if you are creating a service all network operations will be done within a thread.
Service within a thread is not possible.
Now if You want your network operations to be available in multiple activities you should create a service otherwise A separate network thread within an activity will do the job.

A: IntentService initializes on the main thread in onCreate and runs in a separate thread otherwise. No need to deal with extra threads in this case. A Service runs in the main thread and requires that you handle the threading (if needed). It would be best to prototype an IntentService since you're just making a network call. If the network call is short, then just use an AsyncTask.

A: I think you need IntentService. No need to confuse on Service inside Thread. Start Service inside background thread or start a service with background thread .Both are same.

A: It is always better to call thread inside service rather than service inside thread because service is a component of android so it is having some priority level. On the other hand Thread is not a part of Android component so it is having no priority compared to service.
So in case of low memory when Android system starts killing application, it will first kill thread that contains the service because of its lower or no priority. And if you have used Service containing thread then you are good. Hope it helps :)


text:
Q: Angular Material 2 - Expansion Panel Tracking I have a an angular material expansion panels which are being loaded via an array of objects.  I need the key of the object chosen when the expansion panel header is chosen (clicked). So I can then use this chosen object to load data within the panel itself?
Not sure where to start?


text:
Q: iOS project private and public dependencies I have a git-managed iOS application (built mostly in Swift, Xcode 6 beta 4) for which I would like to pull some code out into a git subtree. The code for that is all in a "Common" directory. The problem is, that the "Common" code depends on a Cocoapod (ObjectiveRecord, which depends on ObjectiveSugar).
Under these circumstances, what would be the best way to manage these pieces independently? Ideally, I would like to be able to keep my commit history, although I could stand to lose it if it would make things easier.
I have two ideas that seem like they might work, although I do not know how to go about implementing them:

*

*Have my iOS app depend on a git subtree of the Common code, and that subtree also depend on a subtree of ObjectiveRecord (EDIT: and stop using CocoaPods)

*Have my iOS app depend an a private CocoaPod of my common code, and that CocoaPod also depend on a CocoaPod of ObjectiveRecord.

I would like to be able to make changes to the common code from anywhere and keep the changes everywhere. For instance, if I have the workspace for App1 that has a subtree of Common, and I edit Common from there, I can commit and have App2 pull in the Common changes (and vice versa). Or if I just have the workspace for Common open, edit it there and App1, App2, etc. can all pull in the Common changes — similar to SVN externals.
I have tried this tutorial: http://makingsoftware.wordpress.com/2013/02/16/using-git-subtrees-for-repository-separation/, but to no avail.
Any help would be greatly appreciated.
Thank you!
EDIT:
I ended up going with the private local CocoaPod option. The only problem I am having now is that in Xcode 6 beta 4, "using bridging headers with framework targets is unsupported". Hopefully that will be fixed in beta 5.


text:
Q: question about total variation (measure theory) suppose $v$ is a signed measure on $(X,M)$ and $E\in M$
how do i go about showing that $|v|(E)=sup\{\sum_1^n |v(E_j)|: E_j\cap E_i=0 \forall i\neq j, \cup_1^n E_j=E\}$
sorry it took me awhile to fix the latex

A: Hint: Consider the Hahn Decomposition Theorem, which allows us to split $X$ into a positive and negative set for $\nu$.  That is, we may write $X=P\cup N$, $P\cap N=\emptyset$ where $P$ is a positive set for $\nu$ and $N$ is a negative set for $\nu$.


text:
Q: How to disable custom plugin in admin I have created a custom module to disable free shipping based on some conditions. I have to used
Custom/ShippingRule/Plugin/Magento/Shipping/Model/Shipping.php to do the functionality.
It is working fine now. I want to enable/disable this from admin.

A: I am not sure about the 100% solution. But might below one can be a solution.
Suppose your di.xml which is exist at app/code/{vendor}/{moduleFolder}/etc folder.
<?xml version="1.0"?>
<config>
    <type name="{ObservedType}">
      <plugin name="my_plugin_name" type="{PluginClassName}" sortOrder="1" disabled="false" />
    </type>
</config>

To disable this plugin  at adminhtml area, create di.xml at app/code/{vendor}/{moduleFolder}/etc/adminhtml and  disabled that plugin by plugin name my_plugin_name like below:\
<?xml version="1.0"?>
<config>
    <type name="{ObservedType}">
      <plugin name="my_plugin_name"  disabled="true" />
    </type>
</config>

A: For that you have to create system.xml file in your module.
Path for this file is app/code/{vendor}/{modulename}/etc/adminhtml/system.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="tab_id" translate="label" sortOrder="10">
            {vendor}
        </tab>

            <class>separator-top</class>
            XYZ
            <tab>tab_id</tab>
            <resource>Vendor_Modulename::sectionid_config</resource>
            <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
                General Configuration
                <field id="enable" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
                    Module Enable
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
            </group>

    </system>
</config>

Now you have to set default value
for that create config.xml file at app/code/{vendor}/{modulename}/etc/config.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <sectionid>
            <general>
                <enable>1</enable>
                <display_text>XYZ</display_text>
            </general>
        </sectionid>
    </default>
</config>

This will display configuration in admin. After that you have to fetch value of enable/disable in controller using helper.

A: You can apply your code under this below condition.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('Magento\Framework\App\State');
if($state->getAreaCode() != 'backend')
{
  /* apply your code in here */
}


text:
Q: RTSP stream doesn't work on python, But does on VLC. why? I am trying to get my PTZ camera to stream using python 3 and openCV.
The URL i use in the code works with VLC stream but not with the code.
import cv2
import numpy as np

cap = cv2.VideoCapture(src="rtsp://USER:PASS@XX.XXX.XXX.XXX:XXX/Streaming/Channels/101/")
FRAME_WIDTH = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
FRAME_HIGTH = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print('Frame Size: ', FRAME_WIDTH, 'x', FRAME_HIGTH)

if cap.isOpened():
    ret, frame = cap.read()
else:
    ret = False

while ret:
    ret, frame = cap.read()
    cv2.imshow('Camera', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

When I run it i get the next error:
Traceback (most recent call last):   File "C:/Users/.../CameraTest/TEST.py", line 4, in <module>
    cap = cv2.VideoCapture(src="rtsp://.../Streaming/Channels/101/") TypeError: Required argument 'index' (pos 1) not found

this is and HIKVISON PTZ camera.
Can I please get any tips for how to get her to stream.
TNX in advance.

A: one small change, remove src= from the cv2.VideoCapture() method.
It should look like,
cap = cv2.VideoCapture("rtsp://USER:PASS@XX.XXX.XXX.XXX:XXX/Streaming/Channels/101/")

A: This is working for me in Hikvision camera. Avoid using special letter in the password.
import cv2
cap = cv2.VideoCapture('rtsp://username:password@10.199.27.123:554')
while True:
    ret, img = cap.read()
    cv2.imshow('video output', img)
    k = cv2.waitKey(10)& 0xff
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()


text:
Q: Unable to Delete Using Laravel's Policy I am logged in as user2 and would like to see the delete button on user2's review (screenshot). However, the button did not appear. I am using Laravel's policy.

I have attached my blade code below:
@foreach($reviews as $review)
{{--
     --}}

{{ $review->title }}

User {{ $review->user_id }}

{{ $review->review }}

    id }}" class="card-link">Edit
    {{-- Another link --}}

    @can('delete', $review)
    Delete
    @endcan

Here is my ReviewPolicy code snippet:
public function delete(User $user, Review $review)
    {
        return $user->id === $review->user_id;
    }

Here is my route:
Route::get('/delete/{id}', 'App\Http\Controllers\UserController@deleteReview')->middleware('user');

And lastly, here's the AuthServiceProvider:
protected $policies = [
            'App\Models\Review' => 'App\Policies\ReviewPolicy',
        ];

To my understanding, the deletability of the review lies in ReviewPolicy and that was where I tried to tweak the code, but to no success. Not exactly sure where I have gone wrong.


text:
Q: How to arrange subgroups in a grouped barplot in R in ascending number in R I have a dataset that I am trying to create a grouped bar chart. The groups are  before and after timepoints, and the subgroups are 6 different devices. The before only has 3 of the 6 subgroups, while the after has all 6 of the subgroups. I am having two main issues: getting the code to arrange the subgroups in ascending order, and having the "Before" group on the left of the plot compared to the "After" group.
Below is the code that I have for dataset FDA_co_tier:
library(tidyverse)
library(ggplot2)

F_dev_dec <- FDA_co_tier%>%
  select(device_type, year_approved) %>%
  mutate(year_2015 = if_else(year_approved >= 2015, "after", "before")) %>%
  mutate(year_2015 = factor(year_2015, levels=c("before", "after"))) %>%
  group_by(device_type, year_2015) %>%
  summarise(N=n()) %>%
  mutate(N= factor(N, levels = N))

which gives me a table of:
`summarise()` has grouped output by 'device_type'. You can override using the `.groups` argument.
# A tibble: 9 x 3
# Groups:   device_type [6]
  device_type         year_2015 N
  <chr>               <fct>     <fct>
1 Accessories         after     6
2 Aspiration_catheter before    4
3 Aspiration_catheter after     32
4 Guidewire           before    3
5 Guidewire           after     23
6 Microcatheter       after     7
7 Sheath              after     19
8 Stentretriever      before    17
9 Stentretriever      after     22

I made both the year_2015 variable and the N variable as factors, and tried to set the year_2015 levels with "before" then "after".
As mentioned above, I want to plot the different devices in Bars for the "Before" and "After" points in ascending order of n. To do this, I initially tried:
F_dev_dec %>%
  ggplot(aes(x= year_2015, fill= device_type)) +
  geom_bar(position = position_dodge()) +
      labs(title = NULL,
           x= NULL,
           y= "Count (n)")

which gave me this graph: [1]: https://i.stack.imgur.com/NAM8i.png
Not sure exactly why this has the correct groups ("Before", "After" but all the device subgroups go to 1, like its calculating some odd percentage. I
I next tried to adjust the code and not summarize and not double group the data table by device and year_2015:
F_dev_dec <- FDA_co_tier%>%
  select(device_type, year_approved) %>%
  mutate(year_2015 = if_else(year_approved >= 2015, "after", "before")) %>%
  mutate(year_2015 = factor(year_2015, levels=c("before", "after"))) %>%
  group_by(device_type, year_2015)

then using the same code for the ggplot above, I get something a little closer, but not in ascending order of n for the subgroups : https://i.stack.imgur.com/wSm5L.png
After further attempts of trial and error not getting this, the only way Ive been able to get the plot to look like I want was with this code:
F_dev_dec <- FDA_co_tier%>%
  select(device_type, year_approved) %>%
  mutate(year_2015 = if_else(year_approved >= 2015, "before", "after")) %>%
  mutate(year_2015 = factor(year_2015, levels=c("before", "after"))) %>%
  group_by(device_type, year_2015) %>%
  summarise(N=n())

`summarise()` has grouped output by 'device_type'. You can override using the `.groups` argument.
# A tibble: 9 x 3
# Groups:   device_type [6]
  device_type         year_2015     N
  <chr>               <fct>     <int>
1 Accessories         after         6
2 Aspiration_catheter before        4
3 Aspiration_catheter after        32
4 Guidewire           before        3
5 Guidewire           after        23
6 Microcatheter       after         7
7 Sheath              after        19
8 Stentretriever      before       17
9 Stentretriever      after        22

F_dev_dec %>%
  ggplot(aes(x= year_2015, y= N, fill= reorder(device_type, N))) +
  geom_bar(data=F_dev_dec %>% filter(year_2015 == "before"), width=0.9, position = position_dodge(),  stat = "identity") +
  geom_bar(data=F_dev_dec %>% filter(year_2015 == "after"), width=0.5, position = position_dodge(),  stat = "identity") +
  scale_x_discrete(labels = c("Before", "After")) +
  theme_classic()+
  labs(title = NULL,
       x= NULL,
       y= "Count (n)")

Which gives the Plot im looking for: https://i.stack.imgur.com/KHfzk.png
Of note: in the code immediately above, the mutation of FDA_co_tier to generate the variable year_2015 keeps messing up the final plot. When I attempt do the mutation correctly with  mutate(year_2015 = if_else(year_approved >= 2015, "after", "before")), the final plot looks like this: https://i.stack.imgur.com/G4vyU.png
The data table gets reversed (values that should be "before" are labeled as "after" 2015 and values "after" are labeled as "before"). Its more annoying that anything as the groups all still contain the same values, but the labels are wrong, so I had to write in the scale_x_discrete(labels = c("Before", "After")) line to correct the plot.
Any advice on how to fix the issue with getting the subgroups in correct ascending number and whats going on with the code to generate the plot would be much appreciated!

A: You need to set the appropriate levels for the device_type variable. The easiest way to do it is this way.
library(tidyverse)

F_dev_dec = read.table(
  header = TRUE,text="
device_type         year_2015 N
 Accessories         after     6
 Aspiration_catheter before    4
 Aspiration_catheter after     32
 Guidewire           before    3
 Guidewire           after     23
 Microcatheter       after     7
 Sheath              after     19
 Stentretriever      before    17
 Stentretriever      after     22
") %>% as_tibble()

F_dev_dec = F_dev_dec %>%
  group_by(year_2015) %>%
  arrange(N) %>%
  mutate(
  year_2015 = year_2015 %>% factor(c("before", "after")),
  device_type = device_type %>% fct_inorder()
)

F_dev_dec %>%
  ggplot(aes(x= year_2015, y= N, fill= reorder(device_type, N))) +
  geom_bar(data=F_dev_dec %>% filter(year_2015 == "before"), width=0.9, position = position_dodge(),  stat = "identity") +
  geom_bar(data=F_dev_dec %>% filter(year_2015 == "after"), width=0.5, position = position_dodge(),  stat = "identity") +
  scale_x_discrete(labels = c("Before", "After")) +
  theme_classic()+
  labs(title = NULL,
       x= NULL,
       y= "Count (n)")

Note the following order of commands first arrange(N) and then device_type = device_type %>% fct_inorder ().
P.S.
You may have shared your FDA_co_tier data table with us. Without it, I had to read the summary using read.table.
Update 1
Phew! I got a bit tired to get the effect you expect. But in the end it worked. Let's see what we have here. First, I will work on your completed data. I made them the same for myself.
library(tidyverse)

FDA_co_tier = tibble(
  device_type = c(rep("Accessories", 6),
                  rep("Aspiration_catheter", 36),
                  rep("Guidewire", 26),
                  rep("Microcatheter", 7),
                  rep("Sheath", 19),
                  rep("Stentretriever", 39)),
  year_2015 = c(rep("after", 6),
                rep("before", 4),
                rep("after", 32),
                rep("before", 3),
                rep("after", 49),
                rep("before", 17),
                rep("after", 22)))

output
# A tibble: 133 x 2
   device_type         year_2015
   <chr>               <chr>
 1 Accessories         after
 2 Accessories         after
 3 Accessories         after
 4 Accessories         after
 5 Accessories         after
 6 Accessories         after
 7 Aspiration_catheter before
 8 Aspiration_catheter before
 9 Aspiration_catheter before
10 Aspiration_catheter before
# ... with 123 more rows

Now let's create a plot. Note one clever line of code geom_bar (position = position_dodge (), alpha = 0)), it does not display anything, it only sets the expected order of the variable year_2015.
FDA_co_tier %>%
  mutate(
    year_2015 = year_2015 %>% factor(c("before", "after")))  %>%
  ggplot(aes(year_2015, fill=device_type))+
  geom_bar(position = position_dodge(), alpha=0)+
  geom_bar(data = . %>%
             filter(year_2015 == "before") %>%
             mutate(device_type = device_type %>% fct_infreq() %>% fct_rev()),
           position = position_dodge())+
  geom_bar(data = . %>%
             filter(year_2015 == "after") %>%
             mutate(device_type = device_type %>% fct_infreq() %>% fct_rev()),
           position = position_dodge())


text:
Q: Combine two or more DensityPlot3Ds with different color schemes I have two DensityPlot3D objects where the opacity and coloring are both physically meaningful, and I'm looking for a way to overlap them so that the resulting opacity/color is visually combined in an intuitive way.  Thus, I'm pretty sure that combining them into one DensityPlot3D is not an option.
For example, consider the eigenmodes in the following situation:
reg = DiscretizeRegion[
           ImplicitRegion[-1 <= x <= 1 && -1 <= y <= 1 && -1 <= z <= 1, {x, y, z}]]

{vals, funcs} =
   NDEigensystem[
      {Laplacian[u[x, y, z], {x, y, z}], DirichletCondition[u[x, y, z] == 0, True]},
      u, {x, y, z} ∈ reg, 4]

g1 = DensityPlot3D[funcs[[2]][x, y, z], {x, y, z} ∈ reg,
 ColorFunction -> "SunsetColors", Boxed -> False, Axes -> False, ViewPoint -> {3, 2, 3}];

g2 = DensityPlot3D[funcs[[3]][x, y, z], {x, y, z} ∈ reg,
 ColorFunction -> "RoseColors", Boxed -> False, Axes -> False, ViewPoint -> {3, 2, 3}];

What I want is to be able to combine these two graphics in such a way that in the regions where the densities overlap the combined color/opacity is somehow the sum or product or some other meaningful combination of the individual densities, but maintaining the different color schemes for the two modes (ie, not one unified DensityPlot3D with a common color function and opacity scaling).
I could see calculating an effective color and opacity value at discrete points in the region, but there does not seem to be a way to define a color function or opacity function that depend on position as well as "value".
EDIT:
Things that don't work:
DensityPlot3D[funcs[[2]][x, y, z], {x, y, z} ∈ reg, ColorFunction -> Function[{x, y, z, f}, <anything>]]

(fails because ColorFunction doesn't work that way for DensityPlot3D)
DensityPlot3D[{funcs[[2]][x, y, z],funcs[[3]][x, y, z]}, {x, y, z} ∈ reg]

(displays nothing)
Show[g1, g2]

(only shows g1, because it rasterizes first)
Blend[{g1,g2}]

(rasterizes and then applies the same opacity at every pixel)

A: Here's an answer.  It's a long workaround, so I'll happily accept another answer that takes advantage of simple, built-in functionality. First I construct tables of (rescaled/normalized) function values for funcs[[2]] and funcs[[3]] called r1 and r2, respectively. Then I make my own table of RGBColor values with opacity as the sum of squares of the function values (there's probably a more elegant way to do that than what I came up with, too).
colorTable = Table[RGBColor[
Join[List @@ (Blend[{
    Blend[{Red, Yellow}, r1[[x, y, z]]],
    Blend[{Green, Yellow}, r2[[x, y, z]]]}]),
    {Norm[{r1[[x, y, z]], r2[[x, y, z]]}]^2}]],
{x, 1, Dimensions[r1][[3]]}, {y, 1, Dimensions[r1][[2]]}, {z, 1, Dimensions[r1][[1]]}];
Image3D[colorTable]

This is pretty much what I'm looking for.  Thanks to Szabolcs for the encouragement.


text:
Q: Should commas be used in this sentence?
Various kinds of meat and fish in the bazaar were found by the cook.

In the sentence, should commas be used before and after the phrase 'in the bazaar'? If commas is used there, the phrase is an adverb. If not, it is an adjective, I think.

A: Your sentence as it stands is fine without commas

Various kinds of meat and fish in the bazaar were found by the cook.

If you insisted on using commas, you might write

In the bazaar, various kinds of meat and fish were found by the cook.
  The cook found, in the bazaar, various kinds of meat and fish.

A: The sentence of yours is correct and no comma is required.
However, if you really want to add a comma then your sentence could be written in this way,

Various kinds of meat, and fish in the bazaar were found by the cook.

Other than this, there's no possible place in the sentence where you can add a comma.


text:
Q: How to use Zend Auth to make values globally available in each action & layout.phtml I have implemented Zend Auth by creating a getServiceConfig()-like AuthenticationService Object in Module.php:
'AuthService' => function($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'tblUSRUsers', 'Email', 'Password', "MD5(?)");

                    $authService = new AuthenticationService();
                    $authService->setAdapter($dbTableAuthAdapter);
                    $authService->setStorage($sm->get('Application\Model\MyAuthStorage'));

                    return $authService;
                },

In the controller action, I am getting this object by
$this->getServiceLocator()
                    ->get('AuthService');

For authentication I obtain the values using
$authservice    = $this->getServiceLocator()->get('AuthService');
$arrUserDetails = $authservice->getIdentity();

Its working fine, these values are available.
But the problem is that ServiceLocator is not available in the Controller constructor so can't write the above code there. Writing this code in each and every action doesn't seem to be a good practice.
Could anyone help out with this?

A: There are a couple of ways to do it. You can overload the ControllerConfig method in the Module class so you can instantiate the controllers however you like. Or you can write a controller plugin that will handle the authentication & return the identity.
EDIT
Should have provided these links earlier, but didn't have much access from the phone ;).
To understand ControllerConfig take a look at this blog post. There's an explanation about half way down of the getControllerConfig method in the Module class. This is a method the Module Manager looks for when instantiating the Module classes which allows you to customize the instantiation of a Controller in that Module. Once you return the Controller class, the Controller Manager then injects the rest of the Controller dependencies (plugins, etc.)
Controller plugins are small classes that get injected to every controller and which can be invoked from an action to do some common bit of code. When you use $this->getServiceLocator() in a controller action, you're using a plugin.

A: Possible solution would be to have a route event handler, where you set user credentials:
class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager = $e->getApplication()
            ->getEventManager ();

        $eventManager->attach (
            MvcEvent::EVENT_ROUTE,
            function  (MvcEvent $e)
            {
                $auth = $e->getApplication()
                          ->getServiceManager()
                          ->get('AuthService');

                $e->setParam('userinfo', $auth->getUserInfo());
                // update
                $layout = $e->getViewModel();
                $layout->userinfo = $auth->getUserInfo();
       });
    }

and then access then in the controller like this:
class IndexController extends AbstractActionController
{
    public function indexAction ()
    {
        $this->getEvent()->getParam('userinfo');


text:
Q: Just solved a problem, not on StackOverflow, but would like to share the solution
Possible Duplicate:
Should I ask a question I know the answer to?

I just spent a few hours solving a problem, but it wasn't on StackOverflow. StackOverflow seems like a good place to post the result, but since it's already answered, it isn't really a question any more. Is it still ok to post the question and answer on StackOverflow, or is there a better place to do that?

A: You're encouraged to go ahead and ask the question and answer it yourself if it isn't already on Stack Overflow somewhere.  Do a search first, but ask and answer away if you don't find it.
Note that you'll even get the Self-Learner Badge if your answer is upvoted 3 or more times.

A: I guess it's okay to post it here.
It's the "blog" part of Stack Overflow (see about page)

A: You can always post the question and if you don't get the response/answer from someone else right away, you can then post the solution yourself as an answer.
Just make the question/problem statement real...


text:
Q: Syntax error on tokens, delete these tokens Here is my code that has been giving the problems.
package ca.rhinoza.game;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;

import javax.swing.JFrame;

public boolean running = false;

public class Game extends Canvas implements Runnable {

    private static final long serialVersionUID = 1L;

    public static final int WIDTH = 160;
    public static final int HEIGHT = WIDTH / 12 * 9;
    public static final int SCALE = 3;
    public static final String NAME = "Game";

    private JFrame frame;

    public Game(){
        setMinimumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
        setMaximumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
        setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));

        frame = new JFrame(NAME);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        frame.add(this, BorderLayout.CENTER);
        frame.pack();

        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public synchronized void start(){

        new Thread(this).start();

    }

    public synchronized void stop(){

    }

    public void run() {

    }

    public static void main(String[] args){

        new Game().start();
    }

}

I have no idea why it is doing this.
Edit:
I edited as per your request to see more code.

A: You put
public boolean running = false;

outside of a class definition, effectively in the global namespace. But there are no globals in Java. This is not legal.
I'll say, that's a strange error message for that though. I would expect a little more from the compiler. Something to the effect of class or interface or enum because once you start the statement with public there are exactly three legal things that can follow. But, it is what it is. So, the compiler is right to complain, I just would have expected a more informative error message.

A: You are declaring a field outside of the class:
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;

import javax.swing.JFrame;

public boolean running = false; /// <=============== invalid location

public class Game extends Canvas implements Runnable { // <==== class starts here
    private static final long serialVersionUID = 1L;

    public static final int WIDTH = 160;
    public static final int HEIGHT = WIDTH / 12 * 9;
    public static final int SCALE = 3;
    public static final String NAME = "Game";
    ...

It must be placed inside a class:
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;

import javax.swing.JFrame;

public class Game extends Canvas implements Runnable { // <==== class starts here

    public boolean running = false; /// <=============== valid location

    private static final long serialVersionUID = 1L;

    public static final int WIDTH = 160;
    public static final int HEIGHT = WIDTH / 12 * 9;
    public static final int SCALE = 3;
    public static final String NAME = "Game";
    ...


text:
Q: Check if loaded assembly is domain neutral I've installed a few assemblies in GAC. Now, I'm loading them dynamicly in separate AppDomains.
Is there way to check if they are loaded as domain neutral assemblies?

A: I found the solution by myself. Just use Process Explorer, get details of the process and then go to .Net Assemblies tab. But it need to run Process Explorer as administartor.


text:
Q: Convergence of the size of largest component in subcritical Erdos Renyi graph Considering an Erdos Renyi random graph with $p = \frac{\lambda}{n}$ and $\lambda < 1$, I am trying to show that $ \frac{|C_{max}|}{log (n)} $ approaches  $ \frac{1}{I_{\lambda}} $ in probability, where $|C_{max}|$ is the size of the largest component and $I_\lambda = \lambda -1 - log(\lambda)$.
So I should show that:
$$ \lim_{n \to \infty} P(|\frac{|C_{max}|}{log (n)} - \frac{1}{I_{\lambda}}| > \epsilon) = 0 $$
I think I should use the upper and lower bounds on the largest subcritical component, i.e. $P(|C_{max}|\ge a log(n)) = O(n^{-\delta})$ if $ a > \frac{1}{I_\lambda} $ and $P(|C_{max}|\le a log(n)) = O(n^{-\delta})$ if $ a < \frac{1}{I_\lambda} $, which means that $|C_{max}| \approx \frac{1}{I_\lambda}log(n)$. Then rewriting the equation above:
$$ \lim_{n \to \infty} P(||C_{max}| - \frac{1}{I_{\lambda}} log (n)| > \epsilon log (n)) = 0 $$
Then I should be able to use Chebyshev's inequality, but I'm not sure if this approach is valid until now and I don't know what the variance of $|C_{max}|$ is.

A: So you're not interested in proving those upper and lower bounds, just in using them to prove convergence in probability?
For that, you don't need any extra knowledge of the random graph. For any $\epsilon>0$, the first bound says that we have
$$
 \Pr[|C_{\max} > (\tfrac1{I_\lambda} + \epsilon)\log n] = O(n^{-\delta})
$$
(presumably for some $\delta>0$ depending on $\epsilon$) which we can rewrite as
$$
 \Pr\left[\frac{C_{\max}}{\log n} - \frac1{I_\lambda} > \epsilon\right] = O(n^{-\delta})
$$
and this goes to $0$ in the limit as $n \to \infty$. Similarly, the second bound tells us that
$$
   \Pr[|C_{\max}| < (\tfrac1{I_\lambda} - \epsilon)\log n] = O(n^{-\delta})
$$
and this can be rewritten as
$$
 \Pr\left[\frac{C_{\max}}{\log n} - \frac1{I_\lambda} < -\epsilon\right] = O(n^{-\delta})
$$
which also goes to $0$ in the limit as $n \to \infty$. Finally, the probability you were looking for,
$$
 \Pr\left[\left|\frac{C_{\max}}{\log n} -\frac1{I_\lambda}\right| > \epsilon\right],
$$
is the sum of the two probabilities above, so its limit is also $0$.


text:
Q: String replace not working in function string input= "hello, how are you tod&#97y"
i knw the encode is not in proper format thats why i am using a function to replace improper "tod&#97y" to "today".
f1(input);
but at time of comparing
if  (input.Contains("today") == true)
{
    lbldisplay.Text = str1;
}

it returing false,i have debugged the program.it is working correctly till replace s1.Replace("&#97","a");(shown "hello, how are you today") but at return statement return s1; it is returning original value i.e "hello, how are you tod&#97y".
public string f1(string s1)
{
    s1 = s1.Replace("&#97", "a");
    return s1;
}

please help.thank you.

A: Most likely what is happening is that you're not assigning the return value back to your variable when you call it.  The parameter is not declared ref so this will have no effect:
f1(input);

You would need to use this:
input = f1(input);


text:
Q: call member function out of Yii? I know it's not legal, and looking odd. But it's necessary for me.
I have two projects, one is custom Open-Cart, and the second is in Yii. My main project is opencart. My Yii project is kept in the Main project root.
Now I want to call a Yii function in my open cart.
please anyone help me and tell How to call the Yii function in my main project?
this is my Yii function:-
   $sm=Yii::app()->getSecurityManager();

    if ($salt === null)
        $salt = Yii::app()->params['password_security_salt'];
    if($salt==null)
        $salt=md5 (mt_rand ().mt_rand ().mt_rand ().mt_rand ());
    $pass=sha1($salt.$pass.$salt);
    return $sm->hashData($pass,$key).':'.$salt;

.....................
I want to create a new function manually for my opencart project.
please help me for creating a new project for the same functionality as Yii (upper function) function.

A: You can use Yii functionality outside of the Yii project by initialising the application like so:
// this is in someotherfile.php outside of the yii project
require_once('framework/yii.php');
$config = require_once('protected/config/main.php');
Yii::createWebApplication($config);

// call your function
Yii::app()->getSecurityManager();

Obviously the paths to the yii.php file and the application config (main.php) will need to change to fit your project structure


text:
Q: GenericPrincipal IsInRole returns false for HttpContext.User I have a credential method to set user credentials via GenericPrincipal. I am using asp.net MVC
    public void SetCredentials(HttpContextBase context, string username, bool createPersistenceCookie)
    {
        FormsAuthentication.SetAuthCookie(username, createPersistenceCookie);

        IIdentity identity = new GenericIdentity(username);
        IPrincipal principal = new GenericPrincipal(identity,new []{"standart"});

        context.User = principal;
    }

I want to check User.IsInRole("standart") in controller action,  but it returns false.

*

*context.User.IsInRole("standart") //returns false

I want to use context.User in my application, but it returns always false.

A: I think you used asp.net membership api before. And now you want to create custom principal in your application.
When you send request to server, server uses a new clean HttpContext. So you lost your old informations. If you want to use old session informations is application, you shuld save your data in server or client side. You can do this two way.

*

*Client cookie

*Server session

I recommand you to use client cookies. Because data is being stored to client side, so you save server resources.
   public void SetCredentials(HttpContextBase context, string username, bool createPersistenceCookie)
    {
        var formsAuthenticationTicket = new FormsAuthenticationTicket(
            1,
            username,
            DateTime.Now,
            DateTime.Now.AddMilliseconds(FormsAuthentication.Timeout.TotalMilliseconds),
            createPersistenceCookie,
            roles
        );

        var encryptedTicket = FormsAuthentication.Encrypt(formsAuthenticationTicket);
        var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

        HttpContext.Current.Response.AppendCookie(authCookie);
    }

I sended encrypted cookie to client side. And I should check this cookie all incoming request to server application.
And now in Global.asax file:
    protected void Application_AuthenticateRequest(object sender, System.EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

        if (authCookie == null) return;

        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

        IIdentity identity = new GenericIdentity(ticket.Name);
        IPrincipal principal = new GenericPrincipal(identity, ticket.UserData.Split('|'));

        HttpContext.Current.User = principal;
    }

I hope solve your issue.


text:
Q: auto scroll in an ultragridview for infragistics I am using an Infragistics UltraGridView in my program. Is it possible to set it to automatically scroll the UltraGridView starting at top to the bottom and then resetting it back to the top? Also the UltraGridView is to be set as AutoRefresh. Any ideas?

A: You can simply build a tight loop as this
foreach (UltraGridRow row in grid.Rows)
{
    row.Activate();
}

But it is unclear what is your purpose for this code. Your user probably will not be able to understand anything of the data while it scrolls on the grid.
Instead if your point is to set a particular row as the first one in the grid area then you should work along the line of this
grid.ActiveRowScrollRegion.FirstRow = grid.Rows[500];

(Assuming that you have more than 500 rows of course)
If you want to slow down the scrolling then you could add a Timer and in the Tick event run the Activate call. In this context you could write a class like this
public class SlowScroller
{
    private UltraGridRow current = null;
    private UltraGrid grd = null;
    private System.Windows.Forms.Timer t = null;
    public SlowScroller(UltraGrid grid)
    {
         grd = grid;
         t = new System.Windows.Forms.Timer();
    }

    public void Start(int interval)
    {
        t.Interval = interval;
        t.Tick += onTick;
        t.Start();
    }

    public void Stop()
    {
        if (t.Enabled)
           t.Stop();
    }
    private void onTick(object sender, EventArgs e)
    {
        if(current == null)
            current = grd.Rows[0];
        else
            current = current.GetSibling(SiblingRow.Next);
        current.Activate();
    }
}

And call it with
SlowScroller ss = new SlowScroller(grid);
ss.Start(500); // Scroll every 500 milliseconds

Note the presence of the Stop method. This is necessary because you don't want this class to continue fire the Tick event even when you discard your form. Thus you need to call the Stop in the Form_Closing event handler


text:
Q: Execute Queries in sequence I have 5 queries
all are dependent on one by one
i have to run all queries in one time but it will be executed in sequence
it's possible..?
please help me

A: You can build a stored procedure and execute each query in desired order by placing the queries in corresponding execution order

A: you can use SSIS's sequence or process container to execute all of your SQL encapsulated in stored procedure at the same time, the provided screenshot show's processes in precedence,  but you can also design them to execute at the same time.

Hope this helps.
Cheers!

Imagination is more important than knowledge


text:
Q: Getting OData Count in ASP.NET Core WebAPI Using the sample code from Hassan Habib's Supercharging ASP.NET Core API with OData blog post, I am  able to get the record count using an OData query of $count=true:

What needs to be configured to get the response object to be wrapped in an OData context so that the @odata.count property will show?
In my own ASP.NET Core web API project, I cannot get the simple $count parameter to work and I have no idea why.
With Hassan's sample code, the response JSON is wrapped in an OData context and the payload (an IEnumerable<Student> object) is in the value property of the JSON response.   In my project, the OData context wrapper does not exist; my code never returns OData context, it only returns the payload object of type IEnumerable<T>:

I've also noticed that the Content-Type in the response header is application/json; odata.metadata=minimal; odata.streaming=true; charset=utf-8 in the sample project, where as it is simply application/json; charset=utf-8 in my project.  I don't see any setting that controls this in either project, so I'm assuming the Microsoft.AspNetCore.Odata NuGet package is magically changing the response when it's configured properly.
My project is also using .NET Core 2.2 (Upgraded from 2.1), all the same versions of NuGet packages as Hassan's sample projects, and all the same settings in the StartUp.cs class... although my StartUp.cs is way more complicated (hence the reason I'm not posting it's content here.)

A: I could reproduce your issue when i use [Route("api/[controller]")]and [ApiController] with the startup.cs like below:
app.UseMvc(routeBuilder =>
        {
            routeBuilder.Expand().Select().Count().OrderBy().Filter();
            routeBuilder.EnableDependencyInjection();
        });

To fix it,be sure you have built a private method to do a handshake between your existing data models (OData model in this case) and EDM.
Here is a simple demo:
1.Controller(comment on Route attribute and ApiController attribute):
//[Route("api/[controller]")]
//[ApiController]
public class StudentsController : ControllerBase
{
    private readonly WSDbContext _context;
    public StudentsController(WSDbContext context)
    {
        _context = context;
    }
    // GET: api/Students
    [HttpGet]
    [EnableQuery()]
    public IEnumerable<Student> Get()
    {
        return _context.Students;
    }
}
//[Route("api/[controller]")]
//[ApiController]
public class SchoolsController : ControllerBase
{
    private readonly WSDbContext _context;
    public SchoolsController(WSDbContext context)
    {
        _context = context;
    }
    // GET: api/Schools
    [HttpGet]
    [EnableQuery()]
    public IEnumerable<School> Get()
    {
        return _context.Schools;
    }

2.Startup.cs():
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore(action => action.EnableEndpointRouting = false);
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        var connection = @"Server=(localdb)\mssqllocaldb;Database=WSDB;Trusted_Connection=True;ConnectRetryCount=0";
        services.AddDbContext<WSDbContext>(options => options.UseSqlServer(connection));
        services.AddOData();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc(routeBuilder =>
        {
            routeBuilder.Expand().Select().Count().OrderBy().Filter();
            routeBuilder.MapODataServiceRoute("api", "api", GetEdmModel());
        });
    }

    private static IEdmModel GetEdmModel()
    {
        var builder = new ODataConventionModelBuilder();
        builder.EntitySet<Student>("Students");
        builder.EntitySet<Student>("Schools");
        return builder.GetEdmModel();
    }
}

A: Just been battling this.
I found that if I request my controller at /api/Things that most of the OData options work but $count doesn't.
However, $count does work if I request the same method via /odata/Things.

A: In my case I wanted to extend existing Api methods with [EnableQuery] but have it include the count metadata.
I ended up extending the EnableQuery attribute to return a different reponse, it worked perfectly.
public class EnableQueryWithMetadataAttribute : EnableQueryAttribute
{
    public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
    {
        base.OnActionExecuted(actionExecutedContext);

        if (actionExecutedContext.Result is ObjectResult obj && obj.Value is IQueryable qry)
        {
            obj.Value = new ODataResponse
            {
                Count = actionExecutedContext.HttpContext.Request.ODataFeature().TotalCount,
                Value = qry
            };
        }
    }
    public class ODataResponse
    {
        [JsonPropertyName("@odata.count")]
        public long? Count { get; set; }

        [JsonPropertyName("value")]
        public IQueryable Value { get; set; }
    }
}

A: You can just set an empty preffix route when you map OData, and you will receive OData with your request your endpoint.
routeBuilder.MapODataServiceRoute("ODataEdmModel", "", GetEdmModel());

A: In my case I've created a special action named $count that users the OData Filter query my collection (EF Database) and return the Count;
[HttpGet("$count")]
public async Task<int> Count(ODataQueryOptions<MyBookEntity> odataQueryOptions)
{
    var queryable = this.dataContext.MyBooks;

    return await odataQueryOptions.Filter
        .ApplyTo(queryable, new ODataQuerySettings())
        .Cast<MyBookEntity>()
        .CountAsync();
}


text:
Q: How to Connect oracle with node js and and express js in RESTFUL API? I already Connect MONGO DB and MYSQL on my RESTFul API using nodejs and express JS but don't be connect with oracl.
My Sql Connect Code is given bellow:
const mysqlConnection=mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'',
    database:'suedu_web'
})

mysqlConnection.connect((err)=>{

    if(!err)
    console.log('DB Connected Successfully')
    else
    console.log('DB Connected failed \n Error:' + JSON.stringify(err,undefined,2))
})

Please give me Oracle Code.

A: you can use like this:
{
    user          : process.env.ORACLE_USER,
    password      : process.env.ORACLE_PASSWORD,
    connectString : "(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521))(CONNECT_DATA =(SID= ORCL)))"
  }

A: You can use oracledb an Oracle Database Node.js™ Add-on
// This example uses Node 8's async/await syntax.

const oracledb = require('oracledb');

oracledb.outFormat = oracledb.OUT_FORMAT_OBJECT;

const mypw = ...  // set mypw to the hr schema password

async function run() {

  let connection;

  try {
    connection = await oracledb.getConnection(  {
      user          : "username_oracle",
      password      : "password_oracle",
      connectString : "localhost/XEPDB1"
    });

    const result = await connection.execute(
      'SELECT *
       FROM tableName'
    );
    console.log(result.rows);

  } catch (err) {
    console.error(err);
  } finally {
    if (connection) {
      try {
        await connection.close();
      } catch (err) {
        console.error(err);
      }
    }
  }
}

run();


text:
Q: React js Content is Not Displaying with small width screens on Mobile Devices And Browsers My react js portfolio website's some sections are not displaying in mobile mode. How to fix that?
My problem is that on mobile devices, My code works fine on desktop

A: Use media query for making it responsive. Try this.

https://mui.com/material-ui/react-use-media-query/


text:
Q: Armstrongs Axioms Proof I am having issues proving functional dependencies with Armstrong's Axioms. This one i'm struggling
with. Let R(A,B,C,D,E) be a relation schema and F = {A→CD, C→E, B→D} 1. Prove: F: BC-> DE
What I have:
1 Given B->D
 1.
Augment C on 1, BC->DC
2.
Decomposition on 2, BC->D BC->C
3.
Transitivity on BC->C, BC->E
4.
Union on BC ->D and and 4, BC->DE
Unsure if this is a proper solution.
Also Prove: AC-> BD I don't think this can be proven.
Please Help!

A: your solutions are correct, apart from some apparent misspelling:

*

*Given B->D, C->E

*Augment C on 1:          BC -> DC

*Decomposition on 2:      BC -> C (3.1), BC -> D (3.2)

*Transitivity on 1, 3.1:  BC -> C, C -> E: BC -> E

*Union on 3.2 and 4:      BC -> DE

alternatively:

*

*B->D, C->E

*augment(1.1, c):  bc -> dc

*augment(1.2, d):  cd -> ed

*trans(2, 3):      bc -> de  (note: bc -> dc <=> bc -> cd <=> cb -> cd <=> cb -> dc)

ac -> bd cannot be proven in general: inspecting the armstrong axioms you notice that for some X to appear on the rhs of a derived fd, it must occur on the rhs of one of the original fds, except for

*

*X is a subset of some X' on the lhs of an original fd
or

*the fd is derived by augmentation with X
1.) constitutes a constraint never mentioned.
if 2.) applies, X would appear on a lhs of the original fd too. the only way to eliminate X is by transitivity which requires X to appear on the rhs of one of the original fds.
take b as X to see that ac -> bd is unprovable.
Abbreviations:

Shorthand
Expansion

fd(s)
Functional dependency(/-cies)

lhs
Left-hand side (of an equation / a derivation )

rhs
Right-hand side


text:
Q: Reorganize QT Menu Actions from ui designer After some developing QT app, I need to reorganize my QActions in some different menus.
I know, I can do it manually through editing generated ui_mainwindow.h, but it's not the right way. (As I would need to do it every rebuild).
Is there a possible way to reorder menu actions using a designer interface?
I'm sure the answer is simple.

A: I'm a really overcomplicated the problem. I don't know why I thought that action actually deleted when deleted from menu, but it's possible to reorganize it by deleting and inserting to correct place again.
So simple.


text:
Q: "List of indices must be integers, not str" While getting an API image using aiohttp I am making a discord bot that is meant to send embeds with images gotten froms APIs. I have one for a dog, and it works. The code for the dog one:
if message.content.lower().startswith("!dog"):
    async with aiohttp.ClientSession() as session:
       request = await session.get('https://some-random-api.ml/img/dog') # Make a request
       dogjson = await request.json() # Convert it to a JSON dictionary
    dogembed = discord.Embed(title="Doggy!", color=discord.Color.blue())
    dogembed.set_image(url=dogjson['link'])

await message.channel.send(embed=dogembed)

This works perfectly, and always. However when I try to do the same thing for a cat images, using "https://api.thecatapi.com/v1/images/search" I get this error.

Here is my code for the cat one:
if message.content.lower().startswith("!cat"):
    async with aiohttp.ClientSession() as session:
       request = await session.get('https://api.thecatapi.com/v1/images/search') # Make a request
       catjson = await request.json() # Convert it to a JSON dictionary
    Catembed = discord.Embed(title="Kitty!", color=discord.Color.blue())
    Catembed.set_image(url=catjson['link'])

    await message.channel.send(embed=Catembed)

Please help me with this, I am a beginner to python and APIs.

A: If you take a look at the result of your API call you'll see that it's a list, not a dictionary, as your error also suggests.
[
  {
    "breeds": [],
    "id": "992",
    "url": "https://cdn2.thecatapi.com/images/992.jpg",
    "width": 560,
    "height": 368
  }
]

This means that you can't do catjson['link'], but you first have to take the first element of the list out of it and then access that field.
catjson[0]['link']

Further, as you can see from the snippet I pasted above, link doesn't exist as a field in that API response. You're looking for url.
catjson[0]['url']

For future reference, it never hurts to look at the output of the API (either in your browser or by printing the result) before trying to use it, and also while debugging. If you get an error that a field doesn't exist, take a look at which fields do exist.
The reason it works fine for the dog API is because the response looks completely different, which is to be expected when using two entirely different API's.


text:
Q: Android build error in Crosswalk I am working on an ionic 2 app for few weeks and it was working fine yesterday but today when I am trying to build and test it on my android device using following command:
ionic run android

I am getting following error in crosswalk:

Error: cmd: Command failed with exit code 1 Error output: FAILURE:
  Build failed with an exception.

*

*What went wrong: A problem occurred configuring root project 'android'.

Could not resolve all dependencies for configuration ':_armv7DebugApkCopy'.
    Could not resolve org.xwalk:xwalk_core_library:22+.
     Required by:
         :android:unspecified
    Could not resolve org.xwalk:xwalk_core_library:22+.
    Failed to list versions for org.xwalk:xwalk_core_library.
    Unable to load Maven meta-data from https://download.01.org/crossw
    alk/releases/crosswalk/android/maven2/org/xwalk/xwalk_core_library/maven-metadat
    a.xml.
    Could not GET 'https://download.01.org/crosswalk/releases/cross
    walk/android/maven2/org/xwalk/xwalk_core_library/maven-metadata.xml'.
    Received s tatus code 403 from server: Forbidden

*Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

I haven't changed anything in code since yesterday.
It is trying to fetch some data from following url: https://download.01.org/crosswalk/releases/crosswalk/android/maven2/org/xwalk/xwalk_core_library/maven-metadata.xml
Which at this moment in time is giving a 403.
I had even tried it without internet connection but it didn't work.
I had tried to go to cross-walk website for any solution but I couldn't even get access to www.crosswalk-project.org
Does anyone know any way around of this issue?

A: After some research and changes with gradle file, I have found a solution:
"Define fixed cross-walk version in android gradle file" as followed:
In your platforms\android\cordova-plugin-crosswalk-webview folder, there is a gradle file.
-> Open the file and find following code:
dependencies {
compile xwalkSpec
}

-> replace the code with following:
dependencies {
compile 'org.xwalk:xwalk_core_library:23.53.589.4' //xwalkSpec
}

And try to build it with
ionic run android

It is working for me.

Updated:

If simply replacing the code,as i have suggested, is not working for you then this is exactly what I have done:
As most of you know, when we specify dependency in gradle file, It downloads that dependency from some server and use it in the project but if the "exact" dependency is already used in same/other project in our pc, It reuses the previously downloaded dependency instead of going out to server.
So  I have opened my ionic app(by previously installed or generated apk) and inspected it using Chrome-Developer-Tool. Then I have typed following command in Console:

window.navigator.userAgent

And i have got :

"Mozilla/5.0 (Linux; Android 5.1; genymotion_vbox86p_5.1_150609_195503 Build/LMY47D) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Crosswalk/23.53.589.4 Mobile Safari/537.36"

The response contains the latest Crosswalk version that my gradle build  was using so I just used that specific version in the gradle file because I know that It has been already downloaded and it worked.
I hope these steps will be helpful to some of you to solve this issue.


text:
Q: CSS p element created in a new section ineherinting properties from a different section which has its own class name I hava a p element which somehow is inheriting CSS properties from a different section which has its own class name.
This is a
HTML

Great Location

 Lorem ipsum    dolor sit amet consectetur

CodeSnippet:
https://codepen.io/Helye23/pen/LYGJELr
Any idea?
Thanks!!

A: Your comma in your info-content class means your targeting your p tag outside the class.
Try this istead:
.info-content h2, .info-content p {
    padding: 10px 100px 20px;
    color: white;
}

You may want to adjust this due to padding but this example means you are no longer target all p classes.
https://www.w3schools.com/cssref/sel_element_comma.asp


text:
Q: Java Pattern for generating and parsing data in stream I have certain protocol that I need to parse or generate. The parsing takes an InputStream and produce different type of objects depending the byte stream. The generator takes different inputs and spit out an OutputStream that allows writing to a target stream. Before reading / writing to the stream there might be some header variables that needs to be initialized.
For code right now looks something like follows:
// Parser.
DataX parsed = DataX.parse(new ByteInputStream(new byte [] {..}));
// Access short field of DataX.
System.out.println(parsed.getX() + parsed.getY()); // data in the header.
// Access some long field by spitting InputStream.
System.out.println(parsed.buildInputStream().readFully()); // data as bytes.

// Generator.
OutputStream outstream =
   DataX.Generator(new FileOutputStream('output')).setX(x).setY(y).build();
// Write data.
outstream.write(new byte[] {...});

DataX extends a class Data that implements two methods deserialize and serialize as abstract method which will eventually be called somewhere inside parse() and Generator().
This is a self-made design pattern, so I would like to ask if this makes sense and whether there is a more Java-ist way to do this kind of thing ?

Edit: The reason the stream needs to be incorporate is because the data might be huge (such as a file) and will not be feasible/desirable to store it entirely in the memory.

A: In general it is a good idea to keep data (header values) and its presentation (streams) separate.
Some component accepts streams (Factory method pattern)
and returns plain objects.
Those objects are serialized to streams via a different component later on.
It shouldn't matter if it is a stream at the moment. If later you want to work with Json objects - the design doesn't need to change dramatically.

A: I think a synmetrical pattern is easy to understand.
// Parser
DataX header = new DataX();   // uninitialized header
InputStream is = header.input(new FileInputStream(...));
// At this point header is initialized.
// user reads data from is.

// Generator
DataX header = new DataX();   // uninitialized header
header.setX(x).setY(y);       // initialize header
OutputStream os = header.output(new FileOutputStream(...));
// At this point header is written to os.
// user writes data to os.


text:
Q: Exception Error while making a Clock/Timer class I am trying to make a Clock with the timeGetTime function and some others. But I keep getting an exception error. I know mayby the quality of the program is not really good, but I was just trying to get it work. It's supposed to be a singleton. I hope you can help me!
// The Clock header file

// The Clock API for meassuring time.
#include<Windows.h>
#include<WinBase.h>
#include<MMSystem.h>

class cTime
{
private:
    double m_Ns;
    double m_Ms;
    double m_S;
public:

    // Set Values
    void SetN(double N) {m_Ns = N;}
    void SetM(double M) {m_Ns = M;}
    void SetS(double S) {m_Ns = S;}

    // Get Values
    double GetN() {return m_Ns;}
    double GetM() {return m_Ms;}
    double GetS() {return m_S;}

// GetTime functions
//int GetDiffrenceNs();
//int GetDiffrenceMs();
//int GetDiffrenceS();
};

class cClock
{
private:
cTime m_CurrentTime;            // CurrentTime object
static cClock* m_pClock;                // Pointer to only instance
cTime m_LastTime;               // LastTime object

bool m_PerformanceCounter;      // Set to true if the performance counter         is available
double m_Frequency;         // Tells the frequenty of the     PerformanceCounter. The value that the PerformanceCounter will increase each second.
double m_CounterTime;           // The Counter of the PerformanceCounter.
double m_Trillingstijd;         // How long one count of the performance counter will take.

public:

static cClock* GetClock();

cTime CurrentTime(); // Get the CurrentTime.
cTime LastTime(); // Get the LastTime.

// Virtual destructor.
virtual ~cClock();

protected:
// Protected constructor.
cClock();
};

// The clock cpp file
#include "Clock.h"

cClock* cClock::m_pClock = 0;

cClock* cClock::GetClock()
{

//BOOL perf_flag;        // Timer Selection Flag
//double time_factor;    // Time Scaling Factor
//LONGLONG last_time;    // Previous timer value
//LONGLONG perf_cnt;

if (QueryPerformanceFrequency((LARGE_INTEGER *) &m_pClock->m_Frequency))
    {

    QueryPerformanceCounter((LARGE_INTEGER *) &m_pClock->m_CounterTime);

    m_pClock->m_PerformanceCounter = true;
    m_pClock->m_Trillingstijd=1.0/m_pClock->m_Frequency;

    double LastedSeconds = m_pClock->m_CounterTime/m_pClock->m_Frequency;

    m_pClock->m_LastTime.SetN(LastedSeconds*1000000);
    m_pClock->m_LastTime.SetM(LastedSeconds*1000);
    m_pClock->m_LastTime.SetS(LastedSeconds);

}

else
{
    m_pClock->m_PerformanceCounter = false;

    double LastedMiliseconds = timeGetTime();

    m_pClock->m_LastTime.SetN(LastedMiliseconds*1000);
    m_pClock->m_LastTime.SetM(LastedMiliseconds);
    m_pClock->m_LastTime.SetS(LastedMiliseconds/1000);
}

return cClock::m_pClock;
}

cTime cClock::LastTime()
{
    return m_LastTime;
}

cTime cClock::CurrentTime()
{
if(m_PerformanceCounter)
{
    QueryPerformanceCounter((LARGE_INTEGER *) &m_CounterTime);

    double LastedSeconds = m_CounterTime/m_Frequency;

    m_CurrentTime.SetN(LastedSeconds*1000000);
    m_CurrentTime.SetM(LastedSeconds*1000);
    m_CurrentTime.SetS(LastedSeconds);
}
else
{
    int LastedMiliseconds = timeGetTime();

    m_CurrentTime.SetN(LastedMiliseconds*1000);
    m_CurrentTime.SetM(LastedMiliseconds);
    m_CurrentTime.SetS(LastedMiliseconds/1000);
}

m_LastTime = m_CurrentTime;

return m_CurrentTime;

}
This is my main, really simple but I just tried to get it to work but it doesn't...
#include "Clock.h"
#include<iostream>

using namespace std;

int main()
{
cClock* Clock = cClock::GetClock();
cTime Test = Clock->CurrentTime();

cout << Test.GetN();
cout << Test.GetM();
cout << Test.GetS();
int temp;
cin >> temp;
return 0;
}

A: It seems that the method cClock* cClock::GetClock() uses m_pClock without initializing it (it is still 0).

A: You are never creating an instance of cClock, just accessing a null pointer to one.
If you really think a singleton is a good idea, then cClock::GetClock() will have to create one if it doesn't already exist; along the lines of
cClock* cClock::GetClock()
{
    if (!m_pClock) {
        m_pClock = new cClock;
    }

    // remainder of function

    return m_pClock;
}

Note that this isn't thread-safe, and also introduces a memory leak. Singletons are difficult to implement in C++, and best avoided unless there is a genuine reason for wanting one. I would move the logic of GetClock() into a public constructor, and allow client code to create and destroy clock objects as it sees fit.


text:
Q: Nuxt - Commit then submit I'm using nuxt.js and have a button to submit a form that goes to a method. I need to put some data in the store before I submit my form however it's skipping straight over my commit and submitting the form.
What should I use in this case?
Commit the mesage and when the message is set submit the form. Do I need Fetch, Ascync or a promise?
Form
<form ref="sfForm" action="http://blahblah/thank-you" method="post" @submit.prevent="sfFormSubmit('contactUs')">

Method
methods: {
   sfFormSubmit(type){
      this.$store.commit('messages/setFormMessage', type);
      this.$refs.sfForm.submit();
   }
}


text:
Q: List named semaphores Is there a way to list all posix-named-semaphores, ipcs doesn't seem to give any info about posix semaphores e.g. ipcs -s output is
------ Semaphore Arrays --------
key        semid      owner      perms      nsems
0xcbc384f8 32769      xxx    600        1

Though I have created many posix semaphores and listing `/dev/shm' shows them
-rw------- 1 xxx auniyal 16 2011-08-09 15:59 /dev/shm/sem.mysem
-rw------- 1 auniyal auniyal 16 2011-08-09 16:29 /dev/shm/sem.mysem1

A: So for now solution seems to be to list /dev/shm e.g.
$ ls -al /dev/shm/sem.*|more
-rw------- 1 auniyal auniyal 16 2011-08-09 15:59 /dev/shm/sem.mysem
-rw------- 1 auniyal auniyal 16 2011-08-09 16:29 /dev/shm/sem.mysem1
-rw------- 1 auniyal auniyal 16 2011-08-09 16:37 /dev/shm/sem.mysem2
-rw------- 1 auniyal auniyal 16 2011-08-09 16:37 /dev/shm/sem.mysem3
-rw------- 1 auniyal auniyal 16 2011-08-09 16:39 /dev/shm/sem.mysem4
...


text:
Q: Django editing a model instance fails to find the instance I'm in the process of making a Recipe Book.  For some reason, whenever I try to pull up a recipe from the DB to edit it, I keep getting an error where it can't find the recipe I've specified.  I'm using slugs, and my logic is that I'm going from a detailView where I've already pulled up the db information, to an updateView.  I'm attempting to pass the recipe object I already pulled from the detailView to the updateView, but when I do, it keeps telling me that it can't find the recipe specified.
views.py:
The base views I'm calling here are only providing a default post method for handling a search so that I don't have to put it in for every view I create so I have some code reusability
class RecipeDetailView(BaseDetailView):
    model = Recipe
    template_name = 'RecipeBook/recipe_detail.html'
    context_object_name = 'recipe_view'
    queryset = None
    slug_field = 'slug'
    slug_url_kwarg = 'slug'

    def get_context_data(self, *args, **kwargs):
        context = super(RecipeDetailView, self).get_context_data()
        recipe = self.object
        recipe.ingredients = recipe.ingredients_list.split('\n')

        context['recipe'] = recipe

        return context

class RecipeEditView(BaseUpdateView):
    model = Recipe
    template_name = 'RecipeBook/edit_recipe.html'
    context_object_name = 'recipe_edit'
    queryset = None
    slug_field = 'slug'
    slug_url_kwarg = 'slug'
    form_class = RecipeForm

    def get_context_data(self, *args, **kwargs):
        context = super(RecipeEditView, self).get_context_data()
        recipe = self.object
        print(recipe.name)
        recipe.ingredients = recipe.ingredients_list.split('\n')
        recipe.categories_list = ""
        categories = Category.objects.filter(recipe=recipe)
        for category in categories:
            if category != categories[-1]:
                recipe.categories_list += (category + ", ")
            else:
                recipe.categories_list += category

        recipe_edit_form = RecipeForm(initial={'name': recipe.name, 'ingredients_list': recipe.ingredients,
                                               'directions': recipe.directions, 'prep_time': recipe.prep_time,
                                               'cook_time': recipe.cook_time, 'servings': recipe.servings,
                                               'source': recipe.source, 'category_input': recipe.categories_list})
        context['recipe'] = recipe
        context['recipe_edit_form'] = recipe_edit_form

        return context

models.py:
class Recipe(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100, default="")
    ingredients_list = models.TextField(default="")
    servings = models.IntegerField(default=0, null=True, blank=True)
    prep_time = models.IntegerField(default=0, null=True, blank=True)
    cook_time = models.IntegerField(default=0, null=True, blank=True)
    directions = models.TextField(default="")
    source = models.CharField(max_length=100, default="", null=True, blank=True)
    categories = models.ManyToManyField(Category, blank=True)
    slug = models.CharField(max_length=200, default="")

    def __str__(self):
        return self.name

urls.py
# ex: /Recipes/Grilled_Chicken/
    path('Recipes/<slug>/', views.RecipeDetailView.as_view(), name='view_recipe'),
    path('Recipes/<path:slug>/', views.RecipeDetailView.as_view(), name='view_recipe'),
    # ex: /Recipes/edit/Steak/
    path('Recipes/edit/<slug>/', views.RecipeEditView.as_view(), name='edit_recipe'),
    path('Recipes/edit/<path:slug>/', views.RecipeEditView.as_view(), name='edit_recipe'),

link in recipe_detail.html:
Edit Recipe

I've been going nuts trying to figure it out.  By everything that I have in here, the recipe that I'm pulling up in the detailView should be able to be passed to the editView, but every time I try to open up the edit_recipe page, it keeps telling me that it can't find the recipe specified.  The URL that it generates shows the proper slug and link that it should though.  I don't know what I'm missing at this point...

A: Try this way:
Edit Recipe

A: I ended up having to go back through and change the view to be a DetailView.  That was the only way I could get the recipe instance to be pushed through.  There's something very specific about using an update view with models that isn't very clear...
Once I changed to a DetailView, the page would populate with the form initialized to the recipe values.  I could then make tweaks to make sure everything worked from there.
Thanks for those who responded, it at least got my brain working in a different direction to get this figured out.


text:
Q: jQuery HTML5 audio stops, when user exits page I am not versed in js or jquery, and I currently have playlists and html5 audio files on my site. Right now, when a user leave the page, if audio was playing it keeps playing. There becomes no way to turn it off. I had it so keyboard controls were on, but if a user went to a web form the audio would turn on and off every time you hit the space key. Anyway, here is my javascript for the playlist. I am stuck after that. I am also using this with Rails 5.
<script type="text/javascript">
  var hap_player;
  jQuery(document).on('turbolinks:load', function() {
    var settings = {
      instanceName: "artwork5",
      sourcePath: "",
      activePlaylist: "",
      activeItem: 0,
      volume: 0.5,
      autoPlay: false,
      preload: "auto",
      randomPlay: false,
      loopingOn: true,
      mediaEndAction: "next",
      soundCloudAppId: "",
      gDriveAppId: "",
      usePlaylistScroll: true,
      playlistScrollOrientation: "vertical",
      playlistScrollTheme: "dark-2",
      useKeyboardNavigationForPlayback: false,
      facebookAppId: "644413448983338",
      useNumbersInPlaylist: true,
      sortableTracks: false,
      playlistItemContent: "title"
    };

    hap_player = $("#hap-wrapper").hap(settings);

    $('.hap-playlist-toggle').on('click', function() {
      var playerHolder = $('.hap-player-holder'),
        ease = 'easeInOutCubic',
        time = 500,
        openValue = $("#hap-wrapper").width() - 50;

      if (!hap_player.playlistOpened) {
        playerHolder.stop().animate({
          'left': openValue + 'px'
        }, {
          duration: time,
          easing: ease,
          complete: function() {
            playerHolder.addClass('hap-player-holder-opened');
          }
        });
      } else {
        playerHolder.css('left', playerHolder.css('left')).removeClass('hap-player-holder-opened').stop().animate({
          'left': 0 + 'px'
        }, {
          duration: time,
          easing: ease
        });
      }
      hap_player.playlistOpened = !hap_player.playlistOpened;
    })
  });
</script>