text:
Q: In $\mathbb{R}^n$ show that every convergent sequence is a Cauchy
Show that every convergent sequence in $\mathbb{R}^n$ is a Cauchy sequence.

We want to show the following
$$\forall\varepsilon>0,\exists J> 0,s.t.\forall i\in\mathbb{N}(i\ge J\rightarrow|a_i−L|<ε)$$
$$\rightarrow \forall\varepsilon>0,\exists N\in\mathbb{N},s.t.\forall j,k\in\mathbb{N},(j,k\ge N\rightarrow|a_j-a_k|<\varepsilon)$$
Something to notice is
$|a_i−L|$ and $|a_j-a_k|$ denotes the Euclidean norm in $\mathbb{R}^n$, rather than the absolute value, actually I think absolute value is a special case in $\mathbb{R}^1$ of Euclidean norm. similarly $L\in \mathbb{R}^n$.
Also we have
$$|a_i−L|<ε\Leftrightarrow a_i\in B(L;\varepsilon)$$
$$|a_j−a_k|<ε\Leftrightarrow a_j\in B(a_k;\varepsilon)$$
But, seems not very useful for the proof$\dots$
And i'm thinking that can I just take the proof of $\mathbb{R}^1$, and change something to make it works for $\mathbb{R}^n$

My attempts
Proof.
Let $\{a_n\}_{n=0}^∞$ be a sequence in $\mathbb{R}^n$
Assume $\{a_n\}_{n=0}^∞$ converges to $L$ where $L\in \mathbb{R}^n$
Show $\{a_n\}_{n=0}^∞$ must be Cauchy
Let $j,k\in\mathbb{N}$
By assumption, and since $2\varepsilon>0$ $$L-2\varepsilon<a_j<L+2\varepsilon$$
And
$$ L-\varepsilon<a_k<L+\varepsilon$$
Subtract second from first $$-\varepsilon<a_j-a_k<\varepsilon$$
Implies
$$|a_j-a_k|<\epsilon\tag*{$\square$}$$

This is quick proof and almost the same as case in $\mathbb{R}^1$, is this vaild $?$
Any suggestion would be appreciated.
If not, how do I prove this hold in $\mathbb{R}^n?$
Thanks for your help.

A: That's not a valid proof because those inequalities hold for real numbers but not for elements of $\mathbb R^n$.
You can do it as follows: given $\varepsilon>0$, take $N\in\mathbb N$ such that $n\geqslant N\implies\lVert a_n-L\rVert<\frac\varepsilon2$. Then$$m,m\geqslant N\implies\lVert a_m-a_n\rVert\leqslant\lVert a_m-L\rVert+\lVert L-a_n\rVert<\varepsilon.$$


text:
Q: AWS SAM Unable to call Rekognition and access S3 from Lambda I am trying to call the detectText method from Rekognition framework and it failed to call S3 bucket. I am not sure how to give roles in SAM Template. Below is my SAM template
GetTextFunction:
Type: AWS::Serverless::Function
Properties:
  CodeUri: gettextfn/
  Handler: text.handler
  Runtime: nodejs12.x
  Timeout: 3
  MemorySize: 128
  Environment:
    Variables:
        imagebucket: !Ref s3bucket
  Events:
    TextApiEvent:
      Type: HttpApi
      Properties:
        Path: /gettext
        Method: get
        ApiId: !Ref myapi

A: Looks like your lambda needs RekognitionDetectOnlyPolicy and also looks you miss the policy to read/write data from S3 bucket also. Have a look at below Policies: added after Environment:
Environment:
    Variables:
      imagebucket: !Ref s3bucket
  Policies:
    - S3ReadPolicy:
        BucketName: !Ref s3bucket
    - RekognitionDetectOnlyPolicy: {}
  Events:

You can refer the complete list of AWS SAM policy templates here https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-templates.html
Also have a look at a sample template here
https://github.com/rollendxavier/serverless_computing/blob/main/template.yaml

redpajama_set_name: RedPajamaStackExchange


text:
Q: Gnupg: Breaks software-properties-common (<= 0.96.24.3) but 0.96.20.7 is to be installed I am new to ubuntu i am trying to install vagrant but i am getting following error:
gp@ubuntu:~/Downloads/gnupg-2.2.13$ sudo apt install vagrant
[sudo] password for gp:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 gnupg : Breaks: software-properties-common (<= 0.96.24.3) but 0.96.20.7 is to be installed
E: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages

A: I had the same issue with a failed apt-get dist-upgrade. apt-get upgrade would just silently fail, but state that many packages weren't upgraded.
I upgraded gnupg individually and all was sorted out after that:
sudo apt install --only-upgrade gnupg


text:
Q: PHP insert data from excel file - Loop error I'm trying to get the data that I uploaded from excel using foreach and for loop, but the weird thing is when I upload excel file w/ 12 rows it successfully inserted, but when I upload excel w/ 13 rows and up its only get the last row and I'm getting the error Uninitialized Offset :8.
this is the array when I uploaded excel w/ 12 rows.
array(12)
{
[0]=> array(1) { [0]=> array(9) { [0]=> string(8) "CC-00057" [1]=> float(123) [2]=> string(5) "apple" [3]=> float(45) [4]=> string(2) "pc" [5]=> string(5) "A1011" [6]=> float(1101) [7]=> float(42110) [8]=> string(3) "asd" } }
[1]=> array(1) { [0]=> array(9) { [0]=> string(8) "CC-00057" [1]=> float(124) [2]=> string(6) "grapes" [3]=> float(2) [4]=> string(3) "box" [5]=> string(5) "A1012" [6]=> float(1101) [7]=> float(42111) [8]=> string(3) "asd" } }
[2]=> array(1) { [0]=> array(9) { [0]=> string(8) "CC-00057" [1]=> float(124) [2]=> string(6) "grapes" [3]=> float(20) [4]=> string(3) "box" [5]=> string(5) "A1016" [6]=> float(1101) [7]=> float(42111) [8]=> string(3) "asd" } }
[3]=> array(1) { [0]=> array(9) { [0]=> string(8) "CC-00057" [1]=> float(124) [2]=> string(5) "chico" [3]=> float(7) [4]=> string(3) "box" [5]=> string(5) "A1012" [6]=> float(1101) [7]=> float(42111) [8]=> string(3) "ads" } }
[4]=> array(1) { [0]=> array(9) { [0]=> string(8) "CC-00057" [1]=> float(125) [2]=> string(9) "pineapple" [3]=> float(8) [4]=> string(3) "box" [5]=> string(5) "A1013" [6]=> float(1102) [7]=> float(42112) [8]=> string(3) "ads" } }
[5]=> array(1) { [0]=> array(9) { [0]=> string(8) "CC-00057" [1]=> float(123) [2]=> string(5) "apple" [3]=> float(45) [4]=> string(2) "pc" [5]=> string(5) "A1011" [6]=> float(1101) [7]=> float(42110) [8]=> string(3) "asd" } }
[6]=> array(1) { [0]=> array(9) { [0]=> string(8) "CC-00057" [1]=> float(124) [2]=> string(6) "grapes" [3]=> float(2) [4]=> string(3) "box" [5]=> string(5) "A1012" [6]=> float(1101) [7]=> float(42111) [8]=> string(3) "asd" } }
[7]=> array(1) { [0]=> array(9) { [0]=> string(8) "CC-00057" [1]=> float(124) [2]=> string(6) "grapes" [3]=> float(20) [4]=> string(3) "box" [5]=> string(5) "A1016" [6]=> float(1101) [7]=> float(42111) [8]=> string(3) "asd" } }
[8]=> array(1) { [0]=> array(9) { [0]=> string(8) "CC-00057" [1]=> float(124) [2]=> string(5) "chico" [3]=> float(7) [4]=> string(3) "box" [5]=> string(5) "A1012" [6]=> float(1101) [7]=> float(42111) [8]=> string(3) "ads" } }
[9]=> array(1) { [0]=> array(9) { [0]=> string(8) "CC-00057" [1]=> float(125) [2]=> string(9) "pineapple" [3]=> float(8) [4]=> string(3) "box" [5]=> string(5) "A1013" [6]=> float(1102) [7]=> float(42112) [8]=> string(3) "ads" } }
[10]=> array(1) { [0]=> array(9) { [0]=> string(8) "CC-00057" [1]=> float(123) [2]=> string(5) "apple" [3]=> float(45) [4]=> string(2) "pc" [5]=> string(5) "A1011" [6]=> float(1101) [7]=> float(42110) [8]=> string(3) "asd" } }
[11]=> array(1) { [0]=> array(9) { [0]=> string(8) "CC-00057" [1]=> float(124) [2]=> string(6) "grapes" [3]=> float(2) [4]=> string(3) "box" [5]=> string(5) "A1012" [6]=> float(1101) [7]=> float(42111) [8]=> string(4) "a1a1" } } }

this is when 13 rows it only get the last row.
 array(1)
    {
    [0]=> array(9) { [0]=> string(8) "CC-00057" [1]=> float(124) [2]=> string(6) "grapes" [3]=> float(2) [4]=> string(3) "box" [5]=> string(5) "A1012" [6]=> float(1101) [7]=> float(42111) [8]=> string(4) "a1a1" } }

below is my code.
var_dump ($dataRow);
        if (isset($dataRow)) {
       echo '<pre>';
            foreach($dataRow as $key => $dataVal)   {
                foreach($dataVal as $key => $dataSume)  {
                    $fArray = $dataSume;

                    for($x=0; $x < 1; $x++ ){
                        $refs = strlen($fArray[0]);
                            $this->varOrder->addCount($fArray[0],$fArray[1],$fArray[2],$fArray[3],$fArray[4],$fArray[5],$fArray[6],$fArray[7],$fArray[8],$flag2);
                    }
                }
            }
        echo '</pre>';
         }
                $data['mode'] = 'Empty';
                $data['message'] = 'Data Successfully Uploaded!';
                $this->session->unset_userdata($dataRow);
                $this->session->unset_userdata('Count');
                $this->load->view('home_view', $data);

My question is why I'm only get the last row when I'm start inserting 13 rows and up, is this on my foreach or for loop syntax?


text:
Q: String split to table on whole column I have two tables, the first, dbo.QuestionaireResponse includes the columns PersonID (int not null), ApplicationID (int not null) and RaceIDs.  PersonID is a basic ID column, but RaceIDs is a varchar(255) that contains comma delimited strings of ID's (bad design I know). The other table is a type table dbo.Race with two columns, RaceID (int identity) and RaceDescription (varchar of some sort).  I need to output a table in one of the two following formats:

*

*PersonID, RaceDescription as a one to many relationship

*PersonID, RaceDescriptions (a comma delimited string of values from the race description collumn)

In my research I came across this post http://ole.michelsen.dk/blog/split-string-to-table-using-transact-sql/ but it doesn't quite fit the problem because the split has to be preformed on every record in the column.
I ended up passing the type table to the webservice in addition to the data, but I'm curious if there's another viable solution.  Performance matters in this case though the type table does have a small number or records.
Any suggestions for how to do this in sql server?

A: Try this:
SELECT q.PersonID, r.RaceDescription
FROM dbo.QuestionaireResponse q JOIN dbo.Race r
ON ',' + q.RaceIDs + ','  LIKE  '%,' + CONVERT(varchar(10),r.RaceID) + ',%';

SQL Fiddle


text:
Q: How to remove the background in matplotlib? I'm trying to plot voxel data in matplotlib (python)
In my code, I want to remove the backgroud of my plot.
Also, Is there any method to rotate my plotting as like the Pyntcloud or other visualization tool?
Here is my code and the output figure.
import matplotlib.pyplot as plt
fig =plt.figure()
ax =fig.add_subplot(projection='3d')
ax.grid(False)
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
ax.voxels(xyz_load)

Output Image


text:
Q: Theorem style with margin on both sides I'm strugeling with the theorem package thmtools and its features.
I've declared several theorem styles with \declaretheoremstyle and \declaretheorem.
How can I add a hanging paragraph margin on the left relative to the length of the theorem type and an absoulte margin on the right? As shown in the picture, the first line containing the theorem header, should be indented as in the rest of the document. The acctual content of the theorem however,  should have a margin on the left as wide as the theorem type "Example". The margin on the right should be defined by an absoulte value. While I have found solutions on indenting the left margin (e.g. here), I have not found anything on doing so with the exact length of the theorem type and nothing on an absoulte margin on the right.

A minimal example of the theorem style above in action:
\documentclass[]{article}

\usepackage{amsthm}
\usepackage{thmtools}
\usepackage{lipsum}

\declaretheoremstyle[
    spaceabove=\topsep,
    spacebelow=\topsep,
    headfont=\normalfont\bfseries,
    notefont=\normalfont,
    notebraces={$\lbrack$}{$\rbrack$},
    bodyfont=\normalfont\itshape,
    postheadspace=\newline
]{examplebreak}

\declaretheorem[style=examplebreak,name=Example]{example}

\begin{document}

\begin{example}[First Example]
    \lipsum[2]
\end{example}

\end{document}

I'm grateful for any help!

A: You can do that easily with ntheorem:
\documentclass[]{article}
\usepackage[showframe, nomarginpar]{geometry}
\usepackage{ntheorem}
\usepackage{thmtools}
\usepackage{lipsum}

%\declaretheoremstyle[
% spaceabove=\topsep,
% spacebelow=\topsep,
% headfont=\normalfont\bfseries,
% notefont=\normalfont\mdseries,
%% notebraces={$\lbrack$}{$\rbrack$},
% bodyfont=\normalfont\itshape,
% % postheadspace=\newline
%]{examplebreak}

\newlength\exampleindent
\settowidth{\exampleindent}{\bfseries Example}
\makeatletter
\newtheoremstyle{examplebreak}%
  {\item[\rlap{\vbox{\hbox{\hskip\labelsep \theorem@headerfont
          \llap{##1}\ ##2\theorem@separator}\hbox{\strut\vspace{1pt}}}}]}%
  {\item[\rlap{\vbox{\hbox{\hskip\labelsep \theorem@headerfont
          \llap{##1}\ ##2\ \normalfont\mdseries[##3]\theorem@separator}\hbox{\strut\vspace{1pt}}}}]}
\makeatother
\theoremstyle{examplebreak}
\theoremheaderfont{\normalfont\bfseries}
\theorembodyfont{\normalfont\itshape}
\theoremindent\exampleindent
\theoremrightindent 1.5cm
\newtheorem{example}{Example}

\begin{document}

\begin{example}[First Example]
    \lipsum[2-3]
\end{example}

\begin{example}%[First Example]
    \lipsum[4]
\end{example}
\end{document}


text:
Q: What is $\frac{\det(A+tI)}{\det(B+tI)}$ as $t\to0$? If $A$ and $B$ are two real $2\times 2$ matrices with $\det A = 0 $ and $\det B = 0 $ and $\mathrm{tr}(B)$ is non zero. then what will be limit of $$\lim_{t\to0}\frac{\det(A+tI)}{\det(B+tI)}$$
I used the formula $\lambda^2-\mathrm{tr} A+\det A = 0$. then i think answer is $\dfrac{\mathrm{tr}(A)}{\mathrm{tr}(B)}$. Am I correct?
What would be expansion of $\det(A+tI)$ for a $2\times 2$ matrices?

A: Let $A$ be an $n \times n$ matrix. Then, one may check that
$$\det (A + t I) = t^n + t^{n-1} \operatorname{tr} A + \cdots + t \, \lambda(A) + \det A$$
where $\lambda (A)$ is a certain constant depending on the eigenvalues of the matrix $A$. In the case $n = 2$, $\lambda (A) = \operatorname{tr} A$. So, if $A$ and $B$ are both $n \times n$ matrices,
$$\frac{\det (A + t I)}{\det (B + t I)} = \frac{t^n + t^{n-1} \operatorname{tr} A + \cdots + t \, \lambda(A) + \det A}{t^n + t^{n-1} \operatorname{tr} B + \cdots + t \, \lambda(B) + \det B}$$
Thus, if $\det A = \det B = 0$, and $\lambda (B) \ne 0$,
$$\lim_{t \to 0} \frac{\det (A + t I)}{\det (B + t I)} = \frac{\lambda (A)}{\lambda (B)}$$
and in the special case $n = 2$ this reduces to exactly what you guessed.

A: $
\def\a{\alpha}\def\b{\beta}
\def\z{0}\def\p{\partial}
\def\LR#1{\left(#1\right)}
\def\BR#1{\Big(#1\Big)}
\def\trace#1{\operatorname{Tr}\LR{#1}}
\def\adj#1{\operatorname{adj}\LR{#1}}
\def\qiq{\quad\implies\quad}
\def\grad#1#2{\frac{\p #1}{\p #2}}
\def\c#1{\color{red}{#1}}
\def\CLR#1{\c{\LR{#1}}}
\def\fracLR#1#2{\LR{\frac{#1}{#2}}}
\def\A{\trace{A^{-1}}}
\def\B{\trace{B^{-1}}}
$Define the matrix variables
$$\eqalign{
A &= \LR{A_0+tI} \qiq \dot A = I \\
B &= \LR{B_0+tI} \qiq \dot B = I \\
}$$
Jacobi's formula tells us that
$$\eqalign{
&\a = \det(A) \qiq\dot\a
    = \a\,\trace{A^{-1}\dot A} = \trace{\adj A} \\
&\b = \det(B) \qiq\dot\b
    = \b\,\trace{B^{-1}\dot B}  = \trace{\adj B} \\
}$$
Applying l'Hopital's Rule to your problem yields
$$\eqalign{
\lim_{t\to\z}\fracLR{\a}{\b}
 = \lim_{t\to\z}\fracLR{\dot\a}{\dot\b}
 = \frac{\trace{\adj{A_0}}}{\trace{\adj{B_0}}}
\\
}$$
For a $2\times 2$ matrix, the adjugate has a simple algebraic form
$$\eqalign{
\adj A &= I_2\trace A - A \\
}$$
Taking the trace of both sides yields
$$\eqalign{
\trace{\adj{A}} \,=\, \BR{\trace{I_2} - {\tt1}}\,{\trace{A}}
     \;\equiv\; \trace{A} \\
}$$
which confirms your conclusion.


text:
Q: Encountered IOException running import job: java.io.IOException: Error returned by javac I am trying to run a simple sqoop import program using JAVA.
My Program:
    String driver="com.vertica.Driver";
    Configuration config = new Configuration();
    config.addResource(new Path("/../../../mapred-site.xml"));
    config.addResource(new Path("/../../../core-site.xml"));
    config.addResource(new Path("/../../../hdfs-site.xml"));

    SqoopOptions options = new SqoopOptions();
    options.setConnectString(connection_string);
    options.setDriverClassName(driver);

    options.setUsername(username);
    options.setPassword("xxxxxxxxxxxxx");
    options.setTargetDir(directory path);
    options.setFetchSize(0);
    options.setSqlQuery("SELECT 123456 as runid, " +
            "business_date " +
            "FROM database.table " +
            "WHERE business_date=\'20140922\' " +
            "AND instrument_id=1037894110378941 " +
            "AND $CONDITIONS");

    int ret = new ImportTool().run(options);
    System.out.println("Return Val: "+ret);

I have the following error
15/02/03 02:26:23 WARN sqoop.ConnFactory: $SQOOP_CONF_DIR has not been set in the environment. Cannot check for additional configuration.
15/02/03 02:26:23 WARN sqoop.ConnFactory: Parameter --driver is set to an explicit driver however appropriate connection manager is not being set (via  --connection-manager). Sqoop is going to fall back to org.apache.sqoop.manager.GenericJdbcManager. Please specify explicitly which connection manager should be     used next time.
15/02/03 02:26:23 INFO tool.CodeGenTool: Beginning code generation
15/02/03 02:26:24 INFO manager.SqlManager: Executing SQL statement: SELECT 123456 as runid, business_date FROM silverscreen_qa.SS_INSTRUMENT WHERE  business_date='20140922' AND instrument_id=1037894110378941 AND  (1 = 0)
15/02/03 02:26:24 INFO manager.SqlManager: Executing SQL statement: SELECT 123456 as runid, business_date FROM silverscreen_qa.SS_INSTRUMENT WHERE  business_date='20140922' AND instrument_id=1037894110378941 AND  (1 = 0)
15/02/03 02:26:24 INFO orm.CompilationManager: $HADOOP_MAPRED_HOME is not set
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:11: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.JdbcWritableBridge;
                             ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:12: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.DelimiterSet;
                             ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:13: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.FieldFormatter;
                             ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:14: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.RecordParser;
                             ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:15: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.BooleanParser;
                             ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:16: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.BlobRef;
                             ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:17: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.ClobRef;
                             ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:18: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.LargeObjectLoader;
                             ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:19: error: package com.cloudera.sqoop.lib does not exist
import com.cloudera.sqoop.lib.SqoopRecord;
                             ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:37: error: cannot find symbol
public class QueryResult extends SqoopRecord  implements DBWritable, Writable {
                                 ^
  symbol: class SqoopRecord
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:81: error: cannot find symbol
  public void loadLargeObjects(LargeObjectLoader __loader)
                               ^
  symbol:   class LargeObjectLoader
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:119: error: cannot find symbol
  private final DelimiterSet __outputDelimiters = new DelimiterSet((char) 44, (char) 10, (char) 0, (char) 0, false);
                ^
  symbol:   class DelimiterSet
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:123: error: cannot find symbol
  public String toString(DelimiterSet delimiters) {
                         ^
  symbol:   class DelimiterSet
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:129: error: cannot find symbol
  public String toString(DelimiterSet delimiters, boolean useRecordDelim) {
                         ^
  symbol:   class DelimiterSet
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:140: error: cannot find symbol
  private final DelimiterSet __inputDelimiters = new DelimiterSet((char) 44, (char) 10, (char) 0, (char) 0, false);
                ^
  symbol:   class DelimiterSet
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:141: error: cannot find symbol
  private RecordParser __parser;
          ^
  symbol:   class RecordParser
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:142: error: package RecordParser does not exist
  public void parse(Text __record) throws RecordParser.ParseError {
                                                      ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:150: error: package RecordParser does not exist
  public void parse(CharSequence __record) throws RecordParser.ParseError {
                                                              ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:158: error: package RecordParser does not exist
  public void parse(byte [] __record) throws RecordParser.ParseError {
                                                         ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:166: error: package RecordParser does not exist
  public void parse(char [] __record) throws RecordParser.ParseError {
                                                         ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:174: error: package RecordParser does not exist
  public void parse(ByteBuffer __record) throws RecordParser.ParseError {
                                                            ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:182: error: package RecordParser does not exist
  public void parse(CharBuffer __record) throws RecordParser.ParseError {
                                                            ^
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:64: error: bad operand types for binary operator '=='
    if (this == o) {
             ^
  first type:  QueryResult
  second type: Object
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:67: error: inconvertible types
    if (!(o instanceof QueryResult)) {
          ^
  required: QueryResult
  found:    Object
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:70: error: inconvertible types
    QueryResult that = (QueryResult) o;
                                     ^
  required: QueryResult
  found:    Object
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:78: error: cannot find symbol
    this.runid = JdbcWritableBridge.readLong(1, __dbResults);
                 ^
  symbol:   variable JdbcWritableBridge
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:79: error: cannot find symbol
    this.business_date = JdbcWritableBridge.readDate(2, __dbResults);
                         ^
  symbol:   variable JdbcWritableBridge
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:89: error: cannot find symbol
    JdbcWritableBridge.writeLong(runid, 1 + __off, -5, __dbStmt);
    ^
  symbol:   variable JdbcWritableBridge
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:90: error: cannot find symbol
    JdbcWritableBridge.writeDate(business_date, 2 + __off, 91, __dbStmt);
    ^
  symbol:   variable JdbcWritableBridge
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:119: error: cannot find symbol
  private final DelimiterSet __outputDelimiters = new DelimiterSet((char) 44, (char) 10, (char) 0, (char) 0, false);
                                                      ^
  symbol:   class DelimiterSet
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:132: error: cannot find symbol
    __sb.append(FieldFormatter.escapeAndEnclose(runid==null?"null":"" + runid, delimiters));
                ^
  symbol:   variable FieldFormatter
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:134: error: cannot find symbol
    __sb.append(FieldFormatter.escapeAndEnclose(business_date==null?"null":"" + business_date, delimiters));
                ^
  symbol:   variable FieldFormatter
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:140: error: cannot find symbol
  private final DelimiterSet __inputDelimiters = new DelimiterSet((char) 44, (char) 10, (char) 0, (char) 0, false);
                                                     ^
  symbol:   class DelimiterSet
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:144: error: cannot find symbol
      this.__parser = new RecordParser(__inputDelimiters);
                          ^
  symbol:   class RecordParser
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:152: error: cannot find symbol
      this.__parser = new RecordParser(__inputDelimiters);
                          ^
  symbol:   class RecordParser
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:160: error: cannot find symbol
      this.__parser = new RecordParser(__inputDelimiters);
                          ^
  symbol:   class RecordParser
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:168: error: cannot find symbol
      this.__parser = new RecordParser(__inputDelimiters);
                          ^
  symbol:   class RecordParser
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:176: error: cannot find symbol
      this.__parser = new RecordParser(__inputDelimiters);
                          ^
  symbol:   class RecordParser
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:184: error: cannot find symbol
      this.__parser = new RecordParser(__inputDelimiters);
                          ^
  symbol:   class RecordParser
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:206: error: cannot find symbol
    QueryResult o = (QueryResult) super.clone();
                                  ^
  symbol:   variable super
  location: class QueryResult
/tmp/sqoop-sha0_dev/compile/bda7671a1a4e5e172248f2497654d2c1/QueryResult.java:208: error: incompatible types
    return o;
           ^
  required: Object
  found:    QueryResult
41 errors
15/02/03 02:26:24 ERROR tool.ImportTool: Encountered IOException running import job: java.io.IOException: Error returned by javac
        at org.apache.sqoop.orm.CompilationManager.compile(CompilationManager.java:207)
        at org.apache.sqoop.tool.CodeGenTool.generateORM(CodeGenTool.java:97)
        at org.apache.sqoop.tool.ImportTool.importTable(ImportTool.java:396)
        at org.apache.sqoop.tool.ImportTool.run(ImportTool.java:502)
        at com.cts.rbc.archive.TestConnectionForHive.main(TestConnectionForHive.java:196)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.util.RunJar.main(RunJar.java:212)

Return Val: 1

Possible Solutions I tried.
In my hadoop-env.sh the value of JAVA_HOME is
    JAVA_HOME=/usr/lib/jvm/java-1.7.0-oracle-1.7.0.65.x86_64

I know this sounds repeated but believe me I have tried all solutions described in the solutions provided in similar questions
I tried changing JAVA_HOME in ~/.bashrc with the below code
    JAVA_HOME=/etc/alternatives/java

This is where latest java is installed in my node
It still throws the same error.
The same query works in bash.
Note: I don't have permission to alter JAVA_HOME in hadoop-env.sh as its a shared system.
Possible way to overwrite JAVA_HOME in Java Program?

A: [solved]
There was no need to change java_home (or) hadoop_mapred_home (or) sqoop_home
As the error suggests, it was not able to find sqoop library. Whereas I used sqoop 1.4.4 library in my program.
Please note that I wasn't using any build tool (Maven, SBT or anything)
I was using normal eclipse and adding external .jar to my program.
While exporting the .jar I was using Eclipse standard method (File -> Export -> Java -> Runnable .jar File)
In launch configuration I selected my appropriate project
and in library handling, I was using the option "package required libraries into generated JAR"
When I selected "extract required libraries into generated JAR" and executed .jar file it was executed successfully.


text:
Q: How to get last day of current month via Ni-Fi expression language? As far as I understood there's only now() function available in ni-fi expression language to get time. I can easily get 1st day of each month since it is a constant, but how can I get last day of a current month since it varies from month to month?
Thank you beforehand!

A: ${now():format("yyyy-MM-32"):toDate("yyyy-MM-dd"):format("yyyy-MM"):toDate("yyyy-MM"):minus(86400000)}
//^now  ^next month          ^to date             ^1st of next month                  ^minus 1 day

nifi should provide a function for that...


text:
Q: Django_filters Widget Customize How Can I Customize Widgets in Django_filters?
I tried To Did Like This But There its make Value in Select Field GoneImage When Adding Widget, and When i removed the widget the value is shown Image When Remove Widget,
Sorry for my bad English, Thanks Before
class CustomerOrderFilter(django_filters.FilterSet):
    product = django_filters.ChoiceFilter(
        widget=forms.Select(attrs={'class': 'form-control'}))
    status = django_filters.ChoiceFilter(
        widget=forms.Select(attrs={'class': 'form-control'}))

    class Meta:
        model = Order
        fields = '__all__'
        exclude = ('customer', 'date_created', 'updated',)

A: ChoiceField is generic, you need to explicitly provide choices in your product field
class CustomerOrderFilter(django_filters.FilterSet):
    product = django_filters.ChoiceFilter(
        # replace choices with the choices defined in your order model or just copy it over
        choices=<PRODUCT_CHOICES>,
        widget=forms.Select(attrs={'class': 'form-control'}))


text:
Q: Fluter : How is whenCompleted() different from then() in Future? Can somebody please explain How is whenCompleted() different from then() in Future with example?

A: Based on my understanding:
WhenCompleted:
This is called before then (Immediately the future completes). You can use this function if you do not need the value returned by the future, but you have to do something after the future is completed. It can also return an error.
Then:
You can use this if you need to access the value of the future and do something after the future function is executed. It can aslo return an error.
These are the only differences I could point out.


text:
Q: NullPointerException while passing 2d array to the constructor When I try to pass the 2d array (myString) to constructor, Eclipse shows me NullPointerException in the following line:
DenseBoard<String> temp1 = new DenseBoard<String>(myString, "a");

Could smb please explain me what I did wrong? Thanks in advance!
public class Tester {

    public static void main(String[] args){

        String[][] myString = {{"A B C"}, {"D E F"}, {"G H I"}};
        DenseBoard<String> temp1 = new DenseBoard<String>(myString, "a");
        System.out.println(temp1);
    }
}

Class DenseBoard
import java.util.*;
public class DenseBoard <T> {

 private ArrayList<ArrayList<T>> myBoard;

 public DenseBoard(T[][] x, T fillElem){

      for(int i = 0; i < x.length; i++){
         ArrayList<T> values = new ArrayList<T>();
          for(int j = 0; j < x[0].length; j++){
              values.add(x[i][j]);
          }
          myBoard.add(values);
      }
  }

 public String toString(){
      String result = "";
      for(int i = 0; i < myBoard.size(); i++){
          for(int j = 0; j < myBoard.get(i).size(); j++){
              result += myBoard.get(i).get(j);
          }
          System.out.println();
      }
      return result;
  }

}

A: You havn't Initialized your variable myBoard and in for loop you have to use x[i].length instead of x[0].length
Try this:-
package p1;
import java.util.ArrayList;
public class A1{
    public static void main(String[] args) {
        String[][] myString = {{"A B C"}, {"D E F"}, {"G H I"}};
        DenseBoard<String> temp1 = new DenseBoard<String>(myString, "a");
        System.out.println(temp1);
    }
}

class DenseBoard <T> {
    private ArrayList<ArrayList<T>> myBoard;
    public DenseBoard(T[][] x, T fillElem){
        myBoard = new ArrayList<>();
        for(int i = 0; i < x.length; i++){
            ArrayList<T> values = new ArrayList<T>();
            for(int j = 0; j < x[i].length; j++){
                values.add(x[i][j]);
            }
            System.out.println(i);
            System.out.println(values);
            myBoard.add(values);
        }
    }
    public String toString(){
        String result = "";
        for(int i = 0; i < myBoard.size(); i++){
            for(int j = 0; j < myBoard.get(i).size(); j++){
                result += myBoard.get(i).get(j);
            }
            System.out.println();
        }
        return result;
    }
}

A: Your  myBoard is not initialized in java. Therefore, you should first intialize the object before you use it.
Try this
private ArrayList<ArrayList<T>> myBoard = new ArrayList<>();

A: Your myBoard is null.
You should initialize it with,
private ArrayList<ArrayList<T>> myBoard = new ArrayList<>();

A: It looks like myBoard is never instantiated.


text:
Q: How to get a dependency list out of webpack? Webpack takes a long time to run, so it'd be nice to not run it when not necessary.  Is there a way to generate a list of dependencies, like gcc -M does?

A: Here's my first attempt.   There must be a better way:
webpack --json |
jq -r '.chunks[0].modules[].name' |
sed "s|/~/|/node_modules/|g" |
grep -v "^multi " | # filter out entries
grep -v "(" | # filter out (ignored) and (webpack)/buildin etc
sed 's/.*!//' | # ignore the loaders


text:
Q: Do imported modules have the same working directory as the file being executed? Suppose I have a file called myfile.py in /Users/joe/Documents:
import mymodule

mymodule.foobar()

Now let's say that I need to fetch the current working directory of myfile.py in mymodule (which is in another location). Do they both have the same working directory because I am importing mymodule into myfile, or does mymodule have it's working directory as the directory of where it was installed

A: Because you are importing the module, they both have the same working directory, meaning that completing operations with os will be successful (or whatever other purpose you are using the current working directory for).


text:
Q: MemoryHandler not Pushing when application terminates I am writing a Java Server application using java.util.logging, with a MemoryHandler.
How do I make the MemoryHandler to push data out to file when the application terminates?
I tried to add a ShutDownHook and manually push data to file, but it appears that log handlers already are removed when reaching "hook".
This is my code:
public class example implements Runnable{
static {
    // Set upp logging
    // Adding a MemoryHandler
    FileHandler fileHandler = null;
    MemoryHandler memoryHandler;

    try {
        fileHandler = new FileHandler("myapp.log");
        fileHandler.setLevel(Level.ALL);
    } catch (IOException e) {
        e.printStackTrace();
    }

    memoryHandler = new MemoryHandler( fileHandler, 100, Level.SEVERE);
    Logger rootLogger = Logger.getLogger("");
    rootLogger.addHandler(memoryHandler);
}

public static void main(String[] args) throws Exception {

        Thread serverThread = new Thread(new example());
        serverThread.setDaemon(false);
        serverThread.start();
}

public void run() {

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            // This is execute when application are shutting down.
            //
            // MemoryHandler are not not in the handlers list
            for (Handler handler: Logger.getLogger("").getHandlers())
            {
                System.out.println("Looping handlers");
                if (handler.getClass() == MemoryHandler.class)
                {
                   System.out.println("Memoryhandler found");
                   //This never happens.
                   ((MemoryHandler)handler).push();
                }

        }
    });

    try {
        // ALOT OF STUFF
    }
    catch (Exception ex)
    {
    }

}
}

Please advice!


text:
Q: X subway line vs subway line X Can the name of a bus/train/subway line come before and after the term "line" ? For instance, are both expressions below correct?

*

*subway line F

*F subway line

The former seems more usual to me, but I have recently heard from an American that the latter is also usual .

A: Both usages occur; for example, in Boston (Massachusetts, USA), one refers to the lines of the "T" by color, so you might take a train on the "Blue line"; similarly in London (England), where the Underground/tube lines have names, so your train might be on the "Bakerloo line", and in New York (New York, USA), where you might be riding on the "A train" or "7 train" on the subway system - but in Toronto (Ontario, Canada), the subway lines are referred to by number as "Line 1" through "Line 6".


text:
Q: GIMP batch editing (Script-fu/Python-fu) I have about 500 images, I would like edit all of them in batch, I need to resize them all at to 190x120 dimensions, position then slightly higher (say 10 pixels). And export. Also I would like them all to keep their initial names.
Basically I have a frame and I would like to load images (on layer under it) then size them down (above dimensions) move slightly up and export each individual image with frame so that it keeps its name.
What would be a command I could use in GIMP console (script-fu or Python-fu)?
Or what other method could I use to achieve the result without editing each image individually?
Thanks in advance!

A: i altered one of my own python-fu scripts, and after some testing it seems to do what you want. the interface itself is pretty self-explanatory.
just download the file and install it as a plug-in.
gist link: https://gist.github.com/MCOfficer/bdf6c0c0935d22da38e72cc99fea6375 (archive.md)


text:
Q: Python 3.4 very simple packet sniffer How can I make packet sniffer at selected server and port? Something like Wpe Pro or RPE, but I want to use Python and 'print' for writing these packets. I tried this:
import socket

UDP_IP = "xx.xx.xx.xx"
UDP_PORT = xxxx

sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    print("received message:", data)

but I think it can't work (UDP or something else is wrong?). How can I do it correctly?

A: I have working code that sends then receives and it goes a little something like this:
# set up the UDP socket
connection = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
connection.settimeout(5)

# Send packet by UDP
connection.sendto(request_bytes, (UDP_IP, UDP_PORT))

# Receive response packet
response_bytes = connection.recv(4096)

Could it be the case that settimeout is missing for you?

A: pypcap is a simplified object-oriented Python wrapper for libpcap - the current tcpdump.org version, and the WinPcap port for Windows.
That might save you some time.


text:
Q: How to use binary data in SQLAlchemy? How does one use binary data (BLOB type column) in SQLAlchemy.
I just created a table with fields key, val, where val is BLOB and when I query the table, SQLAlchemy returns:
<read-only buffer for 0x83c3040, size -1, offset 0 at 0x83c3120>

How do I use this read-only buffer?

A: You can iterate over it (e.g. for streaming it) or convert it to a string/binary if you want to have the whole binary in memory (which shouldn't be a problem as long as you are not dealing with movies in the database...)
>>> from sqlalchemy.util import buffer
>>> var = buffer('foo')
>>> var
<read-only buffer for 0xb727fb00, size -1, offset 0 at 0xb727fa80>
>>> str(var)
'foo'
>>> for i in var:
...   print i
...
f
o
o

Regards,
Christoph

A: In SQLAlchemy 1.3, using Python2, binary data is returned as str, in Python 3 it is bytes:
# -*- coding: utf-8 -*-
import zlib

import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import orm

Base = declarative_base()

class Blobby(Base):
    __tablename__ = 'blobby'

    id = sa.Column(sa.Integer, primary_key=True)
    blob = sa.Column(sa.BLOB)

engine = sa.create_engine('mysql+pymysql:///test', echo=True)
Base.metadata.drop_all(bind=engine, checkfirst=True)
Base.metadata.create_all(bind=engine)

Session = orm.sessionmaker(bind=engine)

session = Session()
data = zlib.compress('Hello world'.encode('ascii'))
session.add(Blobby(blob=data))
session.commit()

blob, = session.query(Blobby.blob).first()
print(type(blob), blob)
session.close()

Python2 output
(<type 'str'>, 'x\x9c\xf3H\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x18\xab\x04=')

Python3 output:
<class 'bytes'> b'x\x9c\xf3H\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x18\xab\x04='


text:
Q: Mockito returns FileNotFoundException although file is there I'm trying to run a test on a newly Spring Boot created service class. StringWriter content is regular XML with a few lines of tags named 'transaction'.
PrepareExcelServiceTest.class
@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class PrepareExcelServiceTest {

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();

    private static final Logger log = LoggerFactory.getLogger(PrepareExcelService.class);

    @Test
    public void testPrepareExcelService() throws ParserConfigurationException, SAXException, IOException {
        PrepareExcelService prepareExcelService = new PrepareExcelService();
        StringWriter xmlStringWriter = new StringWriter();

        Source source = new StreamSource("./view/xml/0_dummy.xml");
        xmlStringWriter.write(source.toString());

        prepareExcelService.prepareDocument(xmlStringWriter);
    }
}

PrepareExcelService.class
@Service
public class PrepareExcelService {

    private HSSFWorkbook workbook;
    private HSSFSheet spreadsheet;

    public void prepareDocument(StringWriter xmlStringWriter) throws IOException,
                                                                            SAXException, ParserConfigurationException {
        workbook = setupWorkBook();
        spreadsheet = setupSheet(workbook);

        Document document = parseXMLStringWriter(xmlStringWriter);
        fillContent(document, spreadsheet);

        FileOutputStream output = new FileOutputStream(new File("TestExcelFile.xls"));
        workbook.write(output);
        output.flush();
        output.close();
    }

    private HSSFWorkbook setupWorkBook() {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFCellStyle cellStyle = workbook.createCellStyle();

        cellStyle.setBorderLeft(BorderStyle.MEDIUM);
        cellStyle.setBorderRight(BorderStyle.MEDIUM);
        cellStyle.setBorderTop(BorderStyle.MEDIUM);
        cellStyle.setBorderBottom(BorderStyle.MEDIUM);
        cellStyle.setIndention((short)4);
        cellStyle.setWrapText(true);

        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short)24);
        font.setFontName("Courier New");
        font.setItalic(false);
        cellStyle.setFont(font);

        return workbook;
    }

    private HSSFSheet setupSheet(HSSFWorkbook workbook) {
        HSSFSheet spreadSheet = workbook.createSheet("spreadSheet");
        return spreadSheet;
    }

    private Document parseXMLStringWriter(StringWriter xmlStringWriter) throws ParserConfigurationException,
                                                                                IOException, SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        return builder.parse(xmlStringWriter.toString());
    }

    private void fillContent (Document document, HSSFSheet spreadSheet) {
        HSSFRow row = spreadSheet.createRow(0);
        HSSFCell cell = row.createCell((short) 1);

        NodeList nodeList = document.getElementsByTagName("transaction");
        HSSFRow rowOne = spreadSheet.createRow(1);

        cell.setCellValue("Spreadsheet Header Row");

        for (int i = 0; i < nodeList.getLength(); i++) {
            switch (i) {
                case 0:
                    cell = rowOne.createCell((short) 0);
                    cell.setCellValue("transaction");
                    cell = rowOne.createCell((short) 1);
                    cell.setCellValue(((Element) (nodeList.item(0))).getElementsByTagName("transaction").item(0)
                                                                                .getFirstChild().getNodeValue());
                    break;
                default:
                    break;
            }
        }
    }
}

While testing this service I get the following exception although the file is there and other services interact with it correctly through StringWriter.
java.io.FileNotFoundException: ...\javax.xml.transform.stream.StreamSource@4439f31e (The system cannot find the file specified)

    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
    at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:623)
    at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:189)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:812)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:177)
    at ee.estcard.repgen.service.PrepareExcelService.parseXMLStringWriter(PrepareExcelService.java:78)
    at ee.estcard.repgen.service.PrepareExcelService.prepareDocument(PrepareExcelService.java:39)
    at ee.estcard.repgen.service.PrepareExcelServiceTest.testPrepareExcelService(PrepareExcelServiceTest.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:16)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

I think the problem lies in my incorrect usage of StringWriter, but due to my rookie knowledge of Java I am still unable to solve this problem.

A: No your problem is related to how you use StreamSource, indeed calling source.toString() won't give you the content of the source as you seem to expect but something like javax.xml.transform.stream.StreamSource@4439f31e as you can see in your stack trace.
Simply get rid of your StringWriter and use a InputSource in your code to fix your code but also to make it much more flexible since using InputSource is an open door to many different type of sources, moreover loading the content of a file is not a good practice and should be avoided because if the file is too big you could face OOME if it cannot fit into the heap.
In PrepareExcelServiceTest
PrepareExcelService prepareExcelService = new PrepareExcelService();
InputSource source = new InputSource("./view/xml/0_dummy.xml");
prepareExcelService.prepareDocument(source);

In the method parseXMLStringWriter to be renamed
private Document parseXML(InputSource source) throws ParserConfigurationException,
    IOException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    return builder.parse(source);
}

In the method prepareDocument
public void prepareDocument(InputSource source) throws IOException,
    SAXException, ParserConfigurationException {
    ...

    Document document = parseXML(source);

    ...
}

A: First of all, I doubt the StringWriter is a good type to use for a method signature for transporting "string-content". There are many alternatives, use a pointer (i.e. URI, Path, File) to the content or some consumable representation of the character content (Reader, InputStream, InputSourc) or the content itself (String).
But assume, you did that on purpose:
The DocumentBuilder's parse() method accepts:

*

*an InputSource

*an InputStream

*a URI-String pointing to a file

Your StringWriter or better, the result of it's toString() method is neither of them. So you need to convert the StringWriter's buffer content into any of those types.
Probably the easiest would be to
new InputSource(new StringReader(xmlStringWriter.toString()))

so the method may look like:
private Document parseXMLStringWriter(StringWriter xmlStringWriter) throws ParserConfigurationException,
                                                                                IOException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    return builder.parse(new InputSource(new StringReader(xmlStringWriter.toString())));
}

Now you're able to parse the string contained in the writer. But still, the content is wrong.
The StreamSource's toString() method creates an object reference string, but does not produce the content of the file referenced by the StreamSource. Instead, you need to fetch the content of the file.
Probably the easiest way to get the file content into a String is
String content = new String(Files.readAllBytes(Paths.get("/path/to/file")));

(ignores the encoding of the file)
This should get your test running. But again, don't use the StringWriter at all.


text:
Q: SQL refer a to b and b to a I'm using PHPMyAdmin (so mySQL) to create this.
I have 2 tables, Album and photo.  Of course, a photo can be part of an album and for that I use a foreign key from photo to album.
But now I want to be able to put a photo in the album table so I can use that photo as a cover for my album. I've tried adding a foreign key but that gives me a foreign key constraint.
Here are the tables to help understand what I mean (foto = photo). The red line indicates what I want to achieve.

I'm not that good at SQL so any help is appreciated.
SQL Album:
CREATE TABLE `Albums` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Album_Naam` varchar(255) NOT NULL,
`Aanmaakdatum` datetime NOT NULL,
`FotoID` int(11) DEFAULT '1',
PRIMARY KEY (`ID`),
KEY `FotoID` (`FotoID`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1

SQL Photo
CREATE TABLE `Foto` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Foto_Naam` varchar(255) NOT NULL,
`AlbumID` int(11) DEFAULT NULL,
PRIMARY KEY (`ID`),
KEY `AlbumID` (`AlbumID`),
CONSTRAINT `Foto_ibfk_1` FOREIGN KEY (`AlbumID`) REFERENCES `Albums` (`ID`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=latin1

A: A foreign key can be made optional by making the referencing field nullable; NULL values in the field do not violate the foreign key constraints enforced on it. This can be used to represent purely optional relations or, as in the case of this question, defer setting the value in semi-cyclic dependencies.
Note that to remove the cover photo from an album, the album will first need it's cover reference to that foto set to another photo, or to null. Similarly, to delete the album, you would need to delete it's Fotos, and so first set it's cover to null.


text:
Q: Creating default object from empty value "error in laravel" Hi I'm working on update products form of e-commerce site but when I try to edit details then it shows error "Undefined variable: fileName" and error line is:
 Product::where(['id'=>$id])->
 update(['product_name'=>$data['product_name'],
 'product_code'=>$data['product_ code'],
 'product_color'=>$data['product_color'],
 'description'=>$data['description'],
 'price'=>$data['price'],'image'=>$fileName]);
    return redirect()->back()->with('flash_message_success','Product
  updated successfully!');

or when i try to update image only then its error is: "Creating default object from empty value", or error line is:
$product->image = $filename;

this is code of ProductsController:
 public function editProduct(Request $request, $id=null){

  if($request->isMethod('post')){
    $data = $request->all();
    //echo "<pre>"; print_r($data); die;

    if($request->hasFile('image')){
      $image_tmp = Input::file('image');
      if($image_tmp->isValid()){
        $extension = $image_tmp->getClientOriginalExtension();
        $filename = rand(111,99999).'.'.$extension;
        $large_image_path =
  'images/backend_images/products/large/'.$filename;
        $medium_image_path =
  'images/backend_images/products/medium/'.$filename;
        $small_image_path =
  'images/backend_images/products/small/'.$filename;
        // Resize Images
        Image::make($image_tmp)->save($large_image_path);
        Image::make($image_tmp)->resize(600,600)->save($medium_image_path);
        Image::make($image_tmp)->resize(300,300)->save($small_image_path);

        // Store image name in products table
        $product->image = $filename;
       }
      }

     if(empty($data['description'])){
          $data['description'] = '';
        }

     Product::where(['id'=>$id])-
      >update(['product_name'=>$data['product_name'],
       'product_code'=>$data['product_code'],
       'product_color'=>$data['product_color'],
       'description'=>$data['description'],
       'price'=>$data['price'],'image'=>$fileName]);
       return redirect()->back()->with('flash_message_success','Product
        updated successfully!');
       }

    //Get product details
    $productDetails = Product::where(['id'=>$id])->first();

     return view('admin.products.edit_product')-
      >with(compact('productDetails'));
    }

A: "Undefined variable: fileName"
There's a typo in your variable. Change $fileName to $filename.

A: i guess you need to do something like this
$product=new Product();
$product->image = $filename;

also where did you define $fileName in your code?


text:
Q: Smoothness of a polytope This might a bit a too general question to ask but I cannot get my head around this definition I found. A polytope $P\subset\mathbb{R}^n$ is smooth at the vertex if the set $ \{ (w_1-p),(w_2-p),...,(w_n-p)\}$ can be extended to a basis for $\mathbb{Z}^n$.
Where do the $w_i$ come from? I understand that they are some vectors by which the set of points should form a base but no word whether the $w_i$ are arbitrary or not. If anyone could give me an explanation or better a concise definition I would be most thankful.


text:
Q: Android studio 3.1 aidl is missing I just updated Android studio to version 3.1 few days ago. I am getting this error in Build tab AIDL is missing.
Caused by: java.lang.IllegalStateException: aidl is missing from '.../sdk/build-tools/27.0.3/aidl'

Here is the complete console error I am getting
Caused by: java.lang.IllegalStateException: aidl is missing from '/Users/user_name/Documents/sdk/build-tools/27.0.3/aidl'
    at com.android.builder.core.AndroidBuilder.compileAllAidlFiles(AndroidBuilder.java:963)
    at com.android.build.gradle.tasks.AidlCompile.compileAllFiles(AidlCompile.java:132)
    at com.android.build.gradle.tasks.AidlCompile.doFullTaskAction(AidlCompile.java:188)
    ... 48 more

I have searched for this issue for specific Android Studio 3.1 but not found any solution yet.
Screen shot attached below

A: I got the answer to my question. Actually I am new macbook user and shifted all my stuff from windows Laptop to this mac.
Silly me I also copied the sdk folder from laptop and set as sdk path. Aidl is missing because my build-tools folder has aidl .exe files which is surely not for macbook.
Thanks to pskink for the hints in comments. Really appreciated!
EDIT
Do not ever copy sdk from windows laptop to mac. Always use own mac's version sdk that comes along with android studio.
Cheers!

A: This happens when the versions of SDK, Build Tools and Gradle Plugins doesn't match.
This will be fixed if you use the latest versions of gradle plugins are placed in the project build.gradle, and the other versions are on the build.gradle of the module.


text:
Q: "I reminded myself that..." I'm wondering if "I reminded myself that..." is correct expression in English and if English speakers use such expression at all or if this is replaced by something else.
Let's take this dialogue as an example:

*

*A: How many apples did you buy?

*B: Ten... no, wait, I reminded myself that I bought five more on the way home.

Google Translate and other suggestions:

*

*"I was reminded of..." (but this sounds like someone else reminded me that)

*"I just recalled that I bought" (this sounds nice as well)

Which one would be the most natural one?

A: Reminding is an act that usually involves saying or doing something. So when your wife reminds you to buy apples, she says something like: Don't forget to buy apples, or she writes you a note.
It is certainly also possible to remind yourself. For example, if you were on your way home and you suddenly thought, I must buy apples when I get off the train, then you could tell your wife later: I reminded myself that I needed to buy apples.
However, the expression does not make sense in your dialogue, because at the time of answering your wife, you are not saying or doing something to make you think of buying apples, you are simply remembering buying them. So, you need to say:

Ten ... no, wait, I now remember/recall that I bought five more on the
  way home.

A: Isn't Polish your mother tongue by chance? ;)
A different situation to consider. You're driving to work in the morning, you're thinking about different things and then, bam!, you realize you'd left the iron on. You couldn't say then, "I reminded myself I'd left the iron on." You say, "I remembered I'd left the iron on."


text:
Q: In C#, is there a way to pass an array to a method that takes in a variable length parameters? Suppose I have this method I want to call, and it's from a third-party library so I cannot change its signature:
void PrintNames(params string[] names)
I'm writing this method that needs to call PrintNames:
void MyPrintNames(string[] myNames) {
  // How do I call PrintNames with all the strings in myNames as the parameter?
}

A: I would try
PrintNames(myNames);

You would know if you had a look at the specs on MSDN: http://msdn.microsoft.com/en-us/library/w5zay9db.aspx
They demonstrated it quite clearly - note the comment in the sample code:
// An array argument can be passed, as long as the array
// type matches the parameter type of the method being called.

A: Sure.  The compiler will convert multiple parameters into an array, or just let you pass in an array directly.
public class Test
{
   public static void Main()
   {
      var b = new string[] {"One", "Two", "Three"};
      Console.WriteLine(Foo(b)); // Call Foo with an array

      Console.WriteLine(Foo("Four", "Five")); // Call Foo with parameters
   }

   public static int Foo(params string[] test)
   {
      return test.Length;
   }
}

Fiddle


text:
Q: php sorter script only outputting the same data even though i am asking it to do diffrent okay so i have made the following script to sort some data i have in this format
0|1|2

heres my script (this now works)

    <form method="post">

<textarea name="mp" cols="60" rows="10">0|1|2</textarea>

Delim: <input type="text" name="delim" value="|" size="1" /> data1: <input type="text" name="mail" value="0" size="1" /> data2: <input type="text" name="pwd" value="1" size="1" />
<input type="submit" value=" send " name="btn-submit" />

</form>

<?php

    if (isset($_POST['mp'], $_POST['delim'], $_POST['btn-submit'], $_POST['mail'], $_POST['pwd'])) {
        $mps = preg_split('/\r\n|\r|\n/', $_POST['mp']);

        // Create an array to store results
        $result_data = array();

        // Iterate over requests
        foreach ($mps as $mp) {
            $mp = explode($_POST['delim'], $mp);

            // Store the account details in variables
            $email = $mp[$_POST["mail"]];
                  $password = $mp[$_POST["pwd"]];
            // Prepare a reusable string
            $result_string = "" . $email .  " : " . $password . "";
                            // Add result to the array
            $result_data[] = $result_string;

}
// Store of results complete. We now display them.
        if (count($result_data)) {
            echo "
";
            foreach ($result_data as $result_data_entry) {
                echo "
" . $result_data_entry . "
";
            }
            echo "
";
        }
}

?>

i would now like to save the results into a text file also
any help would be brilliant .
i am writing this extra line as my post has way way too much code .

A: You aren't using the data1 and data2 fields anywhere in your PHP.
I think instead of this:
list($email, $password) = $mp;

you need
$email = $mp[$_POST["mail"]];
$password = $mp[$_POST["pwd"]];

It's also worth noting that the values supplied in those two fields will be zero based.


text:
Q: split data frame into two by column value I have a data frame in R where one of the columns is gender. The values of gender are factors with "f" or "m" though if the data set is bad, it could be more (for instance NA).
I'm trying to split the data frame into a list of data frames with gender being unique. This way I can run the same models on the different populations.
Is there a better way then basically:
dfMale <- mydata[which(mydata$gender == "m"),]
dfFemale <- mdata[which(mydata$gender == "f"),]
dfOther <- mydata[!(1:dim(mydata][1] %in% c(which(mydata$gender == "m"),which(mydata$gender == "f"))]

Thanks.

A: X<-split(df, df$gender)

from this question
Split data.frame based on levels of a factor into new data.frames


text:
Q: Array Guessing game - How to set and get an array? I am trying to create a guessing game where the user enters a name and is
prompted to pick a number 5 times. I am trying to store the numbers in an array and use set and get methods to print out the attributes of the array. I have achieved this for the name but I am unable to set and get the array.
import java.util.Scanner;

public class StudentStore
{

    private String n1;//store's the player's name
    //private int [] s10;  //stores the player's score
    private int i;
    private int noOfPlayers = 5;
    private int[] s10 = new int[noOfPlayers];
    Scanner kboardIn = new Scanner(System.in);
    private int index;
    int newInt = 0;

    public StudentStore(String n1, int [] s10, int i )
    {

            this.n1 = n1;
            this.s10[i] = s10[i];
            this.setName(n1);
            //this.i = i;
            this.setScore(s10,i);
            //this.index = index;
        //  PlayerScore.incNumberScores();
    }

    public void setScore( int []s10, int i)
    {
        //takes an integer score, sets variables and checks topScore
        this.s10[i] = s10[i];
        //this.checkAndSetTopScore();
    }

    public int [] getScore()
    {

        return this.s10;
    }

    public void setName(String n1)
    {
        this.n1 = n1;
    }

    public String getName()
    {
        return this.n1;
    }
}

import java.util.Scanner;

public class StudentTester
{
    public static void main(String args[])
    {

        Scanner kboardIn = new Scanner(System.in);

        int noOfStudents;

        System.out.print("Enter the number of students: ");
        noOfStudents = kboardIn.nextInt();
        //int[] noOfStudents;
        //noOfStudents = new int[100];

        StudentStore[] student1 = new StudentStore[noOfStudents];

        //int s1 = 0;
        int noOfPlayers = 5;
        int[] s10 = new int[noOfPlayers];
        //s10 = 0;
        String n1 = "something";
        int i = 0;

        for (int index = 0; index < student1.length; index++)
            student1[index] = new StudentStore(n1, s10, i);

            for (int index = 0; index <= student1.length; index++)
            {

                System.out.print("What is name of student no "+(index+1)+" ?");
                n1 = kboardIn.next();
                student1[index].setName(n1);
                System.out.print("What is mark for student no "+(index+1)+" ?");
                for(i=0; i < noOfPlayers; i++)
                {
                    s10[i] = kboardIn.nextInt();
                    student1[index].setScore(s10, i);
                    System.out.println("This is it" + s10[i]);
                }
                System.out.println(student1[index].getScore(      ));
                System.out.println(student1[index].getName());
                System.out.println(index);
                System.out.println(s10[index]);
                System.out.println(i);
                //System.out.println(s10[]);

            }

        for (int index = 0; index < student1.length; index++)

            System.out.println("\nTotal Mark for " + student1[index].getName()+ " is\t" + student1[index].getScore());

    }
}

A: System.out.println(student1[index].getScore()); you are getting the array, but printing an array will not give stored values in array. You should iterate over the array and print seperatly all values.

A: Thanks for the reply's. In the program System.out.println(student1[index].getScore()) is not printing a number. It is printing [I@137c6OD. I am not sure how to iterate over the array, but I will look up how to do it. Thanks a lot

A: It seems like you want to know how to loop over arrays. This is how you could achieve it:
String[] strings = {"hi","yo","test"};
for(String s : strings){
   System.out.println(s);
}


text:
Q: how to find same two special character in a fields in impala I have a case statement which derive specific portion of string field based on the condition.
example:
customer_id
7115878969-127881041-000000
650030087-1
130715315-1
2956599329-154074046-000000
127243855-1

Please find my current code below:
case
        when substr(reverse(trim(customer_id)),1,instr(reverse(trim(customer_id)),'-')-1)='000000'
        then split_part(customer_id, '-', 2)
        when substr(reverse(trim(customer_id)),1,instr(reverse(trim(customer_id)),'-')-1)<>'000000'
        then trim(substr(customer_id,1,instr(customer_id,'-')-1))
        --else  'error'
    end as PN

,
it check right side'000000'. but I need to change the condition based on the"-"
if two "-" then 127881041 middle portion of two"-"
if one "-" then 650030087
Thanks


text:
Q: Page not found(404) - polls views django tutorial Estou fazendo o tutorial da documentação do Django, na parte 3 (https://docs.djangoproject.com/en/3.1/intro/tutorial03/) onde é dito depois de adicionar alguns códigos o seguinte:

"Take a look in your browser, at "/polls/34/". It'll run the detail()
method and display whatever ID you provide in the URL. Try
"/polls/34/results/" and "/polls/34/vote/" too – these will display
the placeholder results and voting pages."

O problema é que ao acessar http://127.0.0.1:8000/polls/34/, eu recebo o erro:
Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/polls/34/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
admin/
polls/ [name='index']
The current path, polls/34/, didn't match any of these.
ja revisei o código zilhões de vezes, e to me frustrando...
settings.py
ROOT_URLCONF = 'mysite.urls'

mysite/urls
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('polls/', include('polls.urls')),
]

polls/views
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.

def index(request):
    return HttpResponse("Hello World. You're at the polls index.")

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

polls/urls.py
from django.urls import path

from . import views

urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
    # ex: /polls/5/
    path('<int:question_id>/', views.detail, name='detail'),
    # ex: /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

por que não ta funcionando???
se estiver faltando algum código por favor me avise .
Att: descobri que o problema é no Pycharm, já que no vs code funcionou tudo certinho, o problema pode ser a versão de python sendo utilizada?

A: O seu último código está mesmo em polls.models? Se sim, é aí que está o erro. Você precisa criar uma arquivo chamado 'urls.py' dentro do app 'polls'. É dessa maneira que o urls.py do seu projeto incluirá o 'polls.urls' (confira no segundo pedaço de código que você postou).


text:
Q: Efficient high-volume logger? I have a server which generates about 5MB/s of logs and much more during peaks. My initial test setup was to just use systemd to forward the output to rsyslog and then sending the data to a file. As I expected, this is very expensive with systemd-journal eating up a large chunk of my CPU resources and prevents the server from being able to handle traffic peaks.
I'm looking for a logging setup that would be both high-performance as well as support log rotation. I ran into the following article
https://medium.com/javarevisited/high-performance-logging-java-59ba374b2166
which mentions the memory mapped file appender for log4j. Log4j also has a rotating file logger, but these two do not compose, so I would need to use something external to rotate the logs. However, normally logrotate on the machine sends a HUP signal to tell syslog that a file has been rotated, so that it can close file handles and reopen the new file. This won't really work for a Java server using log4j.
Any recommendations for what to use? My code currently uses slf4j to actual emit stuff to logs, so a big plus if it can interoperate with it.


text:
Q: Modify JSTL import tag to show gzipped text in JSP In my JSPs I am currently using JSTL to show the contents of simple text files that reside on a server as follows:
c:import url="http://www.mysite.com/texts/name_id.txt" charEncoding="UTF-8"/>
These text files can be quite long and there are many of them so I want to compress them and serve the compressed version to the import tag. Can you give me some suggestions on how to modify the JSTL import tag, or create my own tag that achieves the same result when the text file is compressed? I suspect I should use Apache Commons Codec, or is java.util.zip enough?
For your reference, the source for the JSTL 1.2 import tag can be seen at:
http://grepcode.com/file/repo1.maven.org/maven2/javax.servlet/jstl/1.2/org/apache/taglibs/standard/tag/rt/core/ImportTag.java
http://grepcode.com/file/repo1.maven.org/maven2/javax.servlet/jstl/1.2/org/apache/taglibs/standard/tag/common/core/ImportSupport.java#ImportSupport
Regards

A: Create a servlet which is mapped on an URL pattern of /texts/* and does roughly the following job in doGet().
String path = request.getRequestURI().substring(request.getContextPath().length());
InputStream input = new GzipInputStream(getServletContext().getResourceAsStream(path));
OutputStream output = response.getOutputStream();
// Write input to output.

Note that the URL is based on your question and that you can keep your URLs in JSP unchanged this way.


text:
Q: Lighttpd: PHP_FCGI_CHILDREN correct value I'm running Lighttpd on 256MB RAM VPS (with low estimated traffic).
In order to optimize my server performances I decided to change these settings:
                    "PHP_FCGI_CHILDREN" => "1",
                    "PHP_FCGI_MAX_REQUESTS" => "20"

The reason why I set 1 child is that with setting there are 4 php_cgi processes:
2413 11336 /usr/bin/php-cgi
 2415  4592 /usr/bin/php-cgi
 2417 11336 /usr/bin/php-cgi
 2419 27656 /usr/bin/php-cgi
If I set 4 I get >8 children. I'm wondering why and if this is ok.
Now my webserver is very fast, because I finally don't rely on swapping so massively as before.
thanks

A: As you can see in this FAQ there are three config options that control the number of mod_php processes.

*

*PHP_FCGI_CHILDREN (defaults to 1)

*max-procs (defaults to 4)

*min-procs (ignored in current releases)

The formula to caluclate the initially spawned processes looks like this:
no_of_procs = max-procs * ( PHP_FCGI_CHILDREN + 1)

This means, for every procs in max-procs launch PHP_FCGI_CHILDREN workers +1 Guardian process for each parent in max-procs.

A: For newer lighttpd instances, you should set PHP_FCGI_CHILDREN to 0 and control the number of instances spawned.
This can help reduce the number of total processes running as there does not need to be extra master processes. However, if you are using a bytecode cache, set only 1 spawned master process and control the children below it.
Set PHP_MAX_REQUESTS to 500 to avoid another potential problem.


text:
Q: TensorFlow with R I am a beginner with TensorFlow. I have to use TensorFlow 1.8 .I am trying to replicate this code from pure R:
 t <- array(0, dim = 100)
 p <- array(TRUE, dim = 100)
 t[p] <- t[p] + 1

I have tried this:
    TF_t <- tf$Variable(t,tf$int32,name="TF_t")
    TF_p <- tf$Variable(p,tf$bool,name="TF_p")

    TF_t <- TF_t[TF_p ] + 1

    tf$device('/gpu:0')

But i have got an error:
TF_t <- TF_t[TF_p] + 1
Error in py_call_impl(callable, dots$args, dots$keywords) :
  TypeError: Only integers, slices (`:`), ellipsis (`...`), tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid indices, got <tf.Variable 'TF_p:0' shape=(3600013,) dtype=bool_ref>

I need p to be a logical vector, because it's a filter to the data that i want to change.
EDIT:

I have tried this:
TF_t[[p]] + 1 #are you sure this syntax is part of TensorFlow 1.8?

but it gives me error:
 Error in py_call_impl(callable, dots$args, dots$keywords) :
  TypeError: Only integers, slices (`:`), ellipsis (`...`), tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid`indices`

I have tried this one:
TF_timestep_number_inc <- (tf$boolean_mask(TF_t,TF_p)) + 1
step1 <- tf$group( (tf$boolean_mask(TF_tr,TF_p))$assign(TF_timestep_number_inc))

But it gives me error in the assignment:
Error in py_get_attr_impl(x, name, silent) :
  AttributeError: 'Tensor' object has no attribute 'assign'

A: As mentioned by @Ben373, you can use [[]] (not []) for indexing:
t <- array(0, dim = 100)
p <- array(TRUE, dim = 100)
t[p] <- t[p] + 1

TF_t <- tf$Variable(t,tf$int32,name="TF_t")

TF_t[[p]] + 1

tf.Tensor(
[2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2.
 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2.
 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2.
 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2.
 2. 2. 2. 2.], shape=(100,), dtype=float64)


text:
Q: It takes minutes to retrieve DB data I created a REST API to handle basic rest functions for a search catalog application. The user can submit search queries via a POST and it will submit the queries to a MYSQL table. This gets processed and the results sent via a separate application via feeds within an hour later.
My issue I am having is that a couple users can submit thousands of queries and the GET to retrieve these queries for the user, makes a simple request to the DB, but takes a long time to formulate the response. When the response was a simple list of single string queries it worked perfectly, within seconds. Now the response includes each query in its own json object with other meta data and a full array of objects is retrieved.I know it should not take this long so perhaps ideas on how to create the json might help.
            while (rs.next()){
                iquery = new Query();

                if (rs.isBeforeFirst() ) {
                     System.out.println("No data");
                     qExists = "";
                }
                System.out.println(rs.getString(1));

                QueryList.add(rs.getString(2));
                query.setqueryRule(rs.getString(2));
                query.setqueryName(rs.getString(1));
                if(rs.getTimestamp(5) != null){
                    query.setqueryExpiration(rs.getTimestamp(5));
                }else {
                    Thread.sleep(100);
                }

                query.setqueryID(rs.getString(3));
                query.setqueryGUD(rs.getString(4));
                query.setqueryCreated(rs.getTimestamp(6));
                if(rs.getTimestamp(7) != null){
                    query.setqueryModified(rs.getTimestamp(7));
                }else {
                    Thread.sleep(100);
                }

                query.toString();
                QueryList.add(query);

            }
            GreetingController.ResponseID = 1;
            return QueryList;

The class Query but it has all these different properties that I set as shown. But for some reason 50000 queries takes a long time as an example. I am showing below the example response a single query would like;
      "queries":[
     {
        "rule":"apple",
        "id":"y56473",
        "gid":"5bfufiddsd",
        "description":"apple's latest sneak peeks",
        "created":"2016-02-15T19:43:34Z",
        "modified":"2016-02-15T19:43:34Z",
        "expires":"2016-06-13T19:43:34Z"
     },

Any ideas appreciated.

EDIT:
MYSQL response time:
I ran the DB query and it was literally like 1-2 seconds.
id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
'1', 'SIMPLE', 'f', 'ref', 'idx_', '4', 'const', '15727', 'Using where'
'1', 'SIMPLE', 'd', 'const', 'PRIMARY', 'PRIMARY', '4', 'const', '1', 'Using index'


text:
Q: Why do I get this value when printf continues reading and shows the value of the next integer variables I'm not sure whether I'm asking a silly question.
We know that Printf function prints contiguous block of charaters until it finds a null character. Since, array b does not contain a null character and the format specifier in the 2nd printf command is %s, it prints 'xyzx' instead of 'xyz'. (I understand that) this is because the output included the value of a, which is x.
However, when I initialise the array a with value 'xy', the outputs from the 1st and 2nd printf commands become 'xyd' and 'xyzxyd' respectively. My question is why are we getting 'd' from the value of integer int1?
int main(void)
{
int int1 = 100;

char a[2] = "x";
char b[3] = "xyz";
printf("1.: %s\n", a);
printf("2.: %s\n", b);
  return 0;
}

A: Your code exhibits undefined behavior. It's not defined what should happen and compiler is allowed to do what it wants.

why are we getting 'd' from the value of integer int1?

Most probably your int has 4 bytes and your architecture is little endian. 100 is 0x64, so it is stored as 4 bytes as 0x64, 0x00, 0x00, 0x00. Most probably your system uses ASCII and 100 (or 0x64) is the ascii value of d, and the second byte is most probably interpreted as zero terminating character.

A: char b[3] = "xyz"; it has to be char b[4] = "xyz"; to accommodate the terminating nul character.

A:
Why do I get this value when printf continues reading and shows the value of the next integer variables (?)

The "%s" in printf("2.: %s\n", b); expects that b points to a string, a character array with a null character.  char b[3] = "xyz"; lacks a null character and is not a string.
The result is undefined behavior.
In this case, likely code kept printing other nearby memory like a[].

Either insure b is a string
//char b[3] = "xyz";
char b[4] = "xyz";  // b[3] is '\0'
printf("2.: %s\n", b);

Or print with a precision limit which limits printing.
char b[3] = "xyz";
//printf("2.: %s\n", b);
printf("2.: %.*s\n", (int) sizeof b, b);


text:
Q: If I have a web server with 10 process and 10 threads, what does that mean? http://pypi.python.org/pypi/Spawning/
So I'm playing with Spawning...
If I run it with 10 process and 10 threads, what does that mean?
I'm building a chat room (long-polling using eventlet).  Does that mean that only 10 people can be present in the chat room?

A: No. It all depends on the architecture of your application. Event-based apps can support large amounts of connections (users, sessions, whatever matters in your app) in a single thread.
You usually need multiple threads when you're performing blocking IO operations, and multiple processes when you need true computational load distribution. In something simple like a chat application, you can easily avoid the need for both. The standard Python library has the asyncore and asynchat modules which you may find interesting. The Twisted library is a more comprehensive approach.

A: No. Having a certain number of threads/processes doesn't create or change any kind of limit on the content or clients. Having more threads/processes can improve the performance of an application when balanced across them, especially on SMP systems where a single-thread or single-process architecture would be limited to one CPU.


text:
Q: How can I speed up compile time when using many extern type declarations The Project:
C++ Programming in xcode. I have over 3,000+ type definitions spread over 2,000+ .c/.h files. Each myType type contains a string description. I used a script to define a map<std::string, myType> of 3,000+ elements in a .cpp file to use for looking up a myType type to pass to a function that processes data based on which myType is passed to it. Because the myType definitions are spread over 2,000+ files, I used a script to write each extern myType TYPENAME; in a header file.
Overview:
(2,000+ .c files with myTypedefinitions)
myTypes.h (contains all the extern myType statements for each myType in the above files)
myTypes.cpp (contains the map<std::string, myType> of 3,000+ elements in the above files)
typeProcessor.cpp (includes myTypes.h. Uses the map defined in myTypes.cpp to match a string to a myType. Passes the myType to a function from the file below)
dataProcessor.cpp (processes data based on the myType passed to it)
The Problem:
Since I've added myTypes.h with 3,000+ extern statements and myTypes.cpp with a map of 3,000+ elements my project compile time has lengthened from 20 seconds to 1-1.5 hours.
My Question:
Without touching the 2,000+ files or the dataProcessor.cpp that receives the myType, what can I do to reduce the compile time?
Some thoughts I've had:

*

*use a script to put all the myType definitions into one big myTypes.cpp file and remove the extern statements. or

*use a script to #include each of the 2,000+ files containing the myType definitions
I don't know much about compilers, the main factors on compile time, and how to write code to minimize compile time. Any help is appreciated. Thank you.

A: Regardless of many things you could do/have done to structure your code better, why don't you

*

*create a public static registration function e.g. (typemap.h)

.
std::map<std::string, myTypeBase>& getGlobalTypeMap();
# define getGlobalTypeMap _once_ in typemap.cpp !

template <class myType>
  registerTypeMapping(std::string name, const myType& instance)
  {
       getGlobalTypeMap().insert(name, instance);
  }

*

*In every .cpp for a type definition, call the registration function. That way a type registers itself, and there is no need for the type map to 'know all the types'. This is inversion of dependency, in a simple form

*The crux is, that no file needs to include all the type headers for the registration process. You'll still need to include (selected) type headers if you need interfaces specific to the subtype (e.g. when using dynamic_cast<subtype> on a map element)
PS. I'm assuming some kind of common base type for myType (because there is no way you could get the std::map<std::string, myType> to compile otherwise)
Update
Edit

*

*Yes, you can make registerTypeMapping an extern "C" function (just edit the prototype to be C-conforming)

*For each type_xx.h/type_xx.c combi you can always generate an extra source file type_xx_register.c that includes just that type and registers it.

Note that this will lead to more sources but will likely reduce compile times. Especially, if you have a makefile and only compile the type_xx_register.o object file when it's dependencies truly changed.
That way, only a change in typemap.h would cause a recompilation of all these files.

It is also not impossible that a simple
$CC type*_register.cpp -o

_would be faster than the compilation of a single source including all type_xx.h at once_

A: As all these files don't change much (I'm assuming), it's either parsing the 3000+ line header or linking that kills the compile time. If it's parsing, a precompiled header should solve that, if it's linking, something like Visual Studio's incremental linking should help out, but I don't think any compiler except MSVC has this capability (correct me if I'm wrong).

A: it might be a matter of preventing a save on those 3,000 files
do the opposite of the xcode autosave method
this autosave off option is (very foolish) missing in newer versions of xcode (3.1 is a solid xcode) thus all files get a new timestamp and then the equivalent of a clean all rebuild.
try make on the commandline that doesn't save files as a speed comparison.


text:
Q: JUnit: Intercepting a method call and then invoking with different params I am working on junit and using PowerMockRunner to mock static methods.
I am aware that static methods can be mocked using when(...).thenReturn(...)
I need to mock a certain method that takes four arguments:
public static void addInputPath(String, Boolean, Integer, Double)

I need the third parameter(Integer) in any call to this method to be replaced by, say 10. All other parameters should just be passed as is.
In other words, I need to do something like this:
when(addInputPath(str, bool, intgr, dbl)).thenReturn(addInputPath(str, bool, 10, dbl));

Is there a way to do this?

A: So, when I get your requirements right, what you actually want to do is to intercept the call to addInputPath() and invoke it with a different parameter?
If so: I am not sure if this can be done with any mocking framework (and I doubt that it is possible). Mocking frameworks are about mocking calls; not about instrumenting/intercepting calls.
Coming back to your problem, this is a nice example why static calls far too often cause problems. Thus, the best solution in my eyes would be to change your method xyz() to avoid that thing calling addInputPath() directly. Like this:
interface InputPathAdder {
   void addInputPath(str, ... );
}

class ForwardingInputPathAdder implements InputPathAdder {
   // implements the method by calling the static method

and all of a sudden, you can also do:
class ForwardingInputPathAdderWithFixedIntegerParm implements InputPathAdder {
   // implements the method by calling the static method, but using 10 always

( obviously, naming could be improved here )
And now: you use dependency injection to give your "class under test" some Object implementing InputPathAdder. This could be either one that is completely mocked for testing; or it could be one that just does forwarding (in your production environment; or it could be the one that fixes the 3rd parameter). And no need for mocking for your "intercept" situation.


text:
Q: Creating Java Color objects using HSB values I am trying to use create a Color object using HSB value but I am having some trouble.
for(int i = 0; i<255; i++)
{
   Color c = Color.getHSBColor(i,100,100);
   System.out.println(c);
}

I would expect this to rotate through all hues, but instead every color has the same RGB value of RGB(251,251,2)
The output is
java.awt.Color[r=251,g=251,b=2]
java.awt.Color[r=251,g=251,b=2]
java.awt.Color[r=251,g=251,b=2]
....

Any idea what I am doing wrong?
Thanks

A: From the javadocs of Color#getHSBColor(float, float, float):
The s and b components should be
floating-point values between zero and one
(numbers in the range 0.0-1.0).  The h component
can be any floating-point number.  The floor of this number is
subtracted from it to create a fraction between 0 and 1.

In other words, the values don't range from 0 - 255, but from 0.0 - 1.0.


text:
Q: Angular close on outside click - closes also on inside click I am trying to implement close on out side click, the element is closing on outside click, but it closes also on an inside click, it should work like in the example : http://plnkr.co/edit/ybYmHtFavHnN1oD8vsuw?p=preview
I dont understand, why the element.find cant find the target, when it is his child.
HTML Directive

  <button data-ng-click="show = !show" class="dropbtn">Press</button>

   <multiple-date-picker></multiple-date-picker>

HTML Main

  <link rel="stylesheet" href="style.css" />
  <link rel="stylesheet" href="https://arca-computing.github.io/MultipleDatePicker/stylesheets/multipleDatePicker.css" />

  <multi-date></multi-date>

JS
var app = angular.module("app", ['multipleDatePicker']);
app.controller("cntrl", function($scope) {
});

app.directive('multiDate', function($document) {

  return {
    templateUrl: 'multi.html',
    replace: true,
    link: function(scope, element) {

      $document.bind('click', function(event) {
        var isClickedElementChildOfPopup = element
          .find(event.target)
          .length > 0;

        if (isClickedElementChildOfPopup)
          return;

        scope.show = false;
        scope.$apply();
      });
    }

  }

});

PLNKR

A: The directive seems to be fine.
You just need to add $event.stopPropagation to stop outer event.
<multiple-date-picker ng-click="$event.stopPropagation(); dateClickedModelChanged()" day-click="dateClicked" ng-model="dateTimeModel"></multiple-date-picker>

Here is your modified plunker


text:
Q: firebase notification not being shown, and token not being refreshed When I add this bundled dependency, 'com.google.android.gms:play-services:12.0.1' , (FirebaseInstanceIdService,FirebaseMessagingService) these two class are not responding.
Solutions I've tried :

*

*Adding firebase messaging dependency.

*Use my app's google-services.json in sample app and notifications were working fine ..

    <service android:name="com.Bookerr.android.services.MyFirebaseMessagingService"
            android:permission="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        <service android:name="com.Bookerr.android.services.MyFirebaseInstanceIDService"
            android:permission="true">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

        // this is my GRADLE FILE

        apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "com.Bookerr.android"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }

    /*compileOptions {
        targetCompatibility 1.8
        sourceCompatibility 1.8
    }*/
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.ss.bannerslider:bannerslider:1.8.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'uk.co.chrisjenx:calligraphy:2.2.0'
    implementation 'com.github.bumptech.glide:glide:4.8.0'
    implementation 'de.hdodenhof:circleimageview:2.2.0'
    implementation 'com.squareup.retrofit:retrofit:1.9.0'
    implementation 'com.squareup.okhttp:okhttp:2.7.5'
    implementation 'com.squareup:otto:1.3.8'
    implementation 'com.afollestad.material-dialogs:core:0.9.6.0'
    implementation 'com.stripe:stripe-android:6.1.2'
    implementation 'com.stripe:stripe-java:5.33.2'
    implementation 'com.stripe:stripe-android-pay:4.1.3'
    implementation 'io.branch.sdk.android:library:2.19.5'
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'com.github.sundeepk:compact-calendar-view:2.0.2.3'
    implementation 'com.koushikdutta.ion:ion:2.2.1'

//    implementation 'com.google.android.gms:play-services-auth:16.0.1'
//    implementation 'com.google.android.gms:play-services-plus:16.0.0'
//    implementation 'com.google.android.gms:play-services-gcm:16.0.0'
//    implementation 'com.google.android.gms:play-services-maps:16.0.0'
//    implementation 'com.google.android.gms:play-services-location:16.0.0'
//    implementation 'com.google.android.gms:play-services-places:16.0.0'
//    implementation 'com.google.android.gms:play-services-vision:17.0.2'

//    implementation 'com.google.firebase:firebase-storage:16.0.5'
//    implementation 'com.google.firebase:firebase-messaging:17.3.4'
//    implementation 'com.google.firebase:firebase-core:16.0.7'
//    implementation 'com.google.firebase:firebase-database:16.0.6'
//    implementation 'com.google.firebase:firebase-auth:16.1.0'
//    implementation 'com.firebaseui:firebase-ui-auth:0.6.0'
//
    implementation 'com.google.android.gms:play-services:12.0.1'

    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    testImplementation 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'