text
stringlengths
64
81.1k
meta
dict
Q: Good way to include programming code interspersed with explanation It is common to have pieces of (programming) code I write, and I want to prepare an explanatory report. Then, I, while working on it, often still revise the code, as well as writing explanatory notes. So, I wish to include my code content saved elsewhere, into the report. I want to scatter my comments in several portions, among the code pieces, rather than include it entirely. With pdflatex, what is a good way to do this? I know there is a package lstlisting, but there are two shortcomings (as I see it). Consider \documentclass[12pt]{article} \usepackage{listings} \begin{document} \begin{lstlisting} Now including `bar.md`: \input{bar.md} \end{lstlisting} \end{document} And bar.md is whatever I saved in the same directory. First, the \input{bar.md} is treated verbatim, and bar.md is not included. Second, as I said, the block of code being included cannot be split in several parts. Or for example, may I to implement a function \include_my_code to be used as thus? \documentclass[12pt]{article} \begin{document} \include_my_code{bar.md}{1}{20} (Now follows line 1 to 20 of `bar.md`) \include_my_code{bar.md}{21}{40} (Now follows line 21 to 40 of `bar.md`) \end{document} A: About 2 years ago, I wanted to adapt/upgrade my verbatimbox package to conveniently allows things like you request. I got sidetracked along the way, and never finished it. But just so it doesn't go down the memory hole if I fail to get back to it, I will post the last know state of the code here First, the document that creates the output: \documentclass{article} \usepackage{verbatimbox} \begin{document} \def\vbxcodestyle{\ttfamily\scriptsize\strut} \#1 % \setvbxfieldwidth[.06\linewidth]{.74\linewidth}% \def\vbxformat{% \vbxtitlerule=1pt\relax% \setvbxfieldwidth[.06\linewidth]{.74\linewidth}% \vbxtitle{% Verbbox \thenextvbxcount. This is the title.}% \vbxfieldcolor% \vbxnum% \invbxline{11}{\vbxcommentwidth{.22\vbxfieldwidth}% \vbxcomment{I am drawing attention to ``Hello World''}}{}% \invbxline{15}{\vbxcommentwidth{.22\vbxfieldwidth}% \vbxcomment[\normalsize]{I like \LaTeX{}}}{}% \vbxcodestyle% } \begin{verbbox}[\vbxformat] #include <stdio.h> #define N 10 /* Block * comment */ int main() { int i; // Line comment. puts("Hello world!"); for (i = 0; i < N; i++) { puts("LaTeX is also great for programmers!"); } return 0; } \end{verbbox} {\noindent\centering\vbxrebox{\theverbbox}\par} \#2 %\setvbxfieldwidth[.23\linewidth]{.74\linewidth}% \def\vbxformat{% \setvbxfieldwidth[.23\linewidth]{.74\linewidth}% \vbxtitle{% Verbbox \thenextvbxcount. This is the title\\ for my code on\\\today{}}% \invbxline{1}{% \vbxfieldcolor[green!8]\vbxnumcolor{green!75!black}% }{% \invbxlines{3}{4}{% \vbxfieldcolor\vbxnumstyle{\color{red}\normalsize$\rightarrow$}% }{% \invbxlines{8}{18}{% \vbxfieldcolor[blue!12!gray!15]\vbxnumcolor{black!20}% }{% \vbxfieldcolor[cyan!3]\vbxnum% }% }% }% \invbxline{11}{\vbxcommentwidth{.22\vbxfieldwidth}% \vbxcomment{I am drawing attention to ``Hello World''}}{}% \invbxline{15}{\vbxcommentwidth[-.3\vbxfieldwidth]{.22\vbxfieldwidth}% \vbxcomment[\normalsize]{I like \LaTeX{}}}{}% \vbxcodestyle\,% } \begin{verbbox}[\vbxformat] #include <stdio.h> #define N 10 /* Block * comment */ int main() { int i; // Line comment. puts("Hello world!"); for (i = 0; i < N; i++) { puts("LaTeX is also great for programmers!"); } return 0; } \end{verbbox} {\noindent\centering\vbxrefbox{\theverbbox}\par} \noindent x\hrulefill x \#3 \VerbCodeIndent=.06\linewidth\relax \def\vbxformat{% \setvbxfieldwidth[.06\linewidth]{.94\linewidth}% \vbxtitlerule=1pt\relax% \vbxtitle{% Verbbox \thenextvbxcount. This is the title. for a nobox environment, which allows for page breaks}% \vbxfieldcolor% \vbxnum% \invbxline{11}{\vbxcommentwidth{.22\vbxfieldwidth}% \vbxcomment{I am drawing attention to ``Hello World''}}{}% \invbxline{15}{\vbxcommentwidth{.22\vbxfieldwidth}% \vbxcomment[\normalsize]{I like \LaTeX{}}}{}% \vbxcodestyle% } \begin{verbnobox}[\vbxformat] #include <stdio.h> #define N 10 int main() { int i; // Line comment. puts("Hello world!"); for (i = 0; i < N; i++) { puts("LaTeX is also great for programmers!"); } return 0; } #include <stdio.h> #define N 10 int main() { int i; // Line comment. puts("Hello world!"); for (i = 0; i < N; i++) { puts("LaTeX is also great for programmers!"); } return 0; } \end{verbnobox} \noindent x\hrulefill x \#4 \def\vbxformat{% % \setvbxfieldwidth[.06\linewidth]{.94\linewidth}% \vbxtitlerule=1pt\relax% \vbxtitle{% Verbbox \thenextvbxcount. This is the title.}% \vbxfieldcolor% \vbxnum% \invbxline{4}{\vbxcommentwidth{.22\vbxfieldwidth}% \vbxcomment[\normalsize]{I like \LaTeX{}}}{}% \vbxcodestyle% } \VerbCodeIndent=38pt\relax \setvbxfieldwidth[.05\linewidth]{.87\linewidth}% \noindent\verbfilenobox[\vbxformat]{samplecode.txt} \#5 \verbfilebox[\vbxformat]{samplecode.txt} {\centering\vbxrefbox{\theverbbox}\par} \#6 \begin{myverbbox}[\vbxformat]{\myvb} for (i = 0; i < N; i++) { puts("LaTeX is also great for programmers!"); } return 0; \end{myverbbox} \noindent\myvb {\centering\vbxrebox{\myvb}\par} \#7 \fboxrule=2pt \VerbCodeIndent=66pt\relax \begin{cverbbox}[\scriptsize\vbxnum]{blue}{cyan!5}{green} for (i = 0; i < N; i++) { puts("LaTeX is also great for programmers!"); } return 0; \end{cverbbox} \noindent\theverbbox \#8 \VerbCodeIndent=22pt\relax \begin{mycverbbox}[\tiny]{blue}{cyan!5}{green}{mycvb} for (i = 0; i < N; i++) { puts("LaTeX is also great for programmers!"); } return 0; \end{mycverbbox} \noindent\mycvb \#9 \VerbCodeIndent=44pt\relax \begin{verbbox}[\tiny] for (i = 0; i < N; i++) { puts("LaTeX is also great for programmers!"); } return 0; \end{verbbox} \noindent\fbox{\theverbbox} \#10 \VerbCodeIndent=66pt\relax \begin{myverbbox}[\tiny]{\myvb} for (i = 0; i < N; i++) { puts("LaTeX is also great for programmers!"); } return 0; \end{myverbbox} \noindent\fbox{\myvb} \end{document} Here is the trial adaptation of verbatimbox.sty: \def\verbatimboxVersionNumber{v4.00 } \ProvidesPackage{verbatimbox} [2015/01/31 \verbatimboxVersionNumber Routines for placing verbatim text into boxes, useful in places where the verbatim environment is inaccessible. Secondarily, for adding vertical buffer around an object.] % % This work may be distributed and/or modified under the % conditions of the LaTeX Project Public License, either version 1.3 % of this license or (at your option) any later version. % The latest version of this license is in % http://www.latex-project.org/lppl.txt % and version 1.3c or later is part of all distributions of LaTeX % version 2005/12/01 or later. % % This work has the LPPL maintenance status `maintained'. % % The Current Maintainer of this work is Steven B. Segletes. % % verbatimbox.sty is based on boxedverbatim environment found % in moreverb.sty. % % An enabling routine, \addvbuffer[]{} shares some functional % similarities to \raisebox, but it is not the same. % % 2.01 -Added LPPL License info to package % 3.0 -Added myverbbox environment % -Corrected problem when no optional arguments are passed to % verbbox environment % -Added optional arguments to \addvbuffer % -Fixed \verbfilebox so that it restored \verbatim@processline % -Produced real documentation % 3.01 -renamed \macro@name so as not to conflict with (I think) ltxdoc % package % 3.1 -Corrected default argument to \addvbuffer so that it wouldn't % break. Also, gave better guidance in documentation to use % of optional argument to \addvbuffer % -Added verbnobox environment and \verbfilenobox macro % -Improved documentation showing line-specific optional arguments % 3.11 -Eliminated the use of the stringstrings package, which resets % the definition of \| % 3.12 -Corrected bug introduced in V3.11, which occured with [t] % option to \theverbbox % -When using two lengths in \addvbuffer optional argument, % they MUST be individually in {}, rather than "~" or "\ " between % 3.13 -Corrected residual bug from V3.11, when \addvbuffer called % without an optional argument. % 4.00 -Added cverbbox and mycverbbox environments for color % -Added host of code highlighting routines. \NeedsTeXFormat{LaTeX2e} \@ifundefined{verbatim@processline}{\RequirePackage{verbatim}}{} \RequirePackage{xcolor} \RequirePackage{readarray} % Following 3 lines thanks to Prof. Enrico Gregorio, from: % http://tex.stackexchange.com/questions/42318/ % removing-a-backslash-from-a-character-sequence \begingroup\lccode`\|=`\\ \lowercase{\endgroup\def\removebs#1{\if#1|\else#1\fi}} \newcommand{\@macro@name}[1]{\expandafter\removebs\string#1} % \newcounter{VerbboxLineNo} \newlength\VerbCodeIndent \newcommand\vbxstartline[1]{\setcounter{VerbboxLineNo}{\numexpr#1-1\relax}} \newcommand\vbxContinueLineNoAfter{\let\vbx@lineprotocol\vbx@continuelineno} \newcommand\vbxResetLineNoAfter{\let\vbx@lineprotocol\vbx@resetlineno} \newcommand\vbx@continuelineno{\resetvbxtitle} \newcommand\vbx@resetlineno{\setcounter{VerbboxLineNo}{0}\resetvbxtitle} \vbxResetLineNoAfter \vbxstartline{1} \global\newsavebox{\savedverbbox} %%%%%ORIGINAL FORM%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The verbbox environment is based on % the boxedverbatim environment found in moreverb.sty % The optional argument allows the user to modify properties of the text % such as fontsize % \newenvironment{origverbbox}[1][]{% \def\verbatim@processline{% {\setbox0=\hbox{\the\verbatim@line}% \hsize=\wd0 \the\verbatim@line\par}}% \@minipagetrue% \@tempswatrue% \setbox0=\vbox\bgroup #1 \verbatim } {% \endverbatim \unskip\setbox0=\lastbox % \egroup \global\sbox{\savedverbbox}{\box0} } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % David Carlisle provided the \verbbox@inner approach to avoid % problem when no optional argument is provided to verbbox environment: % http://tex.stackexchange.com/questions/109030/optional-arguments-in % -verbatim-environments \newcommand\verbbox@inner[1][]{{\nfss@catcodes\scantokens{\gdef\@tmp{#1}}}} \def\@tmp{} \newenvironment{verbbox}{% \addtocounter{VerbboxLineNo}{-1}% % FOR SOME REASON, USING \my@par INSTEAD OF \par PREVENTS EXTRA SPACE % ABOVE verbbox WHEN USING OPTIONAL ARGUMENTS \let\my@par\par% \def\verbatim@processline{% % FIRST \@tmp APPLIES OPTIONAL ARGUMENT TO EACH VERBATIM LINE % SECOND \@tmp MAKES SURE ANY PRINTED MATTER OF OPTIONAL ARGUMENT % IS ACCOUNTED FOR IN VERBATIM BOX WIDTH {\addtocounter{VerbboxLineNo}{1}% \rule{\VerbCodeIndent}{0pt}% \@tmp\setbox0=\hbox{\@tmp\the\verbatim@line}% \hsize=\wd0 \the\verbatim@line\my@par}}% \@minipagetrue% \@tempswatrue% \setbox0=\vbox\bgroup \verbatim\verbbox@inner% } {% \endverbatim% \unskip\setbox0=\lastbox % \egroup% \global\sbox{\savedverbbox}{\box0\rule{\VerbCodeIndent}{0pt}}% \global\def\@tmp{}% \global\vbx@lineprotocol% } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The myverbbox environment is altered from verbbox environment % The optional argument allows the user to modify properties of % the text such as fontsize % The mandatory argument is a command which is formed so as to % regurgitate the boxed content created within the environment % \newenvironment{myverbbox}[2][]{% % \addtocounter{VerbboxLineNo}{-1}% \def\verbatim@processline{% % THE FIRST #1 ACCOUNTS FOR NON-PRINTING COMMANDS; THE SECOND #1 IS FOR % PRINTED OPTIONAL MATERIAL {\addtocounter{VerbboxLineNo}{1}% \rule{\VerbCodeIndent}{0pt}% #1\setbox0=\hbox{#1\the\verbatim@line}% \hsize=\wd0 \the\verbatim@line\par}}% \@minipagetrue% \@tempswatrue% \global\edef\sv@name{\@macro@name{#2}}% \@ifundefined{\sv@name content}{% \expandafter\newsavebox\expandafter{\csname\sv@name content\endcsname}% }% \expandafter\global\expandafter\edef\csname\sv@name\endcsname{\usebox{% \csname\sv@name content\endcsname}}% \setbox0=\vbox\bgroup \verbatim } {% \endverbatim% \unskip\setbox0=\lastbox % \egroup% \global\sbox{\csname\sv@name content\endcsname}{% \box0\rule{\VerbCodeIndent}{0pt}}% \global\vbx@lineprotocol% } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The verbfilebox command is like the verbbox environment, but takes % a file as input, rather than text typed into an environment. % The optional argument allows the user to modify properties of the text % such as fontsize % Example: \verbfilebox[\scriptsize]{myfile} \let\sv@verbatim@processline\verbatim@processline \newcommand\verbfilebox[2][]{% % \addtocounter{VerbboxLineNo}{-1}% \def\verbatim@processline{% {\addtocounter{VerbboxLineNo}{1}% \rule{\VerbCodeIndent}{0pt}% #1\setbox0=\hbox{#1\the\verbatim@line}% \hsize=\wd0 \the\verbatim@line\par}}% \@minipagetrue% \@tempswatrue% \setbox0=\vbox\bgroup \verbatiminput{#2} \unskip\setbox0=\lastbox % \egroup \global\sbox{\savedverbbox}{\box0} \let\verbatim@processline\sv@verbatim@processline \global\vbx@lineprotocol% } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \newcommand\theverbbox[1][x]{% \if #1t% % The t option is for outputting the savedverbbox inside a tabular % environment (else insufficent vertical space above box) \addvbuffer[{\boxtopsep} {\boxbottomsep}]{\usebox{\savedverbbox}}% \else% \usebox{\savedverbbox}% \fi% } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % \addvbuffer is based on \fbox, % but without a frame. Empty buffer space % is added above and below the object, making a new box. % An optional argument can specify the buffer spaces or, if no % optional argument is specified: % above the box is added \boxtopsep (initially 3pt) vertical space; % below the box is added \boxbottomsep (initially 0pt) vertical space. % \newdimen\boxtopsep \newdimen\boxbottomsep \newdimen\ps@tempdima \newbox\ps@tempboxa \setlength\boxtopsep{3pt} \setlength\boxbottomsep{0pt} \long\def\add@vbuffer#1{\leavevmode\setbox\ps@tempboxa\hbox{#1}\ps@tempdima 0pt \advance\ps@tempdima \dp\ps@tempboxa \hbox{\lower\ps@tempdima\hbox {\vbox{\hbox{\vbox{\vskip\boxtop@sep \box\ps@tempboxa \vskip \boxbottom@sep}}}}}} \global\newlength\boxtop@sep \global\newlength\boxbottom@sep \newcommand\addvbuffer[2][{\boxtopsep} {\boxbottomsep}]{% \getargsC{#1}% \setlength\boxtop@sep{\argi}% \if1\narg\setlength\boxbottom@sep{\argi}\else% \setlength\boxbottom@sep{\argii}\fi% \add@vbuffer{#2}% } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The following two "nobox" commands are basically versions of % \verbatiminput and \verbatim that have been adapted to take the % optional argument style of this package. No boxes are created, % but breaking across page boundaries is not a problem here, as % it would be with a box. \newcommand\verbfilenobox[2][]{% % \addtocounter{VerbboxLineNo}{-1}% \def\verbatim@processline{% {\addtocounter{VerbboxLineNo}{1}% \rule{\VerbCodeIndent}{0pt}% #1\setbox0=\hbox{#1\the\verbatim@line}% \hsize=\wd0 \the\verbatim@line\par}}% \verbatiminput{#2} \let\verbatim@processline\sv@verbatim@processline \global\vbx@lineprotocol% } \newenvironment{verbnobox}{% \addtocounter{VerbboxLineNo}{-1}% % FOR SOME REASON, USING \my@par INSTEAD OF \par PREVENTS EXTRA SPACE % ABOVE verbbox WHEN USING OPTIONAL ARGUMENTS \let\my@par\par% \def\verbatim@processline{% % FIRST \@tmp APPLIES OPTIONAL ARGUMENT TO EACH VERBATIM LINE % SECOND \@tmp MAKES SURE ANY PRINTED MATTER OF OPTIONAL ARGUMENT % IS ACCOUNTED FOR IN VERBATIM BOX WIDTH {\addtocounter{VerbboxLineNo}{1}% \rule{\VerbCodeIndent}{0pt}% \@tmp\setbox0=\hbox{\@tmp\the\verbatim@line}% \hsize=\wd0 \the\verbatim@line\my@par}}% \verbatim\verbbox@inner% } {% \endverbatim% \global\def\@tmp{}% \global\vbx@lineprotocol% } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The cverbbox and mycverbbox macros add color capability to % verbbox'es. In addition to the standard optional argument % that is supported by this package, cverbbox additionally % takes 3 mandatory arguments: font color, background color, % and frame color. The mycverbbox environment additionally % takes a verbbox name as a final argument. \newenvironment{mycverbbox}[5][]{% % \addtocounter{VerbboxLineNo}{-1}% \def\verbatim@processline{% % THE FIRST #1 ACCOUNTS FOR NON-PRINTING COMMANDS; THE SECOND #1 IS FOR % PRINTED OPTIONAL MATERIAL {\addtocounter{VerbboxLineNo}{1}% \rule{\VerbCodeIndent}{0pt}% #1\setbox0=\hbox{#1\the\verbatim@line}% \hsize=\wd0 \the\verbatim@line\par}}% \@minipagetrue% \@tempswatrue% \global\edef\sv@name{\@macro@name{#5}}% \global\edef\cverbboxColor{#3}% \global\edef\cverbboxFColor{#4}% \@ifundefined{\sv@name content}{% \expandafter\newsavebox\expandafter{\csname\sv@name content\endcsname}% }% \expandafter\global\expandafter\edef\csname\sv@name\endcsname{\usebox{% \csname\sv@name content\endcsname}}% \setbox0=\vbox\bgroup\color{#2} \verbatim } {% \endverbatim% \unskip\setbox0=\lastbox % \egroup% \setbox1=\hbox{% \colorbox{\cverbboxColor}{\box0\rule{\VerbCodeIndent}{0pt}}}% \global\sbox{\csname\sv@name content\endcsname}% {% \fboxsep=\fboxrule\colorbox{\cverbboxFColor}{\box1}}% \global\vbx@lineprotocol% } \newenvironment{cverbbox}[4][]{% % \addtocounter{VerbboxLineNo}{-1}% \def\verbatim@processline{% % THE FIRST #1 ACCOUNTS FOR NON-PRINTING COMMANDS; THE SECOND #1 IS FOR % PRINTED OPTIONAL MATERIAL {\addtocounter{VerbboxLineNo}{1}% \rule{\VerbCodeIndent}{0pt}% #1\setbox0=\hbox{#1\the\verbatim@line}% \hsize=\wd0 \the\verbatim@line\par}}% \@minipagetrue% \@tempswatrue% \global\edef\cverbboxColor{#3}% \global\edef\cverbboxFColor{#4}% \setbox0=\vbox\bgroup\color{#2} \verbatim } {% \endverbatim% \unskip\setbox0=\lastbox % \egroup% \setbox1=\hbox{% \colorbox{\cverbboxColor}{\box0\rule{\VerbCodeIndent}{0pt}}}% \global\sbox{\savedverbbox}{% \fboxsep=\fboxrule\colorbox{\cverbboxFColor}{\box1}}% \global\vbx@lineprotocol% } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Here are a series of macros for highlighting code (not syntax % highlighting), \newlength\@vbxcolorfieldoverlap \newlength\vbxfieldwidth \newlength\@vbxcommentindent \newlength\@vbxcommentwidth \newlength\vbxcommentrule \newlength\vbxcommentsep \newlength\vbxtitlerule \newlength\vbxtitlesep \newlength\vbxnumbergap \newlength\vbxleftfieldwidth \newlength\gvbxfieldwidth \newlength\gvbxleftfieldwidth \newsavebox\@thevbxcolorfield \setlength\@vbxcolorfieldoverlap{.1pt}% PREVENTS THIN WHITE LINES IN LISTING \setlength\@vbxcommentindent{.75\vbxfieldwidth} \setlength\@vbxcommentwidth{.24\vbxfieldwidth} \newcounter{vbxcount} % USER MODIFIABLE \def\vbxdefaultcolorfield{black!5} \setlength\vbxnumbergap{2pt} \def\vbxnumberformat{\arabic{VerbboxLineNo}:} \def\vbxnumberstyle{\sffamily\scriptsize} \def\vbxcodestyle{\ttfamily\footnotesize\strut} \setlength\vbxleftfieldwidth{0pt} \setlength\vbxfieldwidth{\linewidth} % \def\vbxcommentstyle{\vbxcodestyle\rmfamily} \def\vbxcommenttextcolor{blue!70!black} \def\vbxcommentfieldcolor{yellow!13} \def\vbxcommentrulecolor{red} \setlength\vbxcommentrule{1pt} \setlength\vbxcommentsep{1pt} % \def\vbxtitlestyle{\centering\rmfamily\small} \def\vbxtitletextcolor{black} \def\vbxtitlefieldcolor{yellow!25} \def\vbxtitlerulecolor{black} \setlength\vbxtitlerule{.5pt} \setlength\vbxtitlesep{1pt} %%%%% \newcommand\@setcolorvbxfield[1]{% \savebox{\@thevbxcolorfield}{% \smash{\makebox[0pt][l]{\vbxcodestyle\textcolor{#1}{% \rule[\dimexpr-\@vbxcolorfieldoverlap-\dp\strutbox]{\vbxfieldwidth}% {\dimexpr\ht\strutbox+\dp\strutbox+2\@vbxcolorfieldoverlap}}}}}% } \newcommand\vbxfieldcolor[1][\vbxdefaultcolorfield]{\@setcolorvbxfield{#1}\usebox{\@thevbxcolorfield}} \newcommand\vbxnum[1][0ex]{\makebox[#1][r]{\smash{% \vbxnumberstyle\vbxnumberformat}\hspace{\vbxnumbergap}}} \newcommand\vbxnumstyle[2][0ex]{\makebox[#1][r]{\smash{% \vbxnumberstyle#2\vbxnumberformat}\hspace{\vbxnumbergap}}} \newcommand\vbxnumcolor[2][0ex]{\makebox[#1][r]{\smash{% \textcolor{#2}{\vbxnumberstyle\vbxnumberformat}}\hspace{\vbxnumbergap}}} \newcommand*\invbxline[3]{\ifnum\value{VerbboxLineNo}=#1\relax#2\else#3\fi} \newcommand*\invbxlines[4]{% \ifnum\value{VerbboxLineNo}<#1\relax#4\else% \ifnum\value{VerbboxLineNo}>#2#4\else#3\fi% \fi% } \newcommand\vbxcomment[2][]{\vbxcodestyle#1\fboxsep=0pt\smash{\rlap{% \textcolor{\vbxcommentrulecolor}{% \rule[-\vbxcommentrule]{\@vbxcommentindent}{\vbxcommentrule}% \ifdim\@vbxcommentindent<0pt\relax% \rlap{\rule[-\vbxcommentrule]{-\@vbxcommentindent}{\vbxcommentrule}}% \fi% }% \raisebox{\dimexpr\dp\strutbox+\vbxcommentsep}{% \textcolor{\vbxcommentrulecolor}{\colorbox{\vbxcommentfieldcolor}{% \fboxsep=\vbxcommentsep% \fboxrule=\vbxcommentrule% \fbox{\parbox[b]{% \dimexpr\@vbxcommentwidth-2\vbxcommentrule-2\vbxcommentsep}% {\color{\vbxcommenttextcolor}\vbxcommentstyle% #1\strut#2\strut}}}}}}}% } \newcommand\setvbxfieldwidth[2][0pt]{% \setlength\vbxfieldwidth{#2}% \global\setlength\gvbxfieldwidth{\vbxfieldwidth}% \setlength\vbxleftfieldwidth{#1}% \global\setlength\gvbxleftfieldwidth{\vbxleftfieldwidth}% } \newcommand\vbxcommentwidth[2][-\textwidth]{% \setlength\@vbxcommentwidth{#2}% \ifdim#1>-\textwidth\setlength\@vbxcommentindent{#1}\else% \setlength\@vbxcommentindent{% \dimexpr\vbxfieldwidth-#2-\vbxtitlerule\relax}\fi% } \newcommand\mastervbxtitle[1]{\fboxsep=0pt% \rule{-\vbxleftfieldwidth}{0pt}% \textcolor{\vbxtitlerulecolor}{\colorbox{\vbxtitlefieldcolor}{% \fboxsep=\vbxtitlesep% \fboxrule=\vbxtitlerule% \fbox{\parbox{\dimexpr\vbxfieldwidth-2\vbxtitlerule-2\vbxtitlesep% +\vbxleftfieldwidth\relax}{% \vbxtitlestyle\textcolor{\vbxtitletextcolor}{#1}}}}}\\% \rule{\VerbCodeIndent}{0pt}% \global\let\vbxtitle\@gobble% } \def\resetvbxtitle{\global\let\vbxtitle\mastervbxtitle} \resetvbxtitle \newcommand\vbxrebox[1]{% \hspace{\dimexpr\gvbxleftfieldwidth-\VerbCodeIndent\relax}% \makebox[\dimexpr\gvbxfieldwidth+\VerbCodeIndent\relax][l]{#1}} \newcommand\vbxrefbox[1]{% \fboxrule=\vbxtitlerule\relax% \fboxsep=-\fboxrule% \textcolor{\vbxtitlerulecolor}{\fbox{\vbxrebox{#1}}}% } \def\thenextvbxcount{\stepcounter{vbxcount}\thevbxcount} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \endinput And here is the output:
{ "pile_set_name": "StackExchange" }
Q: Android - Share Intent for ES File Explorer I want to create an app specifically aimed to launch the ES File Explorer Share by LAN intent. I have the latest Manifest for this app: <?xml version="1.0" encoding="utf-8"?> <manifest ... > <uses-permission ... /> <uses-feature ... /> <uses-sdk ... /> <supports-screens ... /> <application ... android:name="com.estrongs.android.pop.FexApplication" ... > ... <activity android:theme="@16973830" android:label="@2131427483" android:name="com.estrongs.android.pop.view.FileExplorerActivity" android:launchMode="singleTop" android:configChanges="keyboardHidden|orientation|screenSize" android:windowSoftInputMode="stateUnspecified|adjustPan"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="resource/folder"/> </intent-filter> <intent-filter> <action android:name="org.openintents.action.VIEW_DIRECTORY"/> <category android:name="android.intent.category.DEFAULT"/> <data android:scheme="file"/> </intent-filter> <intent-filter> <action android:name="com.estrongs.android.SHOW_DISK_USAGE"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> <activity android:name="com.estrongs.android.pop.app.PopPreferenceActivity" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:name="com.estrongs.android.pop.app.ESNetSettingActivity"/> <activity android:name="com.estrongs.android.pop.app.RecommAcitivity" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:name="com.estrongs.android.pop.app.RecommItemDetailAcitivity" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:name="com.estrongs.android.pop.app.RecommItemImageViewer" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:theme="@2131492869" android:name="com.estrongs.android.pop.app.OpenRecomm" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:theme="@16973835" android:name="com.estrongs.android.ui.view.CreateOAuthNetDisk" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:theme="@16973835" android:name="com.estrongs.android.ui.view.PcsThirdPartOAuth" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:theme="@16973835" android:name="com.estrongs.android.ui.view.CreateOAuthServiceProvider" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:theme="@16973840" android:icon="@2130837715" android:name="com.estrongs.android.pop.app.compress.CompressionActivity" android:configChanges="keyboardHidden|orientation|screenSize"> <intent-filter android:label="@2131427488"> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> <activity android:theme="@16973840" android:icon="@2130837715" android:name="com.estrongs.android.pop.app.compress.CompressionProxyActivity" android:configChanges="keyboardHidden|orientation|screenSize"> <intent-filter android:label="@2131427488"> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="application/zip"/> <data android:mimeType="application/x-rar-compressed"/> <data android:mimeType="application/rar"/> <data android:mimeType="application/x-gzip"/> </intent-filter> </activity> <activity android:theme="@16973840" android:icon="@2130837714" android:name="com.estrongs.android.pop.app.ESFileSharingActivity" android:configChanges="keyboardHidden|orientation|screenSize"> <intent-filter android:label="@2131427545"> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> <intent-filter android:label="@2131428206"> <action android:name="android.intent.action.SEND"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="*/*"/> </intent-filter> <intent-filter android:label="@2131428206"> <action android:name="android.intent.action.SEND_MULTIPLE"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="*/*"/> </intent-filter> </activity> <activity android:theme="@16973830" android:label="@2131427545" android:icon="@2130837714" android:name="com.estrongs.android.pop.app.LocalFileSharingActivity" android:configChanges="keyboardHidden|orientation|screenSize"> <intent-filter android:label="@2131427545"> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> <activity android:theme="@16973835" android:name="com.estrongs.android.pop.app.FileSharingNotificationActivity" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity ... android:name="com.estrongs.android.pop.app.PopVideoPlayer" ... > ... </activity> <activity ... android:name="com.estrongs.android.pop.app.PopVideoPlayerProxyActivity" ... </activity> <activity ... android:name="com.estrongs.android.pop.app.AudioPlayerProxyActivity" ... </activity> <activity android:name="com.estrongs.android.pop.app.StreamingMediaPlayer" ... /> <service ... /> <receiver ... </receiver> <activity ... android:name="com.estrongs.android.pop.app.editor.PopNoteEditor" android:configChanges="keyboardHidden|orientation|screenSize" android:hardwareAccelerated="false"> <intent-filter android:label="@2131427486"> <action android:name="android.intent.action.VIEW"/> <action android:name="android.intent.action.EDIT"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/*"/> </intent-filter> </activity> <activity android:theme="@16973836" android:label="@2131427486" android:icon="@2130837713" android:name="com.estrongs.android.pop.app.BTPopNoteEditor" android:launchMode="singleInstance" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:theme="@16973839" android:label="@2131427483" android:name="com.estrongs.android.pop.app.FileChooserActivity" android:configChanges="keyboardHidden|orientation|screenSize"> <intent-filter> <action android:name="com.estrongs.action.PICK_FILE"/> <category android:name="android.intent.category.DEFAULT"/> <data android:scheme="file"/> </intent-filter> <intent-filter> <action android:name="com.estrongs.action.PICK_FILE"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> <intent-filter> <action android:name="com.estrongs.action.PICK_DIRECTORY"/> <category android:name="android.intent.category.DEFAULT"/> <data android:scheme="file"/> </intent-filter> <intent-filter> <action android:name="com.estrongs.action.PICK_DIRECTORY"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> <intent-filter> <action android:name="android.intent.action.CREATE_SHORTCUT"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> <activity android:theme="@16973839" android:label="@2131427483" android:name="com.estrongs.android.pop.app.ESContentChooserActivity" android:configChanges="keyboardHidden|orientation|screenSize"> <intent-filter> <action android:name="android.intent.action.GET_CONTENT"/> <category android:name="android.intent.category.OPENABLE"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="*/*"/> </intent-filter> </activity> <activity android:theme="@16973839" android:label="@2131427483" android:name="com.estrongs.android.pop.app.ESRingtoneChooserActivity" android:configChanges="keyboardHidden|orientation|screenSize"> <intent-filter> <action android:name="android.intent.action.RINGTONE_PICKER"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> <activity android:theme="@16973839" android:label="@2131427483" android:name="com.estrongs.android.pop.app.ESWallPaperChooserActivity" android:configChanges="keyboardHidden|orientation|screenSize"> <intent-filter> <action android:name="android.intent.action.SET_WALLPAPER"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> <activity android:name="com.estrongs.android.pop.app.imageviewer.CropImage" android:configChanges="keyboard|keyboardHidden|orientation|screenSize" android:hardwareAccelerated="false"/> <activity android:label="@2131427487" android:icon="@2130837710" android:name="com.estrongs.android.pop.app.imageviewer.ViewImage21" android:configChanges="keyboard|keyboardHidden|orientation|screenSize"/> <activity android:label="@2131427487" android:icon="@2130837710" android:name="com.estrongs.android.pop.app.imageviewer.ViewImage" android:configChanges="keyboard|keyboardHidden|orientation|screenSize"/> <activity android:label="@2131427487" android:icon="@2130837710" android:name="com.estrongs.android.pop.app.ImageCommentActivity" android:configChanges="keyboardHidden|orientation|screenSize" android:windowSoftInputMode="stateAlwaysHidden|adjustUnspecified"/> <activity android:name="com.estrongs.android.pop.app.ImageCommentPostActivity" android:configChanges="keyboardHidden|orientation|screenSize" android:windowSoftInputMode="stateUnspecified|adjustResize"/> <activity android:name="com.estrongs.android.pop.app.imageviewer.Wallpaper"/> <service android:name="com.estrongs.android.pop.bt.OBEXFtpServerService"> <intent-filter> <action android:name="android.intent.action.START_OBEX_FTP_SERVER"/> </intent-filter> </service> <provider android:name="com.estrongs.android.pop.app.FileContentProvider" android:exported="true" android:authorities="com.estrongs.files" android:grantUriPermissions="true"/> <activity android:theme="@16973839" android:label="@2131427489" android:icon="@2130837709" android:name="com.estrongs.android.pop.app.DownloaderActivity" android:configChanges="keyboardHidden|orientation|screenSize"> <intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.BROWSABLE"/> <category android:name="android.intent.category.DEFAULT"/> <data ... /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.BROWSABLE"/> <category android:name="android.intent.category.DEFAULT"/> <data ... /> </intent-filter> </activity> <activity android:theme="@16973839" android:label="@2131427489" android:icon="@2130837709" android:name="com.estrongs.android.pop.app.BrowserDownloaderActivity" android:configChanges="keyboardHidden|orientation|screenSize"> <intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.BROWSABLE"/> <category android:name="android.intent.category.DEFAULT"/> <data ... /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.BROWSABLE"/> <category android:name="android.intent.category.DEFAULT"/> <data ... /> </intent-filter> </activity> <activity android:label="@2131427487" android:icon="@2130837710" android:name="com.estrongs.android.pop.app.PopRemoteImageBrowser" android:configChanges="keyboardHidden|orientation|screenSize"> <intent-filter android:label="@2131427487"> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="image/*"/> </intent-filter> </activity> <activity android:theme="@16973830" android:name="com.estrongs.android.ui.theme.ThemeActivity" android:configChanges="keyboard|orientation|screenSize"/> <activity android:theme="@16973830" android:name="com.estrongs.android.ui.theme.ModifyThemeActivity" android:configChanges="keyboard|orientation|screenSize"/> <activity android:theme="@16973830" android:name="com.estrongs.android.ui.theme.ThemeColorActivity" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:theme="@16973830" android:name="com.estrongs.android.ui.theme.ThemeFolderActivity" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:theme="@16973830" android:name="com.estrongs.android.pop.app.network.EsNetworkActivity"/> <activity android:theme="@2131492874" android:label="@2131427483" android:name="com.estrongs.android.pop.ftp.ESFtpShortcut" android:launchMode="singleTop" android:configChanges="keyboardHidden|orientation|screenSize"> <intent-filter> <action android:name="android.intent.action.MAIN"/> </intent-filter> </activity> <service android:name="com.estrongs.android.ftp.ESFtpService" android:exported="false"/> <activity android:name="com.estrongs.android.ui.preference.FtpServerPreference" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:theme="@16973909" android:name="com.estrongs.android.pop.app.ShowDialogActivity" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:name="com.estrongs.android.pop.app.HelpActivity" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:name="com.estrongs.android.pop.app.PrivacyActivity" android:configChanges="keyboardHidden|orientation|screenSize"/> <service android:name="com.estrongs.android.ui.notification.ESTaskService" android:exported="false"/> <receiver android:name="com.baidu.share.message.ShareReceiver"> <intent-filter> <action android:name="baidu.intent.action.PCS_SHARE"/> </intent-filter> </receiver> <receiver android:name="com.estrongs.android.pop.EnableOEMConfig"> <intent-filter> <action android:name="android.intent.action.MEDIA_MOUNTED"/> <action android:name="android.intent.action.MEDIA_UNMOUNTED"/> <action android:name="android.intent.action.MEDIA_BAD_REMOVAL"/> <data android:scheme="file"/> </intent-filter> </receiver> <activity android:name="com.estrongs.android.ui.preference.TabletSettingsActivity" android:configChanges="keyboardHidden|orientation"/> <activity android:theme="@16973830" android:label="@2131427484" android:name=".app.PopAudioPlayer" android:launchMode="multiple" android:configChanges="keyboardHidden|orientation|screenSize" android:windowSoftInputMode="stateUnspecified|adjustPan"/> <activity android:theme="@16973830" android:name=".app.GestureManageActivity" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:theme="@16973830" android:name=".app.HideListActivity" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:theme="@16973830" android:name="com.baidu.sapi2.utils.LoginProtectAcitivity" android:configChanges="keyboardHidden|orientation|screenSize" android:windowSoftInputMode="stateUnspecified|adjustPan"/> <receiver android:name=".app.InstallMonitorReceiver"> <intent-filter> <action android:name="android.intent.action.PACKAGE_ADDED"/> <data android:scheme="package"/> </intent-filter> </receiver> <activity android:theme="@16973840" android:name=".app.InstallMonitorActivity" android:taskAffinity="com.estrongs.android.pop.app.InstallMonitorActivity" android:configChanges="keyboardHidden|orientation|screenSize"/> </application> </manifest> Looking at this Manifest, is there a way I can send to ES File Explorer an intent with a "file path" which will trigger the Send by LAN feature? Note: I want to create this app as the app's built in "Share by LAN" feature in the "Share via" dialogs is broken, see this link for the full description of this bug. (I've reported it to developer) UPDATE I got a response from the ES File Explorer developer team, they said that the "Share by LAN" feature in the "Share via" menu is not as we think it. This feature is only for sending files from Device to Device which both have ES File Explorer open and running on the same network, not for sending files to the PC (although I have requested this new feature as it would be most helpful). A: Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); shareIntent.setType("*/*"); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filePath))); shareIntent.setPackage("com.estrongs.android.pop"); startActivity(shareIntent);
{ "pile_set_name": "StackExchange" }
Q: Differences between FASA's 1993 hardcover and softcover Earthdawn (#6000 and #6001) Were there significant edits between the hardcover (#6000) and the (second printing of the) softcover (#6001) editions of FASA's original Earthdawn from 1993, or did they just fix typos? :) A: I'm not aware of any significant differences. My game group never encountered any situations where there was a difference between those two books in our many years of playing Eartdawn.
{ "pile_set_name": "StackExchange" }
Q: STM32 DMA: bytes remaining in buffer, encoded? For quite a while now I've been struggling with DMA communication with two STM32 boards in some form or another. My current issue is as follows. I have a host (a Raspberry Pi) running the following code, waiting for the board to initialise communication: #include <fcntl.h> #include <stdio.h> int main(int argc, char *argv[]) { unsigned int usbdev; unsigned char c; system("stty -F /dev/ttyUSB0 921600 icanon raw"); usbdev = open("/dev/ttyUSB0", O_RDWR); setbuf(stdout, NULL); fprintf(stderr, "Waiting for signal..\n"); while (!read(usbdev, &c, 1)); unsigned char buf[] = "Defend at noon\r\n"; write(usbdev, buf, 16); fprintf(stderr, "Written 16 bytes\r\n"); while (1) { while (!read(usbdev, &c, 1)); printf("%c", c); } return 0; } Basically it waits for a single byte of data before it'll send "Defend at noon" to the board, after which it prints everything that is sent back. The boards first send out a single byte, and then wait for all incoming data, replace a few bytes and send it back. See the code at the end of this post. The board can be either an STM32L100C or an STM32F407 (in practice, the discovery boards); I'm experiencing the same behaviour with both at this point. The output I'm seeing (on a good day - on a bad day it hangs on Written 16 bytes) is the following: Waiting for signal.. Written 16 bytes ^JDefend adawnon As you can see, the data is sent and four bytes are replaced as expected, but there's an extra two characters in front (^J, or 0x5E and 0x4A). These turn out to be a direct consequence of the signal_host function. When I replace the character with something arbitrary (e.g. x), that is what's being output at that position. It is interesting to note that \n actually gets converted to its caret notation ^J somewhere along the road. It appears that this occurs in the communication to the board, because when I simply hardcode a string in the buffer and use dma_transmit to send that to an non-interactive host program, it gets printed just fine. It looks like I've somehow miss-configured DMA in the sense that there's some buffer that is not being cleared properly. Additionally, I do not really trust the way the host-side program is using stty.. However, I've actually had communication working flawlessly in the past, using this exact code. I compared it to the code stored in my git history across several months, and I cannot find the difference/flaw. Note that the code below uses libopencm3 and is based on examples from libopencm3-examples. STM32L1 code: #include <libopencm3/stm32/rcc.h> #include <libopencm3/stm32/gpio.h> #include <libopencm3/stm32/usart.h> #include <libopencm3/cm3/nvic.h> #include <libopencm3/stm32/dma.h> void clock_setup(void) { rcc_clock_setup_pll(&clock_config[CLOCK_VRANGE1_HSI_PLL_32MHZ]); rcc_periph_clock_enable(RCC_GPIOA); rcc_periph_clock_enable(RCC_USART2); rcc_periph_clock_enable(RCC_DMA1); } void gpio_setup(void) { gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO2 | GPIO3); gpio_set_af(GPIOA, GPIO_AF7, GPIO2 | GPIO3); } void usart_setup(int baud) { usart_set_baudrate(USART2, baud); usart_set_databits(USART2, 8); usart_set_stopbits(USART2, USART_STOPBITS_1); usart_set_mode(USART2, USART_MODE_TX_RX); usart_set_parity(USART2, USART_PARITY_NONE); usart_set_flow_control(USART2, USART_FLOWCONTROL_NONE); usart_enable(USART2); } void dma_request_setup(void) { dma_channel_reset(DMA1, DMA_CHANNEL6); nvic_enable_irq(NVIC_DMA1_CHANNEL6_IRQ); dma_set_peripheral_address(DMA1, DMA_CHANNEL6, (uint32_t) &USART2_DR); dma_set_read_from_peripheral(DMA1, DMA_CHANNEL6); dma_set_peripheral_size(DMA1, DMA_CHANNEL6, DMA_CCR_PSIZE_8BIT); dma_set_memory_size(DMA1, DMA_CHANNEL6, DMA_CCR_MSIZE_8BIT); dma_set_priority(DMA1, DMA_CHANNEL6, DMA_CCR_PL_VERY_HIGH); dma_disable_peripheral_increment_mode(DMA1, DMA_CHANNEL6); dma_enable_memory_increment_mode(DMA1, DMA_CHANNEL6); dma_disable_transfer_error_interrupt(DMA1, DMA_CHANNEL6); dma_disable_half_transfer_interrupt(DMA1, DMA_CHANNEL6); dma_enable_transfer_complete_interrupt(DMA1, DMA_CHANNEL6); } void dma_transmit_setup(void) { dma_channel_reset(DMA1, DMA_CHANNEL7); nvic_enable_irq(NVIC_DMA1_CHANNEL7_IRQ); dma_set_peripheral_address(DMA1, DMA_CHANNEL7, (uint32_t) &USART2_DR); dma_set_read_from_memory(DMA1, DMA_CHANNEL7); dma_set_peripheral_size(DMA1, DMA_CHANNEL7, DMA_CCR_PSIZE_8BIT); dma_set_memory_size(DMA1, DMA_CHANNEL7, DMA_CCR_MSIZE_8BIT); dma_set_priority(DMA1, DMA_CHANNEL7, DMA_CCR_PL_VERY_HIGH); dma_disable_peripheral_increment_mode(DMA1, DMA_CHANNEL7); dma_enable_memory_increment_mode(DMA1, DMA_CHANNEL7); dma_disable_transfer_error_interrupt(DMA1, DMA_CHANNEL7); dma_disable_half_transfer_interrupt(DMA1, DMA_CHANNEL7); dma_enable_transfer_complete_interrupt(DMA1, DMA_CHANNEL7); } void dma_request(void* buffer, const int datasize) { dma_set_memory_address(DMA1, DMA_CHANNEL6, (uint32_t) buffer); dma_set_number_of_data(DMA1, DMA_CHANNEL6, datasize); dma_enable_channel(DMA1, DMA_CHANNEL6); signal_host(); usart_enable_rx_dma(USART2); } void dma_transmit(const void* buffer, const int datasize) { dma_set_memory_address(DMA1, DMA_CHANNEL7, (uint32_t) buffer); dma_set_number_of_data(DMA1, DMA_CHANNEL7, datasize); dma_enable_channel(DMA1, DMA_CHANNEL7); usart_enable_tx_dma(USART2); } int dma_done(void) { return !((DMA1_CCR6 | DMA1_CCR7) & 1); } void dma1_channel6_isr(void) { usart_disable_rx_dma(USART2); dma_clear_interrupt_flags(DMA1, DMA_CHANNEL6, DMA_TCIF); dma_disable_channel(DMA1, DMA_CHANNEL6); } void dma1_channel7_isr(void) { usart_disable_tx_dma(USART2); dma_clear_interrupt_flags(DMA1, DMA_CHANNEL7, DMA_TCIF); dma_disable_channel(DMA1, DMA_CHANNEL7); } void signal_host(void) { usart_send_blocking(USART2, '\n'); } int main(void) { clock_setup(); gpio_setup(); usart_setup(921600); dma_transmit_setup(); dma_request_setup(); unsigned char buf[16]; dma_request(buf, 16); while (!dma_done()); buf[10] = 'd'; buf[11] = 'a'; buf[12] = 'w'; buf[13] = 'n'; dma_transmit(buf, 16); while (!dma_done()); while(1); return 0; } STM32F4 code: #include <libopencm3/stm32/rcc.h> #include <libopencm3/stm32/gpio.h> #include <libopencm3/stm32/usart.h> #include <libopencm3/cm3/nvic.h> #include <libopencm3/stm32/dma.h> void clock_setup(void) { rcc_clock_setup_hse_3v3(&hse_8mhz_3v3[CLOCK_3V3_168MHZ]); rcc_periph_clock_enable(RCC_GPIOA); rcc_periph_clock_enable(RCC_USART2); rcc_periph_clock_enable(RCC_DMA1); } void gpio_setup(void) { gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO2 | GPIO3); gpio_set_af(GPIOA, GPIO_AF7, GPIO2 | GPIO3); } void usart_setup(int baud) { usart_set_baudrate(USART2, baud); usart_set_databits(USART2, 8); usart_set_stopbits(USART2, USART_STOPBITS_1); usart_set_mode(USART2, USART_MODE_TX_RX); usart_set_parity(USART2, USART_PARITY_NONE); usart_set_flow_control(USART2, USART_FLOWCONTROL_NONE); usart_enable(USART2); } void dma_request_setup(void) { dma_stream_reset(DMA1, DMA_STREAM5); nvic_enable_irq(NVIC_DMA1_STREAM5_IRQ); dma_set_peripheral_address(DMA1, DMA_STREAM5, (uint32_t) &USART2_DR); dma_set_transfer_mode(DMA1, DMA_STREAM5, DMA_SxCR_DIR_PERIPHERAL_TO_MEM); dma_set_peripheral_size(DMA1, DMA_STREAM5, DMA_SxCR_PSIZE_8BIT); dma_set_memory_size(DMA1, DMA_STREAM5, DMA_SxCR_MSIZE_8BIT); dma_set_priority(DMA1, DMA_STREAM5, DMA_SxCR_PL_VERY_HIGH); dma_disable_peripheral_increment_mode(DMA1, DMA_SxCR_CHSEL_4); dma_enable_memory_increment_mode(DMA1, DMA_STREAM5); dma_disable_transfer_error_interrupt(DMA1, DMA_STREAM5); dma_disable_half_transfer_interrupt(DMA1, DMA_STREAM5); dma_disable_direct_mode_error_interrupt(DMA1, DMA_STREAM5); dma_disable_fifo_error_interrupt(DMA1, DMA_STREAM5); dma_enable_transfer_complete_interrupt(DMA1, DMA_STREAM5); } void dma_transmit_setup(void) { dma_stream_reset(DMA1, DMA_STREAM6); nvic_enable_irq(NVIC_DMA1_STREAM6_IRQ); dma_set_peripheral_address(DMA1, DMA_STREAM6, (uint32_t) &USART2_DR); dma_set_transfer_mode(DMA1, DMA_STREAM6, DMA_SxCR_DIR_MEM_TO_PERIPHERAL); dma_set_peripheral_size(DMA1, DMA_STREAM6, DMA_SxCR_PSIZE_8BIT); dma_set_memory_size(DMA1, DMA_STREAM6, DMA_SxCR_MSIZE_8BIT); dma_set_priority(DMA1, DMA_STREAM6, DMA_SxCR_PL_VERY_HIGH); dma_disable_peripheral_increment_mode(DMA1, DMA_SxCR_CHSEL_4); dma_enable_memory_increment_mode(DMA1, DMA_STREAM6); dma_disable_transfer_error_interrupt(DMA1, DMA_STREAM6); dma_disable_half_transfer_interrupt(DMA1, DMA_STREAM6); dma_disable_direct_mode_error_interrupt(DMA1, DMA_STREAM6); dma_disable_fifo_error_interrupt(DMA1, DMA_STREAM6); dma_enable_transfer_complete_interrupt(DMA1, DMA_STREAM6); } void dma_request(void* buffer, const int datasize) { dma_set_memory_address(DMA1, DMA_STREAM5, (uint32_t) buffer); dma_set_number_of_data(DMA1, DMA_STREAM5, datasize); dma_channel_select(DMA1, DMA_STREAM5, DMA_SxCR_CHSEL_4); dma_enable_stream(DMA1, DMA_STREAM5); signal_host(); usart_enable_rx_dma(USART2); } void dma_transmit(const void* buffer, const int datasize) { dma_set_memory_address(DMA1, DMA_STREAM6, (uint32_t) buffer); dma_set_number_of_data(DMA1, DMA_STREAM6, datasize); dma_channel_select(DMA1, DMA_STREAM6, DMA_SxCR_CHSEL_4); dma_enable_stream(DMA1, DMA_STREAM6); usart_enable_tx_dma(USART2); } int dma_done(void) { return !((DMA1_S5CR | DMA1_S6CR) & 1); } void dma1_stream5_isr(void) { usart_disable_rx_dma(USART2); dma_clear_interrupt_flags(DMA1, DMA_STREAM5, DMA_TCIF); dma_disable_stream(DMA1, DMA_STREAM5); } void dma1_stream6_isr(void) { usart_disable_tx_dma(USART2); dma_clear_interrupt_flags(DMA1, DMA_STREAM6, DMA_TCIF); dma_disable_stream(DMA1, DMA_STREAM6); } void signal_host(void) { usart_send_blocking(USART2, '\n'); } int main(void) { clock_setup(); gpio_setup(); usart_setup(921600); dma_transmit_setup(); dma_request_setup(); unsigned char buf[16]; dma_request(buf, 16); while (!dma_done()); buf[10] = 'd'; buf[11] = 'a'; buf[12] = 'w'; buf[13] = 'n'; dma_transmit(buf, 16); while (!dma_done()); while(1); return 0; } A: Well, I can be brief about this one. I recommend against using stty for this sort of thing. I realise I have probably not configured stty properly, and with some option-tweaking it is probably possible to get it right, but it's completely unclear. I ended up throwing it out the window and using pyserial instead. I should've done that weeks ago. The above STM32 code works fine and the required Python code is completely trivial. #!/usr/bin/env python3 import serial dev = serial.Serial("/dev/ttyUSB0", 921600) dev.read(1) # wait for the signal dev.write("Defend at noon\r\n".encode('utf-8')) while True: x = dev.read() print(x.decode('utf-8'), end='', flush=True)
{ "pile_set_name": "StackExchange" }
Q: Is there any way to iterate all fields of a data class without using reflection? I know an alternative of reflection which is using javassist, but using javassist is a little bit complex. And because of lambda or some other features in koltin, the javassist doesn't work well sometimes. So is there any other way to iterate all fields of a data class without using reflection. A: There are two ways. The first is relatively easy, and is essentially what's mentioned in the comments: assuming you know how many fields there are, you can unpack it and throw that into a list, and iterate over those. Or alternatively use them directly: data class Test(val x: String, val y: String) { fun getData() : List<Any> = listOf(x, y) } data class Test(val x: String, val y: String) ... val (x, y) = Test("x", "y") // And optionally throw those in a list Although iterating like this is a slight extra step, this is at least one way you can relatively easy unpack a data class. If you don't know how many fields there are (or you don't want to refactor), you have two options: The first is using reflection. But as you mentioned, you don't want this. That leaves a second, somewhat more complicated preprocessing option: annotations. Note that this only works with data classes you control - beyond that, you're stuck with reflection or implementations from the library/framework coder. Annotations can be used for several things. One of which is metadata, but also code generation. This is a somewhat complicated alternative, and requires an additional module in order to get compile order right. If it isn't compiled in the right order, you'll end up with unprocessed annotations, which kinda defeats the purpose. I've also created a version you can use with Gradle, but that's at the end of the post and it's a shortcut to implementing it yourself. Note that I have only tested this with a pure Kotlin project - I've personally had problems with annotations between Java and Kotlin (although that was with Lombok), so I do not guarantee this will work at compile time if called from Java. Also note that this is complex, but avoids runtime reflection. Explanation The main issue here is a certain memory concern. This will create a new list every time you call the method, which makes it very similar to the method used by enums. Local testing over 10000 iterations also show a general consistency of ~200 milliseconds to execute my approach, versus roughly 600 for reflection. However, for one iteration, mine uses ~20 milliseconds, where as reflection uses between 400 and 500 milliseconds. On one run, reflection took 1500 (!) milliseconds, while my approach took 18 milliseconds. See also Java Reflection: Why is it so slow?. This appears to affect Kotlin as well. The memory impact of creating a new list every time it's called can be noticeable though, but it'll also be collected so it shouldn't be that big a problem. For reference, the code used for benchmarking (this will make sense after the rest of the post): @AutoUnpack data class ExampleDataClass(val x: String, val y: Int, var m: Boolean) fun main(a: Array<String>) { var mine = 0L var reflect = 0L // for(i in 0 until 10000) { var start = System.currentTimeMillis() val cls = ExampleDataClass("example", 42, false) for (field in cls) { println(field) } mine += System.currentTimeMillis() - start start = System.currentTimeMillis() for (prop in ExampleDataClass::class.memberProperties) { println("${prop.name} = ${prop.get(cls)}") } reflect += System.currentTimeMillis() - start // } println(mine) println(reflect) } Setting up from scratch This bases itself around two modules: a consumer module, and a processor module. The processor HAS to be in a separate module. It needs to be compiled separately from the consumer for the annotations to work properly. First of all, your consumer project needs the annotation processor: apply plugin: 'kotlin-kapt' Additionally, you need to add stub generation. It complains it's unused while compiling, but without it, the generator seems to break for me: kapt { generateStubs = true } Now that that's in order, create a new module for the unpacker. Add the Kotlin plugin if you didn't already. You do not need the annotation processor Gradle plugin in this project. That's only needed by the consumer. You do, however, need kotlinpoet: implementation "com.squareup:kotlinpoet:1.2.0" This is to simplify aspects of the code generation itself, which is the important part here. Now, create the annotation: @Retention(AnnotationRetention.SOURCE) @Target(AnnotationTarget.CLASS) annotation class AutoUnpack This is pretty much all you need. The retention is set to source because it has no value at runtime, and it only targets compile time. Next, there's the processor itself. This is somewhat complicated, so bear with me. For reference, this uses the javax.* packages for annotation processing. Android note: this might work assuming you can plug in a Java module on a compileOnly scope without getting the Android SDK restrictions. As I mentioned earlier, this is mainly for pure Kotlin; Android might work, but I haven't tested that. Anyways, the generator: Because I couldn't find a way to generate the method into the class without touching the rest (and because according to this, that isn't possible), I'm going with an extension function generation approach. You'll need a class UnpackCodeGenerator : AbstractProcessor(). In there, you'll first need two lines of boilerplate: override fun getSupportedAnnotationTypes(): MutableSet<String> = mutableSetOf(AutoUnpack::class.java.name) override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latest() Moving on, there's the processing. Override the process function: override fun process(annotations: MutableSet<out TypeElement>, roundEnv: RoundEnvironment): Boolean { // Find elements with the annotation val annotatedElements = roundEnv.getElementsAnnotatedWith(AutoUnpack::class.java) if(annotatedElements.isEmpty()) { // Self-explanatory return false; } // Iterate the elements annotatedElements.forEach { element -> // Grab the name and package val name = element.simpleName.toString() val pkg = processingEnv.elementUtils.getPackageOf(element).toString() // Then generate the class generateClass(name, if (pkg == "unnamed package") "" else pkg, // This is a patch for an issue where classes in the root // package return package as "unnamed package" rather than empty, // which breaks syntax because "package unnamed package" isn't legal. element) } // Return true for success return true; } This just sets up some of the later framework. The real magic happens in the generateClass function: private fun generateClass(className: String, pkg: String, element: Element){ val elements = element.enclosedElements val classVariables = elements .filter { val name = if (it.simpleName.contains("\$delegate")) it.simpleName.toString().substring(0, it.simpleName.indexOf("$")) else it.simpleName.toString() it.kind == ElementKind.FIELD // Find fields && Modifier.STATIC !in it.modifiers // that aren't static (thanks to sebaslogen for issue #1: https://github.com/LunarWatcher/KClassUnpacker/issues/1) // Additionally, we have to ignore private fields. Extension functions can't access these, and accessing // them is a bad idea anyway. Kotlin lets you expose get without exposing set. If you, by default, don't // allow access to the getter, there's a high chance exposing it is a bad idea. && elements.any { getter -> getter.kind == ElementKind.METHOD // find methods && getter.simpleName.toString() == "get${name[0].toUpperCase().toString() + (if (name.length > 1) name.substring(1) else "")}" // that matches the getter name (by the standard convention) && Modifier.PUBLIC in getter.modifiers // that are marked public } } // Grab the variables .map { // Map the name now. Also supports later filtering if (it.simpleName.endsWith("\$delegate")) { // Support by lazy it.simpleName.subSequence(0, it.simpleName.indexOf("$")) } else it.simpleName } if (classVariables.isEmpty()) return; // Self-explanatory val file = FileSpec.builder(pkg, className) .addFunction(FunSpec.builder("iterator") // For automatic unpacking in a for loop .receiver(element.asType().asTypeName().copy()) // Add it as an extension function of the class .addStatement("return listOf(${classVariables.joinToString(", ")}).iterator()") // add the return statement. Create a list, push an iterator. .addModifiers(KModifier.PUBLIC, KModifier.OPERATOR) // This needs to be public. Because it's an iterator, the function also needs the `operator` keyword .build() ).build() // Grab the generate directory. val genDir = processingEnv.options["kapt.kotlin.generated"]!! // Then write the file. file.writeTo(File(genDir, "$pkg/${element.simpleName.replace("\\.kt".toRegex(), "")}Generated.kt")) } All of the relevant lines have comments explaining use, in case you're not familiar with what this does. Finally, in order to get the processor to process, you need to register it. In the module for the generator, add a file called javax.annotation.processing.Processor under main/resources/META-INF/services. In there you write: com.package.of.UnpackCodeGenerator From here, you need to link it using compileOnly and kapt. If you added it as a module to your project, you can do: kapt project(":ClassUnpacker") compileOnly project(":ClassUnpacker") Alternative source setup: Like I mentioned earlier, I bundled this into a jar for convenience. It's under the same license as SO uses (CC-BY-SA 3.0), and it contains the exact same code as in the answer (although compiled into a single project). If you want to use this one, just add the Jitpack repo: repositories { // Other repos here maven { url 'https://jitpack.io' } } And hook it up with: kapt 'com.github.LunarWatcher:KClassUnpacker:v1.0.1' compileOnly "com.github.LunarWatcher:KClassUnpacker:v1.0.1" Note that the version here may not be up to date: the up to date list of versions is available here. The code in the post still aims to reflect the repo, but versions aren't really important enough to edit every time. Usage Regardless of which way you ended up using to get the annotations, the usage is relatively easy: @AutoUnpack data class ExampleDataClass(val x: String, val y: Int, var m: Boolean) fun main(a: Array<String>) { val cls = ExampleDataClass("example", 42, false) for(field in cls) { println(field) } } This prints: example 42 false Now you have a reflection-less way of iterating fields. Note that local testing has been done partially with IntelliJ, but IntelliJ doesn't seem to like me - I've had various failed builds where gradlew clean && gradlew build from a command line oddly works fine. I'm not sure whether this is a local problem, or if this is a general problem, but you might have some issues like this if you build from IntelliJ. Also, you might get errors if the build fails. The IntelliJ linter builds on top of the build directory for some sources, so if the build fails and the file with the extension function isn't generated, that'll cause it to appear as an error. Building usually fixes this when I tested (with both modules and from Jitpack). You'll also likely have to enable the annotation processor setting if you use Android Studio or IntelliJ.
{ "pile_set_name": "StackExchange" }
Q: SendGrid not sending emails on Heroku from default inqury/contact form This is my first app using RefineryCMS. The way I have sent mail from applications in the past is not currently work with my refinery app. I have tried numerous ways of doing this by way of numerous searches on the internet and I cannot make this work. Currently, here is what I have: In the environment.rb file I have this: config.action_mailer.smtp_settings = { :enable_starttls_auto => true, :address => 'smtp.sendgrid.net', :port => '25', :authentication => :plain, :user_name => '[email protected]', :password => 'mypassword', :domain => 'mydomain' } I have also tried: ActionMailer::Base.smtp_settings = { :enable_starttls_auto => true, :address => 'smtp.sendgrid.net', :port => '25', :authentication => :plain, :user_name => '[email protected]', :password => 'mypassword', :domain => 'mydomain' } I have tried putting these settings in the production and development classes. Tried locally and on heroku but I just can't get the built in inquiry/contact form to send out the notifications emails and I have no idea why it won't work. Like I said earlier, I have tried every solution (they are all very similar) I can find for this but can't make it work. If somebody could please tell what I am doing wrong and what, exactly, it is I need to do, that would be awesome. Thanks in advance, ~Mike A: Actually, it was a bug in the existing version of refinerycms-inquiries that was causing the mail not to send. once I updated to 0.9.9.9, it worked as expected. In case anyone needs to know how to perform this update: First, add this line to your Gem file: gem 'refinerycms-inquiries', '~> 0.9' Then run this command: bundle update refinerycms-inquiries and this is all I added to the environment.rb file: ActionMailer::Base.smtp_settings = { :enable_starttls_auto => true, :address => 'smtp.sendgrid.net', :port => '25', :authentication => :plain, :user_name => '[email protected]', :password => 'mypassword', :domain => 'mydomain.com' } That's it.
{ "pile_set_name": "StackExchange" }
Q: C code changes terminal text color; how to restore defaults? Linux I have a C file running on Linux. It prints some lines in red (failures) and some in green (passes). As you might expect, it uses escape codes in the printf statements as follows: #define BLACK "\033[22;30m" #define GREEN "\033[22;31m" printf(GREEN "this will show up green" BLACK "\n"); If the BLACK at the end wasn't there, the terminal text will continue to be green for everything. In case you didn't catch it, that's fine for a terminal window with a non-black background, but otherwise you'll end up with black-on-black. Not good! Running the program has this problem, as does capturing the output in a text file and then viewing the file with "more" or "less". Is there a code to restore defaults instead of specifying a color at the end of the printf statement? This needs to be in C, but I would be interested in reading about other approaches. Update: Thank you all. Your responses helped me find even more useful info elsewhere. I updated my macros as follows (note 31 is for red and I fixed that typo below): #define RESET_COLOR "\e[m" #define MAKE_GREEN "\e[32m" printf(MAKE_GREEN "this will show up green" RESET_COLOR "\n"); I found the following links helpful in understanding how these codes work: http://www.phwinfo.com/forum/comp-unix-shell/450861-bash-shell-escapes-not-working-via-putty-ssh.html explains what these escape sequences do, and to use ncurses if portability is needed. http://www.linuxselfhelp.com/howtos/Bash-Prompt/Bash-Prompt-HOWTO-6.html http://bluesock.org/~willg/dev/ansi.html shows even more escape sequences; useful to get the big picture A: Try using: #define RESETCOLOR "\033[0m" That should reset it to the defaults. More about these terminal codes can be found here: http://en.wikipedia.org/wiki/ANSI_escape_code A: "\033[0m" See here: http://en.wikipedia.org/wiki/ANSI_color
{ "pile_set_name": "StackExchange" }
Q: jquery delay function My delay function is not working in my jquery rotate function. I am not sure why. Basically, my code will make my div turn an angle and it will stop at a certain angle. This works at the moment. However i added a delay so it it will work after 3 or 4 seconds. However its not doing it. $(window).load(function() { var $elie = $("#super"); rotate(1); function rotate(degree) { $elie.css({ '-webkit-transform': 'rotate(' + degree + 'deg)', '-moz-transform': 'rotate(' + degree + 'deg)', '-o-transform': 'rotate(' + degree + 'deg)', '-ms-transform': 'rotate(' + degree + 'deg)', 'transform': 'rotate(' + degree + 'deg)' }); console.log(degree); if (degree < 55) { timer = setTimeout(function() { rotate(++degree) }, 10) delay: 4000; } } });​ A: If you want to delay the rotation just make a 'setTimeout' around the delay function: $(window).load(function() { var $elie = $("#super"); setTimeout(function() { rotate(1); }, 4000) function rotate(degree) { $elie.css({ '-webkit-transform': 'rotate(' + degree + 'deg)', '-moz-transform': 'rotate(' + degree + 'deg)', '-o-transform': 'rotate(' + degree + 'deg)', '-ms-transform': 'rotate(' + degree + 'deg)', 'transform': 'rotate(' + degree + 'deg)' }); console.log(degree); if (degree < 55) { timer = setTimeout(function() { rotate(++degree) }, 10) } }; });​ (also as mentioned removed the dalay: 4000, which don't has the effect you want!) Fiddler example: http://jsfiddle.net/49VEe/ edit2: You can use HTML5 transition to get the rotation effect instead of your recursive function (sample without delay: $(window).load(function() { var $elie = $("#super"); rotate(55); function rotate(degree) { $elie.css({ '-webkit-transform': 'rotate(' + degree + 'deg)', '-moz-transform': 'rotate(' + degree + 'deg)', '-o-transform': 'rotate(' + degree + 'deg)', '-ms-transform': 'rotate(' + degree + 'deg)', 'transform': 'rotate(' + degree + 'deg)', '-webkit-transition': 'all 1s ease-in-out', '-moz-transition': 'all 1s ease-in-out', '-o-transition': 'all 1s ease-in-out', transition: 'all 1s ease-in-out' }); }; });​ Fiddler: http://jsfiddle.net/mZzjP/
{ "pile_set_name": "StackExchange" }
Q: How to pass yamel file content to cloud formation nested stack? I tried this in many ways: aws cloudformation deploy --stack-name agent-prod --template-file prod-agent.yaml --region eu-central-1 --parameter-overrides ConfigFile="$(cat config.yaml)" and aws cloudformation deploy --stack-name agent-prod --template-file prod-agent.yaml --region eu-central-1 --parameter-overrides ConfigFile=fileb://config.yaml but it didn't work. is there a good way and known to do that? A: You can't currently pass your parameters in YAML format. It's a commonly requested feature. One alternative is to pass your parameters in JSON format using the parameters argument: --parameters params.json params.json: [ { "ParameterKey": "Foo", "ParameterValue": "Bar" } ]
{ "pile_set_name": "StackExchange" }
Q: telnet port 23 connection failed window 7 I'm using windows 7 and I'm trying to connect to my router with telnet: open cmd type telnet xxx.xxx.xxx.xxx. Result is could not open connection to the host, on port 23:connection failed. What I have already tried: Control panel -> Program and Features -> Turn windows features on or off - Check telnet client box (I also checked Telnet server but it gives an error) Control panel -> Windows Firewall -> Advanced setting -> Inbound rules -> New rules -> Port 23, TCP - Allow the connection, domain/private/public I can't find Telnet as a service. I don't know how to uninstall, reinstall. I tried cmd net start telnet - then I get: service name invalid A: You don't need to do anything else to windows to get the telnet client working. You already get an error message from it saying could not open connection to host on port 23: connection failed - telnet client is operating, just not how you'd like. Either: The IP address is wrong (can you ping the device?) The device is not available at that IP (again can you ping the IP?) Outbound connections on your Windows Firewall are blocked (outbound to connect to a device) Or most likely telnet is not supported or turned on in your router (Which router do you have?) If your router supports remote command line access (not all of them do) then it may be SSH (Secure Shell) on Port 22. If you are using Windows then a popular package is Putty - but there are other clients available.
{ "pile_set_name": "StackExchange" }
Q: mysql: encrypting and decrypting data Does mysql provide a mechanism for storing and retrieving encrypted data? I don't mean passwords, I mean real strings. I'd like to encrypt a string, store in mysql and then retrieve the decrypted string at a later date. So, I know there is the AES_Encrypt and decrypt functions. But they ask for a key. (which is fine) but I wondering if you call those functions and use your user password as the key. Or something else that is super-simple. Also, is there a simple wrapper for the AES_Encrypt & decrypt functions in Rails? Or do you need to build the query manually? A: You can just concat the encrypt functions: select aes_encrypt('MyData',Password('MyPassword')) and back again.. select Aes_decrypt( aes_encrypt('MyData',Password('MyPassword')) , Password('MyPassword')) A: If I understand you, then all you need is a method to generate an AES key from your (or other) user password? Shouldn't you be asking 'Is there an easy method to generate an AES-key from 5-20char string'? As you point out, the other tools are already in place in mysql: http://dev.mysql.com/doc/refman/5.0/en/encryption-functions.html Also you might find some ideas in this post here on SO.
{ "pile_set_name": "StackExchange" }
Q: inline-block appearing wider in Firefox/Safari than Chrome, spilling over line I made this site. On Chrome (v24.0), everything appears as intended. When I look at it in Safari or Firefox, the layout breaks: the links "view cart" and "checkout" in the top right spill over to an extra line. It's hard to describe, but compare how they look in Chrome (correct) vs Firefox and Safari (wrong) and it should be obvious what I mean. How can I fix this? Everything I've tried that successfully solves the problem in Firefox and Safari just breaks it in Chrome. My current CSS (Sass): .account-links { font-size: 0; } .account-links a { box-sizing: border-box; width: 90px; margin: 0px; font-size:9pt; -moz-box-shadow:inset 0px 0px 0px 0px #ffffff; -webkit-box-shadow:inset 0px 0px 0px 0px #ffffff; box-shadow:inset 0px 0px 0px 0px #ffffff; background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #f9f9f9), color-stop(1, #e9e9e9) ); background:-moz-linear-gradient( center top, #f9f9f9 5%, #e9e9e9 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9', endColorstr='#e9e9e9'); background-color:#f9f9f9; border-top:1px solid #dcdcdc; border-bottom:1px solid #dcdcdc; &:first-child { border-right:1px solid #dcdcdc; } display:inline-block; color:#666666; font-family:arial; font-weight:bold; padding: 5px 0px; text-decoration:none; text-shadow:0px 1px 0px #ffffff; &:hover { background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #e9e9e9), color-stop(1, #f9f9f9) ); background:-moz-linear-gradient( center top, #e9e9e9 5%, #f9f9f9 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#e9e9e9', endColorstr='#f9f9f9'); background-color:#e9e9e9; } &:active { position:relative; top:1px; } } A: That's because you're using unprefixed box-sizing for #shop-meta .account-links a. Add -moz-box-sizing: border-box and -webkit-box-sizing: border-box and it should work as intended. Edit: Actually I've found that there's some bug in Safari (using v5.1.7 for Windows) that prevents box-sizing from working properly. The solution for that browser is to set float: left on .account-links a. You don't need -webkit-box-sizing.
{ "pile_set_name": "StackExchange" }
Q: What is the right way to combine frontend and backend (Angular6/PHP) Informations: Using - Angular6 (frontend), plain PHP (backend), MySQL (db), Postman (testing) Domains: http://frontend-domain.com; http://backend-domain.com http://frontend-domain.com directory structure: app (default angular app) |_node_modules |_src |_... http://backend-domain.com directoy structure: app |_api | |_contract | |-contract.php (waits for incoming POST requests) |_config | |-Database.php (database class with db connection data and function connect()) |_models |-Contract.php (contract class with sql querys) Situation: I do not have any connection problems or any query problems. I am able to request the backend (api) successfully. I am working on a login authentification and I used localstorage to save an auth_token . I need it to verify that the user is logged in and allowed to see the dashboard. Now I have read that using localstorage is bad. Question(s): If I am not allowed to save data in localstorage how else shall I identify the current user on a specific client? -> Someone said to use the session on server side: I was thinking about "how will this work?" => It didn't work. Even the php $_COOKIE did not work. I also tried to implement the the whole backend folder in the angular app (app/src/backend). The requests were still successfull but the sessions and cookies still did not work. What else shall I do? How is the combination of frontend and backend in my example? Should I use an internal backend on the same domain where the frontend sits or should I keep it? Is it recommended to split it like I did? Did I even get it? Is this how a backend is build? Or is this just a simple (public) api? A: Its not a good practice to keep your backend in your angular app. The approach you did before is good, Keeping your backend and frontend separately. In that case you can use multiple languages and connect it with your angular app through REST APIs Regarding saving token in localStorage. I think its not bad. But if you are still uncomfortable with that. Try to save your token in browser cookies. Have a look at this answer it might help. Is it safe to store a jwt in localStorage with reactjs?
{ "pile_set_name": "StackExchange" }
Q: Extending existing Swing look and feels with custom JComponents I'm writing a custom JComponent, that should look differently for different look and feels. I intend to have different ComponentUi classes at least for the WindowsLookAndFeel, the MetalLookAndFeel and for the MotifLookAndFeel. Now, while this task seems easy enough, I couldn't find out how to easily extend an existing look and feel with my custom ComponentUi classes. How would I go about registering the correct ComponentUi for the different look and feels? Is this possible at all? If not, what is the preferred way to write a custom component for different look and feels? To be a bit more specific, at the moment I'm overriding JComponent#updateUI in my custom component to set the different ComponentUi instances: @Override public void updateUI() { LookAndFeel feel = UIManager.getLookAndFeel(); if (feel instanceof WindowsLookAndFeel) { setUI(MyWindowsCustomUi.createUI(this)); } else if (feel instanceof MotifLookAndFeel) { setUI(MyMotivCustomUi.createUI(this)); } else if (feel instanceof MetalLookAndFeel) { setUI(MyMetalCustomUi.createUI(this)); } else{ setUI(MyBasicCustomUi.createUI(this)); } } But this approach seems to entirely defeat the purpose and usefulness of look and feels. I'd like to be able to change this to the following: public void updateUI() { setUI((MyCustomUi)UIManager.getUI(this)); } And this should set the correct subclass of MyCustomUi for the current look and feel. I know, that I could easily achieve this by creating custom subclasses of each supported LookAndFeel, that register the corresponding ComponentUi during e.g. BasicLookAndFeel#initComponentDefaults(UIDefaults) - but this is not what I want to do. A: If you want it or not - you have to register your custom UIs somehow with the UIManager, how else could it know about them ;-) What you don't need, though, is a custom subclass of the supported LAFs: you can register them manually (and update the registration when the LAF is changed, that is you'll need a propertyChangeListener on the UIManager to be notified in such a case). Assuming a JCustom with a classID of "CustomUI" and ui implementations following the usual conventions (that is BasicCustomUI, WindowsCustomUI ... ) the registration would be something like: String prefix = UIManager.getLookAndFeel().getID(); UIManager.getLookAndFeelDefaults().put("CustomUI", myUIPackage + "." + prefix + CustomUI); Note that the custom ui needs a static createUI which returns an instance of the ui: public static ComponentUI createUI(JComponent comp) { return new BasicCustomUI(); } and the component needs to publish its uiClassID, lookup and set its ui: @Override public String getUIClassID() { return "CustomUI"; } @Override public void updateUI() { setUI(UIManager.getUI(this)); } The benefit of using SwingX is to provide the infrastructure to automagically register custom components. You'll need an additional class - CustomAddon - which provides the per-LAF configuration and the custom component has to contribute that addon: // in JCustom static { LookAndFeelAddons.contribute(new CustomAddon()); } // in CustomAddon @Override protected void addBasicDefaults(LookAndFeelAddons addon, DefaultsList defaults) { super.addBasicDefaults(addon, defaults); defaults.add("CustomUI", "mypackage.BasicCustomUI"); } @Override protected void addMacDefaults(LookAndFeelAddons addon, DefaultsList defaults) { super.addMacDefaults(addon, defaults); defaults.add("CustomUI", "mypackage.MacCustomUI"); } //... similar methods for all supported LAFs
{ "pile_set_name": "StackExchange" }
Q: How can I automatically timestamp rows in a Google Sheet? I am entering data into a Google Sheet. I would like to have a column where each row will be automatically timestamped with the DateTime in which I entered (or last updated) the contents of the row. I know that I can do this manually by adding =now() to a cell, which will record the timestamp. However, this will update on any change to the doc, so I then need to copy and ctrl-shift-v to paste back just the value. Would be more ideal if there was a formula that I could paste down the column which would only set now() as the value if there is a change in any of the selected columns in the given row. Thoughts on how to do this? A: The following onEdit trigger will add the date to the adjoining column: Code ES6/v8/arrow/shorthand if statement const onEdit = (e) => e.range.columnStart === 1 ? e.range.offset(0,1).setValue(new Date()) : null classic function onEdit(e) { if(e.range.columnStart === 1) { e.range.offset(0,1).setValue(new Date()) } } Explained It reads as follows: the script is only fired when an edit was made in column 1 (A) if in column A, then add the date into the adjoining cell else do nothing You could use the Utilities class to format the date to the date/time notation const onEdit = (e) => e.range.columnStart === 1 ? e.range.offset(0,1).setValue(Utilities.formatDate(new Date(), SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "dd-MM-yyyy HH:mm")) : null but you can format the column from within the Google Sheet as well (Format > Number > Date time). Paste this script into the script editor (Tools > Script editor) and save. Now it should work.
{ "pile_set_name": "StackExchange" }
Q: SQL Server 2008 Merge Statement to check and insert if a record doesnt exist I am trying to add a record into a table by checking against certain conditions for the existance of record through sql script. I am trying it using Merge Statement. Its not working couldnt tract out where i am going wrong. Can some one help me with this?. Thanks MERGE Categories As target USING ( SELECT CategoryKey From Categories where CategoryName = 'TestName' ) AS source on (source.CategoryKey = target.CategoryKey) WHEN Not Matched THEN INSERT VALUES ('TestName'); A: This'll do the job: MERGE Categories As target USING (SELECT 'TestName' AS CategoryName) AS source ON (source.CategoryName = target.CategoryName) WHEN NOT MATCHED THEN INSERT (CategoryName) VALUES ('TestName');
{ "pile_set_name": "StackExchange" }
Q: Why does my text has the justify effect when I didnt made it to have this effect (css/php) Why my text has the justify effect? In my whole site, I make echos and i dont specify a "text-align:justify;" but my text is still justifying. Justify is when you make the browser window smaller, the text moves so it fits in the window. I tryed making something like this: <?php echo "<h1>some stuff.</h1>"; ?> <html> <head> <style> h1 { text-align:center; } etc.... but it just makes the text go in the center and it keeps the justify effect. please help me =[ thanks A: Justify is when you make the browser window smaller, the text moves so it fits in the window. That's not what justify is. Justify makes it so all lines of text are the same width, like this: (source: pws-ltd.com) If you don't want the text to stay inside the window when you shrink it (so if you want a horizontal scrollbar), you have to set a min-width on a <div> containing the text. Edit: though maybe I misunderstood what you were actually trying to do, and you just want it centered. If so, use margin: 0 auto; not text-align: center;
{ "pile_set_name": "StackExchange" }
Q: $ is not a function in wordpress I am trying to make a site responsive but I need to reorder the sidebars to make them appear below the content. I found this script in another answer but it tells me $ is not a function in the console. I guess this is something about jquery and how wordpress handles it with document ready and that kind of thing, but I don't know how the syntax is and stuff.. <script type="text/javascript"> $(window).resize(function() { if ( $(window).width() < 768 ) { $("#firstsidebar").insertAfter("#maincontent"); } else{ $("#maincontent").insertAfter("#firstsidebar"); } }); $(document).ready(function(){ if ( $(window).width() < 768 ) { $("#firstsidebar").insertAfter("#maincontent"); } }); </script> EDIT. ok. I am getting a lot of negative ratings because of this question. Maybe it is super simple and stupid, but I don't know javascript and jquery, I just "kind of" understand it a little. A: When jQuery doesn't respond to $, it's usually either because there's a conflict with another library trying to use the same sigil, or the CMS / Web server / environment is set up to explicitly avoid such conflicts. You can use jQuery every place you would normally use $. That almost invariably works. Or you can wrap the invocation in a function that establishes a local argument: jQuery( document ).ready(function( $ ) { // You can use the locally-scoped $ in here as an alias to jQuery. $( "div" ).hide(); }); Other options are available, including defining your own custom access point (like jq or J$), or even defining the $ to explicitly point to jQuery (or the jQuery.noConflict() proxy). Many of these are discussed in the jQuery documentation. You can also brute-force it, by defining $ early on in your code: $ = jQuery; Now $ will work exactly as you expected. Probably. (Unless or until it doesn't, because one of the aforementioned JS library compatibility issues has bitten you. At which point you might decide to fall back to one of the more structured, planned ways of achieving compatibility.)
{ "pile_set_name": "StackExchange" }
Q: codingbat-like site for C++ Guys, I need to find a good site like codingbat to "learn again" C++. I learned it at school but then I've never used it seriously. I'm not looking for something like Project Euler because it focuses on math problems. I need something really focused on C++ principles, chacteristics and tools. A: I don't think such a site exists and I doubt it ever will. The reason is that C++ is huge - and I mean reeaallllyyy huge. When you start to write C++ code professionally (that is, 40hrs per week) and take 1 or 2 hrs for learning new stuff about C++ every day (that is, 5-10hrs per week), reading books and articles, you will need months, if not years, to become a real professional C++ programmer - unworldly presuming your job doesn't require you to learn any 3rd-party APIs, new tools, technologies, and whatnot, which will distract you from learning C++. For several years, I have taught C++ to students who already had one year exposure to Java. In 4-5 months, 12-15 lectures, and at the very least twice that time in the lab, I've managed to drag them from "Hello, world!" all the way to a short introduction to template meta programming. Everyone who know all of the area covered by that span will tell you that, after this, they'd still be bloody novices. (Heck, I'm using C++ for >15 years, earn my money writing C++ code >10 years, and still learn new stuff about it almost weekly. And that's not even considering the huge amount of stuff dumped over us by the new standard, which has been "just around the corner" for several years). Due to the sheer size of the territory to cover in order to learn C++, and also due to the fact that C++ is old enough that its programmers can be categorized into several generations when it comes to which standard idioms and "best" practices they learned, and finally because (again due to its incredible hugeness) new techniques are constantly discovered and evolving (template meta programming, now a very important feature of C++, was an accident nobody had planned for), the C++ community's opinions on idioms and practices isn't as compact as, say, the Java community's, and can hardly be communicated as a set of a few dozen rules without arousing heated discussions. (I think the fact that there are several different very good and recommended Best Practices books listing several dozen rules of thumb each, and the fact that some of them managed to later acquire a supplementing More Best Practices book, literally speaks volumes about this.) You will find many professional C++ programmers who happily use only 30% of what C++ offers. For example, many use it just as an OO language, missing out templates (maybe except for the STL), exceptions, and other very useful stuff. But C++ is a multi-paradigm language. It supports object-oriented programming as well as generic programming, generative programming, a lot of functional programming stuff, and quite a few other paradigms. And it becomes most powerful where those paradigms are combined. So what's my advice? Have a look at The Definitive C++ Book Guide and List. First make your pick from the beginner's books. Since you say you already had exposure to C++, I'd recommend Accelerated C++ by Andrew Koenig and Barbara Moo. That's an excellent introduction which can't be praised enough for the way it changed teaching C++, but it comes with quite a steep learning curve. Also, with 250 pages, it's really just a short introduction. An alternative to that would probably be either Stanley Lippman's C++ Primer (which, at 1000 pages, covers the same ground in detail) or Bruce Eckel's Thinking in C++ (which I don't know) or Bjarne Stroustrup's classic The C++ Programming Language (also 1k pages) or his newest book, Programming - Principles and Practice Using C++ (which I haven't looked at yet). These books come with enough tasks to keep you busy for a while. Add a few of your own to that and you can be busy learning for months. Then slowly work your way down the list. The next C++ standard, now generally expected in 2011, will add a few challenging concepts to the language (like rvalue references) and a vastly expanded standard library. (The current draft has almost twice as many pages as the last one.) Unfortunately, since the standard isn't yet finished, there are no books available teaching it. It's all spread out in articles and in online discussions (although Wikipedia has a pretty good article about it), and it's all meant for fluent C++ programmers, not for C++ novices. There is, unfortunately, not a single text out there teaching C++1x to C++ newbies And I'm afraid it might take years before you can make your pick between several recommended books doing this. And don't forget the C++ FAQ, which is a pretty good (and very readable) online collection of best practices (and their rationals), although it's by no means an introductory text. A: There is no substitute for practice. Find a program you want on your machine (maybe as simple as something that counts the number of lines in a project), and write it in C++. I wish I could tell you that I have an awesome resource that shows you every C++ trick in the book, but truth be told, you are that resource. Practice. Learn from your own mistakes. You are your best teacher.
{ "pile_set_name": "StackExchange" }
Q: How to activate JOptionPane from another class? I have main class with a main GUI from where I want to activate and get values from a new class with a JOptionPane like the code below. Since I already have a main GUI window opened, how and where should I activate/call the class below and finally, how do I get the values from the JOptionPane? Help is preciated! Thanks! import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class OptionPaneTest { JPanel myPanel = new JPanel(); JTextField field1 = new JTextField(10); JTextField field2 = new JTextField(10); myPanel.add(field1); myPanel.add(field2); JOptionPane.showMessageDialog(null, myPanel); } Edit: InputNewPerson nyPerson = new InputNewPerson(); JOptionPane.showMessageDialog(null, nyPerson); String test = nyPerson.inputName.getText(); A: I guess looking at your question, you need something like this. I had made a small JDialog, where you will enter a UserName and Answer, this will then be passed to the original GUI to be shown in the respective fields, as you press the SUBMIT JButton. Try your hands on this code and ask any question that may arise : import java.awt.*; import java.awt.event.*; import javax.swing.*; /* * This is the actual GUI class, which will get * values from the JDIalog class. */ public class GetDialogValues extends JFrame { private JTextField userField; private JTextField questionField; public GetDialogValues() { super("JFRAME"); } private void createAndDisplayGUI(GetDialogValues gdv) { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationByPlatform(true); JPanel contentPane = new JPanel(); contentPane.setLayout(new GridLayout(0, 2)); JLabel userName = new JLabel("USERNAME : "); userField = new JTextField(); JLabel questionLabel = new JLabel("Are you feeling GOOD ?"); questionField = new JTextField(); contentPane.add(userName); contentPane.add(userField); contentPane.add(questionLabel); contentPane.add(questionField); getContentPane().add(contentPane); pack(); setVisible(true); InputDialog id = new InputDialog(gdv, "Get INPUT : ", true); } public void setValues(final String username, final String answer) { SwingUtilities.invokeLater(new Runnable() { public void run() { userField.setText(username); questionField.setText(answer); } }); } public static void main(String... args) { Runnable runnable = new Runnable() { public void run() { GetDialogValues gdv = new GetDialogValues(); gdv.createAndDisplayGUI(gdv); } }; SwingUtilities.invokeLater(runnable); } } class InputDialog extends JDialog { private GetDialogValues gdv; private JTextField usernameField; private JTextField questionField; private JButton submitButton; private ActionListener actionButton = new ActionListener() { public void actionPerformed(ActionEvent ae) { if (usernameField.getDocument().getLength() > 0 && questionField.getDocument().getLength() > 0) { gdv.setValues(usernameField.getText().trim() , questionField.getText().trim()); dispose(); } else if (usernameField.getDocument().getLength() == 0) { JOptionPane.showMessageDialog(null, "Please Enter USERNAME." , "Invalid USERNAME : ", JOptionPane.ERROR_MESSAGE); } else if (questionField.getDocument().getLength() == 0) { JOptionPane.showMessageDialog(null, "Please Answer the question" , "Invalid ANSWER : ", JOptionPane.ERROR_MESSAGE); } } }; public InputDialog(GetDialogValues gdv, String title, boolean isModal) { this.gdv = gdv; setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setLayout(new BorderLayout()); setModal(isModal); setTitle(title); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(0, 2)); JLabel usernameLabel = new JLabel("Enter USERNAME : "); usernameField = new JTextField(); JLabel questionLabel = new JLabel("How are you feeling ?"); questionField = new JTextField(); panel.add(usernameLabel); panel.add(usernameField); panel.add(questionLabel); panel.add(questionField); submitButton = new JButton("SUBMIT"); submitButton.addActionListener(actionButton); add(panel, BorderLayout.CENTER); add(submitButton, BorderLayout.PAGE_END); pack(); setVisible(true); } }
{ "pile_set_name": "StackExchange" }
Q: Star Trek: The Next Generation episode with a black snowman My three-year-old daughter has just been telling me about an episode of The Next Generation which was on earlier. The man runned on the sand and he fell in the black thing, and he came up a black snowman. Followed by The mans had their orange torches, and they threw fire on the black snowman and it melted. My curiosity is piqued; can anyone help me identify this episode where phaser fire (I presume) melts a black creature in a sandy environment? A: My best guess is "Skin of Evil" (S01E23), in which Riker gets absorbed by what could be described compactly as a sludge monster and is later spat out covered in Metamucil and printer ink. While the monster isn't destroyed, melted, or even harmed by phaser fire, I'm quite certain that at some point he responds to phaser fire by "melting down" into a less anthropomorphic, more ooze-like form and retreating.
{ "pile_set_name": "StackExchange" }
Q: Where did Parashurama teach Dronacharya & Karna? What is the present name of the place where Parashurama taught Dronacharya and Karna from the Mahabharat? Is the place currently an aashrama? A: The scriptures mention that Parashurama gifted the entire earth to Prajapati Kashyap and retired to the Mahendra mountains. As mentioned in the Canto 9 of Shrimad Bhagavatam: SB 9.16.26: Lord Parasurama still lives as an intelligent brahmana in the mountainous country known as Mahendra. Completely satisfied, having given up all the weapons of a kshatriya, he is always worshiped, adored and offered prayers for his exalted character and activities by such celestial beings as the Siddhas, Caranas and Gandharvas. This Mahendragiri is believed to be in modern day Odisha. This is where Karna learnt from the avatar as mentioned in the Shanti Parva of Mahabharat: Thus addressed by him, Drona, from partiality for Phalguna, as also from his knowledge of the wickedness of Karna, said, 'None but a Brahmana, who has duly observed all vows, should be acquainted with the Brahma weapon, or a Kshatriya that has practised austere penances, and no other.' When Drona had answered thus, Karna, having worshipped him, obtained his leave, and proceeded without delay to Rama then residing on the Mahendra mountains. Approaching Rama, he bent his head unto him and said, 'I am a Brahmana of Bhrigu's race.' This procured honour for him. With this knowledge about his birth and family, Rama received him kindly and said, 'Thou art welcome!' at which Karna became highly glad. While residing on the Mahendra mountains that resembled heaven itself, Karna met and mixed with many Gandharvas, Yakshas, and gods. Regarding Parshurama teaching Dronacharya, he didn't really take him as a student rather just gave him some of his divine weapons when he was preparing to retire from active life. Drona and Drupada were actually taught by Drona's father Bharadwaj. The Chaitraratha Parva of the Mahabharat mentions these details: And about the time that Drona was born, Prishata also obtained a son named Drupada. And that bull amongst Kshatriyas, Prishata's son, going every day to that asylum of Bharadwaja, played and studied with Drona. And after Prishata's death, Drupada succeeded him on the throne. Drona about this time heard that (the great Brahmana hero) Rama (on the eve of his retiring into the weeds) was resolved to give away all his wealth. Hearing this, the son of Bharadwaja repaired unto Rama who was about to retire into the woods and addressing him, said, 'O best of Brahmanas, know me to be Drona who hath come to thee to obtain thy wealth.' Rama replied, saying, 'I have given away everything. All that I now have is this body of mine and my weapons. O Brahmana, thou mayest ask of me one of these two, either my body or my weapons.' Then Drona said, 'It behoveth thee, sir, to give me all thy weapons together with (the mysteries of) their use and withdrawal.' "The Brahmana continued, 'Then Rama of Bhrigu's race, saying, 'So be it,' gave all his weapons unto Drona, who obtaining them regarded himself as crowned with success. Drona obtaining from Rama the most exalted of all weapons, called the Brahma weapon, became exceedingly glad and acquired a decided superiority over all men. Coming back to Mahendra Parvata, later on in the story, when the Pandavs are in exile they reach Mahendra mountain and as mentioned in Section CXV of the Vana Parva they meet a rishi called Akritavrana there who narrates the entire life-story of Parshurama to the Pandavs. When Yuddhishtir asks him when can he get a glimpse of Lord Parshurama, Akritavrana replies: 'Thy journey to this spot is already known to Rama, whose soul spontaneously knows everything. And he is in every way well-pleased with thee, and he will show himself readily to thee. And the saints who practise penances here, are permitted to see him on the fourteenth and the eighth day of the lunar course. On the morrow at the end of this very night there will set in the fourteenth day of the lunar course. On that occasion thou wilt have a sight of him, clad in a sable deerskin, and wearing his hair in the form of a matted mass." From the above verses it seems that there indeed was an Ashram on the Mahendra mountain where many other rishis used to reside. Again in the Uluka Dutagamana Parva the rishi Hotravahana tells Amba, the princess of Kashi: Do not go back to thy father's abode, O blessed lady! I am the father of thy mother. I will dispel thy grief. Rely on me, O daughter! Great, indeed, must thy affliction he when thou art so emaciated! At my advice, go unto the ascetic Rama, the son of Jamadagni. Rama will dispel this great affliction and grief of thine. He will slay Bhishma in battle if the latter obeyeth not his behest. Go, therefore, unto that foremost one of Bhrigu's race who resembleth the Yuga-fire itself in energy! That great ascetic will place thee once more on the right track!' Hearing this, that maiden, shedding tears all the while, saluted her maternal grandsire, Hotravahana, with a bend of her head and addressed him, saying, 'Go I will at thy command! But shall I succeed in obtaining a sight of that reverend sire celebrated over the world? How will he dispel this poignant grief of mine? And how shall I go to that descendant of Bhrigu? I desire to know all this.' "Hotravahana said, 'O blessed maiden, thou wilt behold Jamadagni's son, Rama, who is devoted to truth and endued with great might and engaged in austere penances in the great forest. Rama always dwelleth in that foremost of the mountains called Mahendra. Many Rishis, learned in the Vedas, and many Gandharvas and Apsaras also dwell there. Go, blessed be thou, and tell him these words of mine, having saluted with thy bent head that sage of rigid vows and great ascetic merit. Tell him also, O blessed girl, all that thou seekest. If thou namest me, Rama will do everything for thee, for Rama, the heroic son of Jamadagni, that foremost of all bearers of arms, is a friend of mine highly pleased with me, and always wisheth me well!' All the above mentioned verses indicate that Parshurama had a permanent abode at Mahendra Parvat. Coming to what exists there today, you can check out this link which details the temples existing there today - Temples on Mahendragiri Hills.
{ "pile_set_name": "StackExchange" }
Q: How to search over and return elements of your knockout view model by some property I have a view model that has an observableArray of timeSlices. Among other properties, each timeSlice has a time, place, and status. When a user clicks on one timeSlice, I want to query the surrounding ones to test their status. So basically, I want to search through my observableArray() at specific time/places to check other properties about the elements. How can this be done in knockout? A: A knockout observable array is just a javascript array when unwrapped. You could use a computed if you want to associate a subset of items with the item just clicked var samePlaceSlices = ko.computed(function() { // assumes you have observableArray called timeSlices var timeSlicesArr = timeSlices(), samePlaceSliceArr = []; // just loop through items like a normal array for(var i = 0; i < timeSlicesArr.length; i++) { // assumes slices have a property called place, not an observable // and a single observable called clickedSlice that is the last clicked slice if(timeSlicesArr[i].place == clickedSlice().place) { samePlaceSliceArr.push(timeSlicesArr[i]); } } return samePlaceSliceArr;
{ "pile_set_name": "StackExchange" }
Q: How to separate site configurations among managed multi sites I have got concerns raised by the 2 teams (to work in the same time) that multi site configuration may not be a solution for them. We want to have different sites working in the same instance of Sitecore. For example: In the situation when we have multi site <site> configured (Let's assume SiteDefinition.config or Dynamic Sites Manager for Sitecore) and Web A has to use Membership provider "One" and Web B has to use Membership provider "Two" what is the best way to handle this situation? And what is the other risk from having 2 teams working in 2 different web projects in the same Sitecore instance? A: Working multiple teams in one Sitecore solution is a question of discipline and organisation. By organisation I primarily mean how and where assets for the sites are stored and organised. To start with your example however; different sites needing different membership providers. You don't actually map sites directly to a provider, you map them to a default domain. Extranet by default, but this can be changed. <site name="sitea" domain="domaina" ... /> <site name="siteb" domain="domainb" ... /> And each membership provider in your solution would be set up, to deliver these new domains to your solution. As for how to organise yourselves; I recommend following the guidelines laid out in the Helix architecture recommendations. Specifically the section named Patterns, Principles and Conventions that directly discusses everything related to multi-tenant implementations, file structure, organising Sitecore content, security setup and so on. In short. Yes, there are some more things to consider when working multiple teams in the same solution, but it is definitely doable and done by many teams around the world every day. Breaking up your solution into two separate Sitecore instances has the added implication of needing a whole new set of licenses. One set for each site. Depending on your customer, this might not be an option at all.
{ "pile_set_name": "StackExchange" }
Q: Javascript playing with object items I'm having 2 sets of object, an example: var objA = {}; objA.data1a = 100; objA.data2a = 70; objA.data3a = 16; objA.data4a = 37; objA.data5a = 88; //my ObjA will contain the following //{"data1a":100, "data2a":70, ......... "data5a":88} var objB = {} objA.data1b = 19; objA.data2b = 5; objA.data3b = 7; objA.data4b = 6; objA.data5b = 2; var getDifferences = {}; //I want to get the differences using a loop but I'm not sure how am I able to do so. //I am able to do this currently // getDifferences.data1 = objA.data1a - objB.data1b; // getDifferences.data2 = objA.data2a - objB.data2b; // getDifferences.data3 = objA.data3a - objB.data3b; may I know if there's a loop to loop through an object so that for each loop I can minus and store the differences into another object? A: An iteration over the keys. I assume, that objB should contain the other values. var objA = { data1a: 100, data2a: 70, data3a: 16, data4a: 37, data5a: 88 }, objB = { data1b: 19, data2b: 5, data3b: 7, data4b: 6, data5b: 2 }, getDifferences = {}; Object.keys(objA).forEach(function (k) { var kk = k.substring(0, k.length - 1); getDifferences[kk] = objA[kk + 'a'] - objB[kk + 'b']; }); document.write('<pre>' + JSON.stringify(getDifferences, 0, 4) + '</pre>'); More Example What if.. my naming were different? EXAMPLE: var storeA = {}; {"1000": 532, "2020": 123} and var storeB = {}; {"1000": 200, "2020": 12} var storeA = {"1000": 532, "2020": 123}, storeB = {"1000": 200, "2020": 12}, getDifferences = {}; Object.keys(storeA).forEach(function (k) { getDifferences[k] = storeA[k] - storeB[k]; }); document.write('<pre>' + JSON.stringify(getDifferences, 0, 4) + '</pre>'); Even more Example in storeX obj and storeY obj. { '4100': 3060431, '4130': 4413045, '16386': 4191921, '17476': 4161761 } { '4100': 3332286, '4130': 7640173, '16386': 5773080, '17476': 4692493 } var storeA = { '4100': 3060431, '4130': 4413045, '16386': 4191921, '17476': 4161761 }, storeB = { '4100': 3332286, '4130': 7640173, '16386': 5773080, '17476': 4692493 }, getDifferences = {}; Object.keys(storeA).forEach(function (k) { getDifferences[k] = Math.abs(storeA[k] - storeB[k]); }); document.write('<pre>' + JSON.stringify(getDifferences, 0, 4) + '</pre>');
{ "pile_set_name": "StackExchange" }
Q: What is php composer and what does dependency manager mean? I'm trying to understand what exactly composer is and does. I'm totally new to it and what the concepts are that surround it. The things I have problems with are: What is a dependency? What does it mean in PHP? What does it mean that composer is a dependency manager? What is the main argument for using composer or a dependency manager in general? A: can you please explain the main reason why I should use composer and what is a dependency You use it to install libraries made by other people. Example: you're dealing with dates in your PHP application. You can use date function and DateTime class that comes with PHP. However, you need to display a human-readable date in format of "5 minutes ago" or "in 2 hours" etc. So you get to developing and you realize that you're going to spend time on this feature. It's a nice to have, but it takes time to do it. A wise developer will think "Someone definitely had the same issue as I did, let's see how they solved it" and you stumble upon this library: Carbon Now you want to use this library because it takes care of your problem. Your option is to download it from github and add to your project manually, which means placing it in some directory, including it in your app etc. OR you can use Composer and you can tell Composer that you want a specific version of the library. In your terminal, you type: composer require "nesbot/carbon: ~1.21" Composer downloads the specific version of the library, places it in vendor/ directory and provides you with an autoloader. For you, that means you can: Install libraries made by other developers Track which version of libraries you installed and lock down your project to that specific library version You get an autoloader, so it's simple for you to add libraries to your project, you don't have to manually type require or include because all you need to do is include vendor/autoload.php to gain access to all libraries installed via composer. Since you most likely had issues with dates, databases, mailing and so on - other people had them as well and some of those people were awesome enough to create free code for the rest of us to use. Composer helps you get that code and manage it.
{ "pile_set_name": "StackExchange" }
Q: If $0 < r < p < \infty$, then $\|f\|_r \leq (\frac{p}{p-r})^{1/r} \mu(X)^{1/r - 1/p} \|f\|_{p, w}$ (weak $L^p$ norm) Let $(X, \mu)$ be a finite measure space. If $0 < r < p < \infty$, prove that $||f||_r \leq (\frac{p}{p-r})^{1/r} \mu(X)^{1/r - 1/p} \|f\|_{p, w}$. Here $\|f\|_{p, w}$ is the "weak $L^p$ norm" on $f$, equal to $\sup\limits_{k > 0} {k \mu(\lbrace x: |f(x)| > k \rbrace)^{1/p}}$. The problem comes with a hint to first show $\mu(\lbrace x: |f(x)| > t \rbrace) \leq \min\{\mu(X), t^-p ||f||_{p, w}\}$ and then use the layer cake principle. I've figured out that inequality and I'm sure I could work out the rest if I knew what function to use for the layer cake principle, and what "version" of f I should be composing it with (i.e., $|f|, |f|^p, |f|^r$). I would appreciate some kind of hint toward finding that function, as my own attempts at doing so have failed. A: Hint: if $\lambda(t)=\mu\left(\left\{x:|f(x)|>t\right\}\right)$, then $$\int_X|f|^r\,d\mu=r\int_0^{\infty}t^{r-1}\lambda(t)\,dt.$$ Then break this integral in two intervals, $[0,M]$ and $[M,\infty)$, and minimize the resulting function of $M$.
{ "pile_set_name": "StackExchange" }
Q: Plotting multivariable integration If I have a multivariable integration like NIntegrate[x^2 + y^2, {x, 1, 5}, {y, 6, 10}] But I need to plot its result in terms of x . Then how to do it ? A: DSaad's answer above is correct. You can use symbolic integration to get the formula. The solution when using numeric integration (NIntegrate instead of Integrate) can more complicated. You have to be careful about the order of evaluation. In earlier versions of Mathematica, you had to use ?NumericQ to delay the evaluation of the numeric integral: myFunction[t_?NumericQ]:= NIntegrate[x^2 + y^2, {x, 0, t}, {y, 6, 10}]; Plot[myFunction[t], {t, 0, 6}] To see why ?NumericQ is needed here, please see this. Using ?NumericQ is a still a good idea. It helps your function to behave consistently and makes your code more predictable. A: I think this would be your answer : data = Integrate[x^2 + y^2, {x, 0, t}, {y, 6, 10}]; Plot[data, {t, 0, 6}] and this would be your Graphic :
{ "pile_set_name": "StackExchange" }
Q: JSP - issue with custom Taglib I just tried to add a custom taglib to my project, such that the testtaglib.tld file contains: <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>name</shortname> <tag> <name>test</name> <tagclass>taglib.TestTaglib</tagclass> <bodycontent>empty</bodycontent> <attribute> <name>testCode</name> <required>true</required> <rtexprvalue>true</rtexprvalue> <type>java.lang.String</type> </attribute> </tag> <taglib> And then I added taglib class TestTaglib.java public class TestTaglib extends TagSupport { private String testCode; public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); //doing some conversion with testCode out.print(testCode); return EVAL_PAGE; } catch(IOException ioe) { throw new JspException("Error: " + ioe.getMessage()); } } } And then in .jsp file <name:test testCode="${testCode}"/> Okay the issue is:TestTaglib.java is recognizing values of testCode as ${testCode} and not the original value. Any suggestion? A: Hi all inbuilt tag already handles the expression language. Just change your code as mentioned below and it will work fine. public class TestTaglib extends TagSupport { private String testCode; public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); //doing some conversion with testCode String value = (String) ExpressionUtil.evalNotNull("test", "testCode", testCode, String.class, this, pageContext); out.print(value); return EVAL_PAGE; } catch(IOException ioe) { throw new JspException("Error: " + ioe.getMessage()); } } } ExpressionUtil is class provided under org.apache.taglibs.standard.tag.el.core package. Here is short desc of evalNotNull method args 1) tagName : your tag name is test 2) tagAttribute: to eval in your case it is testCode 3) expression : which is el expression ${testCode} 4) Value: Class of expression value whether it is Boolean,String or any Object 5) tagClass: Reference of tag handler class so you can pass this 6) pageContext: which is coming from TagSupport
{ "pile_set_name": "StackExchange" }
Q: Rough, easy DIY method of measuring magnetic field strength How to easily, using standard DIY equipment measure the strength of magnetic field generated by a permanent magnet? Narrowing down the "loose language" of the above: strength of magnetic field: either flux density B at given point relative to the magnet or magnetic flux ΦB over area enclosed by a loop made of wire - whichever will be easier to measure, either of those is fine. standard DIY equipment: commonly found household items, rudimentary tinkering tools. Soldering tools, multimeter, simple electronic parts, or maybe an easy to make spring-based dynamometer - anything of this class of complexity. The distance of measurement is such that the field is easily noticeable through simplest methods e.g. another magnet held in hand exerts perceptible force - distance of maybe 5cm away at most. The measurement doesn't need to be very accurate - error of order of 50% is quite acceptable. Simplicity is preferred over accuracy. Rationale: trying to estimate what coil I need to generate sufficient amount of power to light a LED with a frictionless generator based on that magnet (knowing speed of movement of the magnet and location of the coil relative to the path of the magnet). If you know other simple methods of doing that (without need for measuring the field), they are most welcome them too. A: The easiest method is to put a magnetic compass on one of the magnet's axes of symmetry, and orient the compass and magnet such that the magnet's field is perpendicular to the earth's. Then the tangent of the deflection angle is equal to the ratio of the fields. A: For what it's worth: http://www.coolmagnetman.com/magmeter.htm - a home-made device based on a Hall effect device - for about $40.
{ "pile_set_name": "StackExchange" }
Q: How to change the size of one image in a LayerDrawable Hello I am working on a android launcher that has a circle background behind all the app icons. I am using a LayerDrawable to get this to work however the circle image is smaller then the app icons see here: So my question is how do I make the circle icon bigger than the app icon? heres my circle icon code: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="oval"> <stroke android:color="#ccc" android:width="5dp" /> <solid android:color="#ffffff"/> <size android:width="58dp" android:height="58dp"/> </shape> </item> </selector> and heres my class that generates the app icons: package Appname.widget; import android.content.ClipData; import android.content.Context; import android.content.Intent; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.support.annotation.ColorInt; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.View; import android.widget.ImageView; import appame.R; import appname.AppManager; import appname.util.DragAction; import appname.util.GoodDragShadowBuilder; import appname.util.LauncherSettings; import appname.util.Tool; public class AppItemView extends View implements Drawable.Callback{ public Drawable getIcon() { return icon; } public void setIcon(Drawable icon) { this.icon = icon; this.icon.setCallback(this); } @Override public void refreshDrawableState() { invalidateDrawable(icon); super.refreshDrawableState(); } @Override public void invalidateDrawable(Drawable drawable) { invalidate(); } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public float getIconSize() { return iconSize; } public void setIconSize(float iconSize) { this.iconSize = iconSize; } private float iconSize; private Drawable icon; private String label; public boolean isShortcut; public Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Rect mTextBound = new Rect(); private boolean noLabel,vibrateWhenLongPress; private float labelHeight; public AppItemView(Context context) { super(context); init(); } public AppItemView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init(){ setWillNotDraw(false); labelHeight = Tool.convertDpToPixel(14,getContext()); textPaint.setTextSize(sp2px(getContext(),14)); textPaint.setColor(Color.DKGRAY); } public static int sp2px(Context context, float spValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); } @Override protected void onDraw(Canvas canvas) { Drawable iconback = getResources().getDrawable(R.drawable.iconback); LayerDrawable appicon = new LayerDrawable(new Drawable[]{iconback, icon}); appicon.setLayerGravity(0, Gravity.CENTER); appicon.setLayerGravity(1, Gravity.CENTER); if (label != null && !noLabel){ textPaint.getTextBounds(label,0,label.length(),mTextBound); } //The height should be the same as they have the same text size. float mHeight = iconSize + (noLabel? 0 : labelHeight); float heightPadding = (getHeight() - mHeight)/2f; if (label != null && !noLabel) { float x = (getWidth()-mTextBound.width())/2f; if (x < 0) x = 0; canvas.drawText(label,x, getHeight() - heightPadding, textPaint); } if (appicon != null ) { canvas.save(); canvas.translate((getWidth()-iconSize)/2,heightPadding); appicon.setLayerWidth(1, (int) iconSize); appicon.setLayerHeight(1, (int) iconSize); appicon.setBounds(0,0,(int)iconSize,(int)iconSize); appicon.draw(canvas); canvas.restore(); } } public static class Builder{ AppItemView view; public Builder(Context context){ view = new AppItemView(context); float iconSize = Tool.convertDpToPixel(LauncherSettings.getInstance(view.getContext()).generalSettings.iconSize, view.getContext()); view.setIconSize(iconSize); } public AppItemView getView(){ return view; } public Builder setAppItem(AppManager.App app){ view.setIcon(app.icon); view.setLabel(app.appName); return this; } public Builder withOnClickLaunchApp(final AppManager.App app){ view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Tool.createScaleInScaleOutAnim(view, new Runnable() { @Override public void run() { Tool.startApp(view.getContext(), app); } }); } }); return this; } public Builder withOnLongClickDrag(final AppManager.App app,final DragAction.Action action,@Nullable final OnLongClickListener eventAction){ withOnLongClickDrag(Desktop.Item.newAppItem(app),action,eventAction); view.setScaleX(0.75f); // <- resized by scaling view.setScaleY(0.75f); return this; } public Builder withOnLongClickDrag(final Desktop.Item item, final DragAction.Action action, @Nullable final OnLongClickListener eventAction){ view.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { if (view.vibrateWhenLongPress) v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); Intent i = new Intent(); i.putExtra("mDragData", item); ClipData data = ClipData.newIntent("mDragIntent", i); v.startDrag(data, new GoodDragShadowBuilder(v), new DragAction(action), 0); if (eventAction != null) eventAction.onLongClick(v); return true; } }); return this; } public Builder withOnTouchGetPosition(){ view.setOnTouchListener(Tool.getItemOnTouchListener()); return this; } public Builder setTextColor(@ColorInt int color){ view.textPaint.setColor(color); return this; } public Builder setNoLabel(){ view.noLabel = true; return this; } public Builder vibrateWhenLongPress(){ view.vibrateWhenLongPress = true; return this; } public Builder setShortcutItem(final Intent intent){ view.isShortcut = true; view.setScaleX(0.75f); // <- resized by scaling view.setScaleY(0.75f); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Tool.createScaleInScaleOutAnim(view, new Runnable() { @Override public void run() { view.getContext().startActivity(intent); } }); } }); view.setScaleX(0.75f); // <- resized by scaling view.setScaleY(0.75f); view.setIcon(Tool.getIconFromID(view.getContext(),intent.getStringExtra("shortCutIconID"))); view.setLabel(intent.getStringExtra("shortCutName")); return this; } } } Please note the icons are being generated in JAVA NOT XML! any help would be amazing! Thanks in advance :) A: Before creating the LayerDrawable you could wrap the icon inside a InsetDrawable like so: Drawable iconWithPadding = new InsetDrawable(icon, paddingSize); LayerDrawable appicon = new LayerDrawable(new Drawable[]{iconback, iconWithPadding}); That will effectively apply a padding to the icon.
{ "pile_set_name": "StackExchange" }
Q: Send GPS data while App is running background in Android I developed app that getting GPS data and send to Server. So i want to get GPS data while my app is running background in Android device. I have search in many websites, but i could not answer. I use 2 class. One of them is Main class and another is GPSTracker class. Now i give some part code of 2 class. Main Class public class Request extends Activity { public static Float longitude; public static Float latitude; public static int ID; public static String URL="http://xxx.xxx"; GPSTracker gps; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_request); final Button button_send_info = (Button)findViewById(R.id.button_send_info); final TextView show_infos = (TextView) findViewById (R.id.textView1); gps = new GPSTracker(Request.this); if(gps.canGetLocation()){ latitude = (float) gps.getLatitude(); longitude = (float) gps.getLongitude(); // \n is for new line Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); }else{ // can't get location // GPS or Network is not enabled // Ask user to enable GPS/network in settings gps.showSettingsAlert(); } if( Build.VERSION.SDK_INT >= 8){ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } button_send_info.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("latitude", latitude.toString())); postParameters.add(new BasicNameValuePair("longitude", longitude.toString())); String response = null; try { response = CustomHttpClient.executeHttpPost(URL, postParameters); String res=response.toString(); show_infos.setText(res); } catch (Exception e) { //hata alanı } } }); GPSTracker Class; public class GPSTracker extends Service implements LocationListener { protected LocationManager locationManager; public GPSTracker(Context context) { this.mContext = context; getLocation(); } public Location getLocation() { try { locationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE); // getting GPS status isGPSEnabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); // getting network status isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled && !isNetworkEnabled) { // no network provider is enabled } else { this.canGetLocation = true; if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } // if GPS Enabled get lat/long using GPS Services if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e) { e.printStackTrace(); } return location; } How can i do it? A: There is a component called Service in android. It provides background activity. You can perform background process in it. Service has no GUI. You can write a GPS fetching code there. Have a look at simple tutorial of Service components from Vogella.
{ "pile_set_name": "StackExchange" }
Q: display datatable between two primary key in datagridview C# (sorry my english is so bad) i try to display data in datagridview like this var db = new mydataDataContext(); var id1 = from data in db.tbl_adads where data.num1 ==int.Parse( txtnum1.Text) select data.id; int id_1 =int.Parse(id1.ToString()); var q = from show in db.tbl_adads where show.id > id_1 select show; dataGridView1.DataSource =q ; but when i run it and use it,compiler get error from int id_1 =int.Parse(id1.ToString()); and say An unhandled exception of type 'System.FormatException' occurred in System.Data.Linq.dll Additional information: Input string was not in a correct format. how can i do my work? A: id1 has type of IEnumerable<T> (where T is type of data.id). When you call ToString() on this variable you just get type name of variable, which cannot be parsed to int. Possibly you need just first matching result: var id1 = db.tbl_adads.Where(d => d.num1 == Int32.Parse(txtnum1.Text)) .Select(d => d.id) .FirstOrDefault();
{ "pile_set_name": "StackExchange" }
Q: Can I get close buttons to plasma widgets? I updated recently from kubuntu 14.04 to 18.04 and got new plasma 5.12.6. However, the widgets (like network manager, volume, battery, calendar etc) are all missing close buttons (crosses on the right top corner). I can close them by clicking the right icon on the toolbar again but it is slower and more difficult (first you need to know which icon to click, if it was opened accidentally, and second you need better eye-hand coordination since the toolbar icons are so small and close to each other). Instead of close buttons, there are useless pin buttons (which I always click accidentally, when searching for close). I am also remembering that in old plasma, it was possible to close widget windows by clicking anywhere the toolbar. Is this a new feature of plasma widgets? Is it possible to get the old close buttons back? Or the behaviour to close widgets by clicking the toolbar anywhere? Edit: Below a screenshot showing the task bar and one widget open. A: DK Bose's solved the problem. Left-click anywhere above the toolbar (but not on the toolbar itself) minimizes the widget.
{ "pile_set_name": "StackExchange" }
Q: Как аппроксимировать нелинейную функцию в Python Здравствуйте.У меня есть массив данных.Их нужно аппроксимировать использовав эту функцию:x=Ae^(-ht) sin(2π/T t+ф). В массиве данных указан год и сопуствующий ему темп роста.Если будет нужно я напишу данные.Пожалуйста помогите! Данные 1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016. 1 случай:1,-7.9,2.8,3.2,2.2,3.9,2.7,2.5,6.2,5.7,3.6,3.2,-0.4,5.6,3.3,3,2.6,5.9,-2.3,-1.1. 2 случай:3.2,-18.8,-5,0.7,5.5,0,4.2,3.4,1.3,12.2,1.4,11.3,0.3,2.9,5.1,4.9,-3.5,5.1,-1.9,-2.1 3 случай:-1.7,-13.5,7.4,6.5,-3.9,2.6,0.3,0.5,-1.5,8,0.8,4.5,1.9,2.8,-2.8,3.4,-2.2,-1.1,-11.3,7.7 A: Попробуйте так: import matplotlib.pyplot as plt from scipy.optimize import curve_fit def func(t, A, h, T, phi): return A*np.exp(-h*t)*np.sin(2*np.pi/T*t + phi) t = np.array([1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016]) y = np.array([1,-7.9,2.8,3.2,2.2,3.9,2.7,2.5,6.2,5.7,3.6,3.2,-0.4,5.6,3.3,3,2.6,5.9,-2.3,-1.1]) popt, pcov = curve_fit(func, t, y, (1e3, 1e-2, 1., -1e1), maxfev=10**6) A, h, T, phi = popt print('A={0}\nh={1}\nT={2}\nphi={3}'.format(*tuple(popt))) plt.scatter(t, y, s=30, color='orange') plt.plot(t, func(t, *popt)) Параметры: A=2.5799396598541523e+33 h=0.037592823141341276 T=1.0293760398048617 phi=348.9653603351754 График: UPDATE: RuntimeWarning: overflow encountered in exp это предупреждение о том, что во время оптимизации произошло переполнение в функции np.exp(), например np.exp(10**4) - выдаст такое предупреждение Можно ли сделать чтобы график был периодичнее? на самом деле периодичность будет заметна на большем интервале: plt.scatter(t, y, s=30, color='orange') x = np.arange(1980, 2040) plt.plot(x, func(x, *popt))
{ "pile_set_name": "StackExchange" }
Q: Why do books titled "Abstract Algebra" mostly deal with groups/rings/fields? As a computer science graduate who had only a basic course in abstract algebra, I want to study some abstract algebra in my free time. I've been looking through some books on the topic, and most seem to 'only' cover groups, rings and fields. Why is this the case? It seems to me you'd want to study simpler structures like semigroups, too. Especially looking at Wikipedia, there seems to be a huge zoo of different kinds of semigroups. A: There is not that much substantial to say about general semigroups at an introductory level, in comparison to groups, say, and what there is to say at this level (e.g. the theory of Green's relations) tends to rely on a prior understanding of groups in any case. (One thing I have in mind here --- but I am speaking as a non-expert --- is that semi-groups are much closer to general universal algebra than groups, and universal algebra is not, I would say, appropriate as a topic for a first course in abstract algebra.) The theory of groups lends itself well to a first course, because the axioms are fairly simple but lead fairly quickly to non-trivial theorems, such as the Sylow theorems. Groups (especially group actions) are also ubiquitous, and the kind of counting arguments which one can make are very useful to learn. (It is the inability to make these sorts of counting arguments that causes so many problems when you investigate semi-groups, in comparison to the case of groups.) The theory of fields is particularly useful in number theory, and Galois theory also provides a nice tie-in with the theory of groups, which in fact served as Galois's motivation for introducing groups in the first place. The theory of fields (especially the part to do with finding roots of polynomials) is also the part of abstract algebra that is closest to high school algebra, so it is not surprising that there is a substantial focus on it. The theory of rings normally appears both because it is a precursor to field theory (fields are particular kinds of rings, and the polynomial rings $F[x]$ also play an important role in the study of fields), and because it includes many basic examples from mathematics, such as matrix rings, the integers, quaternions, and so on. Rings also play an important role in the study of group representations (via the appearance of group rings), which, even if they don't appear in a first course, are just over the horizon. Summary: So overall, I think the answer is that groups, rings, and fields are the parts of algebra that are most closely connected to the basic core topics of mathematics, and are also closely integrated with one another. (Groups not immediately obviously so, but because of Galois theory and group rings, for example.) The theory of semigroups, by contrast, doesn't play much role in the rest of mathematics, and the theory that does exist is more complicated than the theory of groups (despite the axioms being simpler). A: Historically, the first "modern algebra" textbook was van der Waerden's in 1930, which followed the groups/rings/fields model (in that order). As far as I know, the first paper with nontrivial results on semigroups was published in 1928, and the first textbook on semigroups would have to wait until the 1960s. There is also a slight problem with the notion of "simpler". It is true that semigroups have fewer axioms than groups, and as such should be more "ubiquitous". However, the theory of semigroups is also in some sense "more complex" than the theory of groups, just as the theory of noncommutative rings is harder than that of commutative rings (even though commutative rings are "more complex" than rings because they have an extra axiom) and the structure theory of fields is simpler than that of rings (fewer ideals, for one thing). Groups have the advantage of being a good balance point between simplicity of structure and yet the ability to obtain a lot of nontrivial and powerful results with relatively little prerequisites: most 1-semester courses, even at the undergraduate level, will likely reach the Sylow theorems, a cornerstone of finite group theory. Semigroups require a lot more machinery even to state the isomorphism theorems (you need to notion of congruences). A: Historical inertia. A relatively small number of people were responsible for more or less deciding the modern abstract algebra curriculum around the beginning of the 20th century, and their ideas were so influential that their choice of topics is rarely questioned, for better or for worse. See, for example, Section 9.7 of Reid's Undergraduate commutative algebra.
{ "pile_set_name": "StackExchange" }
Q: How to make MainActivity ready before SplashActivity finish? I'd like to make my splash screen more smooth. I maked splash screen after I read this link. However, when I finish SplashActivity and intent to MainActivity, I feel SplashActivity finish too early, I saw screen saver of my device before MainActivity show (I estimate the delay to be 0.5s). What I want is the MainActivity ready before the SplashActivity finish. I tried the solutio that is set flags FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_CLEAR_TASK in my Intent, but it's not make smooth. Below is the code for transtion between 2 activities: private void transitionActivity() { Intent intent = new Intent(SplashActivity.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } And Manifest file: <activity android:name=".SplashActivity" android:launchMode="singleTask" android:theme="@style/SplashScreenTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".MainActivity" android:launchMode="singleTask" android:theme="@style/AppThemeNoActionBar" /> A: maybe the point is he want to give delay in splash screen if that so you can do that using Handler() int SplashDuration = 2000; new Handler().postDelayed(new Runnable() { @Override public void run() { Intent i = new Intent(splashScreen.this, MainActivity.class); startActivity(i); finish(); } }, SplashDuration); and if that still to fast or to slow for you, you can change the time at "SplashDuration"
{ "pile_set_name": "StackExchange" }
Q: Excessive memory allocation in Java Sandbox security Under the Java security model it is possible to block most dangerous actions from untrusted classes, but the last time I checked (a few years ago now) it was still possible for untrusted code to perform a denial of service attack by continually allocating memory until the JVM crashes with an OutOfMemoryException. Looking now, I can't see any improvement in the situation. I have a requirement to run untrusted code from 3rd parties inside a Java application and I'd like to know if it is possible to somehow restrict the heap/stack space that a class or thread can allocate in the Java security model. Thus preventing memory allocation based DoS attacks. I know about -Xss, but as I understand it that restricts all threads, most of which need no restriction. I have also considered creating a container for the untrusted code that will run in its own JVM and communicate with the main app through sockets, or doing some static analysis on the untrusted code. However, these both sound like more effort than I hoped, although if someone knows of a trick or opensource library for this I'm interested. So, is there a way to restrict the amount of memory than a thread can allocate to itself or some other way of preventing memory allocation denial of service attacks in Java? A: There is currently no way to do this with standard APIs in Java. More people have been interested in this and there is a JSR underway for this called Resource Consumption Management API which may be something to look into.
{ "pile_set_name": "StackExchange" }
Q: Can you make a CSS element into a link? I have a site that has a <header> which is styled so that the header graphic is the background-image. I would like to have the header link to the home page. Is there an elegant way to do this that will allow me to keep it as a header with a background-image? CSS: #header { background-image: url('../images/header.jpg'); height: 144px; display: block; } A: Background images are not linkable. The "proper" way to go about this would be to have an <a> element that has the appropriate href, and put the background-image to that. Use CSS to make the <a> tak up the needed space.
{ "pile_set_name": "StackExchange" }
Q: List view implementation with text view and toggle button i= Here in my application I want to create the list view with toggle button and text view. when I am clicking on the list item I want to go next Activity. But when I am clicking on the Toogle button I need to display it is in off mode or on mode. below I add my code. $ This is my main activity public class MainActivity extends Activity { int startminute; int endminute; Date date; ToggleButton togg; ListView lv; String[] days = { "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" }; boolean[] onOff = new boolean[] { false, false, false, false, false, false, false }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); if (savedInstanceState != null) { onOff = savedInstanceState.getBooleanArray("status"); } lv = (ListView) findViewById(R.id.listView1); lv.setAdapter(new MyAdapter()); lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { Intent in = new Intent(MainActivity.this, StartAndEndTime.class); in.putExtra("position", position); startActivity(in); } }); } public class MyAdapter extends BaseAdapter { public int getCount() { return days.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { return position; } @Override public int getViewTypeCount() { return days.length; } public View getView(final int position, View convertView, ViewGroup parent) { View v = null; TextView arryText; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.inflate, null); arryText = (TextView) v.findViewById(R.id.inflateText); togg = (ToggleButton) v.findViewById(R.id.toggleButton1); v.setTag(new ViewHolder(arryText, togg)); togg.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (togg.isChecked()) { togg.setChecked(false); onOff[position] = false; Toast.makeText(MainActivity.this, "is off", Toast.LENGTH_SHORT).show(); } else { onOff[position] = true; togg.setChecked(true); Toast.makeText(MainActivity.this, "is on", Toast.LENGTH_SHORT).show(); } } }); arryText.setText(days[position]); togg.setChecked(onOff[position]); } return v; } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBooleanArray("status", onOff); } A: change your getView method in this way... public View getView(final int position, View convertView, ViewGroup parent) { View v = null; TextView arryText; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.inflate, null); } arryText = (TextView) v.findViewById(R.id.inflateText); togg = (ToggleButton) v.findViewById(R.id.toggleButton1); v.setTag(new ViewHolder(arryText, togg)); togg.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (onOff[position]) { togg.setChecked(false); onOff[position] = false; Toast.makeText(MainActivity.this, "is off", Toast.LENGTH_SHORT).show(); } else { onOff[position] = true; togg.setChecked(true); Toast.makeText(MainActivity.this, "is on", Toast.LENGTH_SHORT).show(); } } }); arryText.setText(days[position]); togg.setChecked(onOff[position]); return v; }
{ "pile_set_name": "StackExchange" }
Q: How to check which subclass is the event fired? I know event.type in DOM. I can parse for example mouseup, keydown, touchstart and so on. But how can I check for the event subclass? Like MouseEvent, AnimationEvent or ClipboardEvent? Can I use the event.type property? A: You can check the class like void myHandler(Event e) { if(e is MouseEvent) { print('Mouse'); } else if(e is AnimationEvent) { print('Animation'); } else if(e is KeyboardEvent) { print('Keyboard'); } }
{ "pile_set_name": "StackExchange" }
Q: Android Grouped TextView My Android application has a form that the user has to fill in. I was looking for something like this. This http://img688.imageshack.us/img688/4162/photocr.jpg. I mean where the Edit Text look neat like this. Any suggestions on how we can replicate this in Android. I have seen a couple of Applications in Android that have a UI like this. Any suggestions will be welcome. Kind Regards, <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/round_linearlayout" android:orientation="vertical" > <EditText android:id="@+id/first_name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/first_name_hint_text" android:singleLine="true" android:textColor="#778BB0" android:textColorHint="#778BB0" android:textSize="13sp" android:textStyle="bold" /> <EditText android:id="@+id/last_name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/last_name_hint_text" android:singleLine="true" android:textColor="#778BB0" android:textColorHint="#778BB0" android:textSize="13sp" android:textStyle="bold" /> <EditText android:id="@+id/email_address" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/email_address_hint_text" android:singleLine="true" android:textColor="#778BB0" android:textColorHint="#778BB0" android:textSize="13sp" android:textStyle="bold" /> <EditText android:id="@+id/password" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/password_hint_text" android:singleLine="true" android:textColor="#778BB0" android:textColorHint="#778BB0" android:textSize="13sp" android:textStyle="bold" /> <Button android:id="@+id/already_have_an_account" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:background="@android:color/transparent" android:padding="20dp" android:text="@string/already_have_an_account" android:textColor="@color/hyperlink" /> </LinearLayout> A: Edited the answer to what you want. public class EditTextView extends LinearLayout{ private LayoutInflater inflater; private EditText edit_text; private TextView item; private View spacer; public EditTextView(Context context) { super(context); inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); initialize(); } public void setLabel(String label){ item.setText(label); } public void setText(String text){ item.setText(text); } public String getText(){ if((edit_text != null)&& (edit_text.getText() != null)){ return edit_text.getText().toString(); } return ""; } public void showSpacer(){ spacer.setVisibility(View.VISIBLE); } private void initialize() { inflater.inflate(R.layout.edit_text_view, this); edit_text = (EditText) findViewById(R.id.edit_text); item = (TextView) findViewById(R.id.edit_text_label); spacer = (View) findViewById(R.id.spacer); spacer.setVisibility(View.GONE); } } Used to get text as follows EditTextView textView = (EditTextView) groupedView2.getFieldViewAt(0); System.out.println(textView.getText()); textView = (EditTextView) groupedView2.getFieldViewAt(1); System.out.println(textView.getText()); This works for me very well. Let me know if you have any issues. A: It's easy what you want to achieve with android. You just need to use shape drawables for your edit texts. Here is how you can achieve this: shape drawables drawable for upper edit text <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <solid android:color="#ffffff"/> <corners android:topLeftRadius="15dp" android:bottomLeftRadius="0dp" android:topRightRadius="15dp" android:bottomRightRadius="0dp"/> </shape> drwable for lower edit text <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <solid android:color="#ffffff"/> <corners android:topLeftRadius="0dp" android:bottomLeftRadius="15dp" android:topRightRadius="0dp" android:bottomRightRadius="15dp"/> </shape> XML for the layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#3434ff" android:gravity="center" android:orientation="vertical" android:padding="50dp" > <ImageView android:id="@+id/img" android:layout_width="fill_parent" android:layout_height="80dp" android:background="@drawable/stack" android:layout_marginBottom="50dp" /> <EditText android:id="@+id/emailEdt" android:layout_width="fill_parent" android:layout_height="60dp" android:background="@drawable/edit_back1" android:hint="Email" android:paddingLeft="10dp" /> <View android:layout_width="fill_parent" android:layout_height="1dp" android:background="#5a5a5a" /> <EditText android:id="@+id/passwordEdt" android:layout_width="fill_parent" android:layout_height="60dp" android:background="@drawable/edit_back2" android:hint="Password" android:paddingLeft="10dp" /> </LinearLayout> The resulting layout will be like this:
{ "pile_set_name": "StackExchange" }
Q: How to create custom function for callback - tensorflow I am trying to create custom function in Tensorflow, to save and print selected data after every epochs. So I created callback class MyOwnFunction(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): print('Saving after {} epoch'.format(epoch + 1)) model.save('C:/Users/model.h5') with open('C:/Users/trainingHistory', 'wb') as file_pi: pickle.dump(history.history, file_pi) history = model.fit( train_generator, epochs=num_epochs, callbacks=[MyOwnFunction()], validation_data=validation_generator) But I am getting an error: NameError: name 'history' is not defined A: The object you bind to history in the global namespace does not exist until model.fit returns. That means it's not in the global namespace when fit calls your callback. In addition to accessing a variable that doesn't exist, the lines that open the file overwrite the contents every time the callback executes. The most likely solution is to move the following outside your function to the global namespace after binding history: with open('C:/Users/trainingHistory', 'wb') as file_pi: pickle.dump(history.history, file_pi)
{ "pile_set_name": "StackExchange" }
Q: wpf How to remove rectangle(corner) line form border <DockPanel Margin="5,5,5,5" Background="Red"> //the line color refercence this. <DockPanel Margin="0,12,0,0" HorizontalAlignment="Left"> <Path Data="M 12,12 C 5,10.3 2.9,7.6 0.25,0.25 6.9,5.16 8.5,5.1 12,5" Fill="#EEEEEE" /> <Border Margin="0,-6,0,0" Background="#EEEEEE" BorderBrush="#EEEEEE" BorderThickness="5" CornerRadius="5,5,5,5"> <TextBlock>#Test</TextBlock> </Border> </DockPanel> </DockPanel> I have create a Border to set the CornerRadius and BorderThickness, but the Border inside will show the rectangle(corner) line. May I know how to remove it?thanks. Other case: A: This will solve the issue. <DockPanel Margin="5,5,5,5" Background="red"> <DockPanel Margin="0,12,0,0" HorizontalAlignment="Left"> <Path Data="M 12,12 C 5,10.3 2.9,7.6 0.25,0.25 6.9,5.16 8.5,5.1 12,5" Fill="#EEEEEE" Margin="0,0,-1,0"/> <Border Margin="0,-6,0,0" Background="#EEEEEE" CornerRadius="5" Padding="5"> <TextBlock>#Test</TextBlock> </Border> </DockPanel> </DockPanel>
{ "pile_set_name": "StackExchange" }
Q: GWT hibernate spring serialization problem Hey everyone! I'm developing a gwt + spring + hibernate app, but when I run it I get this error: [WARN] Exception while dispatching incoming RPC call com.google.gwt.user.client.rpc.SerializationException: Type 'org.springframework.orm.jpa.JpaSystemException' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = org.springframework.orm.jpa.JpaSystemException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.karq.saatekava.shared.dto.TelekanalDTO; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.karq.saatekava.shared.dto.TelekanalDTO at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:614) at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:126) at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter$ValueWriter$8.write(ServerSerializationStreamWriter.java:152) at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeValue(ServerSerializationStreamWriter.java:534) at com.google.gwt.user.server.rpc.RPC.encodeResponse(RPC.java:616) at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:390) at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:588) at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:551) at org.spring4gwt.server.SpringGwtRemoteServiceServlet.processCall(SpringGwtRemoteServiceServlet.java:37) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248) at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:324) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505) at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488) [ERROR] 500 - POST /saatekava/springGwtService/telekanalService (127.0.0.1) 57 bytes A: You have 2 problems: You are trying to persist a detached object. You should merge it instead. The exception caused by 1) is not serializable because of GWT didn't notice it in your rpc service signature. Simple solution - catch exceptions in your RPC service methods and throw your custom one. Check out Gilead, it mayhelp. public void someRpcMethod() throws MyException{ try{ dosomething(); }catch(RuntimeException e){ throw new MyException("something failed", e); } } Tt might be good idea not to pass all exceptions to the client and handle them in different way. Here you can fine more informations: http://code.google.com/webtoolkit/doc/latest/tutorial/RPC.html#exceptions
{ "pile_set_name": "StackExchange" }
Q: Mac OS X Profile Manager I am wondering if when I set settings in profile manager if they should take place immediately. They currently only take effect after a restart or log out/in. I expected to send a push notification of some sort and have the settings take place immediately. If choose lock device - the device does lock immediately - so that part is working. Was just curious about if the settings should be immediate too and what I can do to troubleshoot. Before anyone suggests the firewall - firewall is off on the server and devices. Everything is on the same subnet so there is no routing taking place. Thanks! A: New profiles should be installed on the device quickly. If there are no network issues, my experience is that it should take under a minute for the device to get the update. Note that even with the server & devices on the same network, there can still be delays/problems due to internet connectivity: to push an update, the server sends a notification to one of Apple's push notification server (over the internet), that forwards the notification to the device (again, over the internet and subject to firewall etc issues), and then finally the device makes an HTTP (/HTTPS) connection to the server to actually fetch the new profile. But that doesn't necessarily mean the profile will take effect quickly. I've seen inconsistent behavior with programs/system components not loading the new settings until they're restarted (e.g. by a logout or reboot). You can check whether the new profile has been downloaded in System Preferences -> Profiles pane, or with the profiles command; if it shows up there, the download worked but the relevant program hasn't noticed it yet.
{ "pile_set_name": "StackExchange" }
Q: How do I add a custom font to a Cocoapod? I want to use a custom font within a Cocoapod, but I can't find anything on using a custom font within a static library. As there is no info.plist file, there is no where to tell the app what font to use. Any ideas? A: There is a way of using a custom font without adding anything to the plist file. NSBundle *bundle = [NSBundle bundleForClass:[self class]]; NSURL *fontURL = [bundle URLForResource:<#fontName#> withExtension:@"otf"/*or TTF*/]; NSData *inData = [NSData dataWithContentsOfURL:fontURL]; CFErrorRef error; CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData); CGFontRef font = CGFontCreateWithDataProvider(provider); if (!CTFontManagerRegisterGraphicsFont(font, &error)) { CFStringRef errorDescription = CFErrorCopyDescription(error); NSLog(@"Failed to load font: %@", errorDescription); CFRelease(errorDescription); } CFSafeRelease(font); CFSafeRelease(provider); You also need the CFSafeRelease function for this to work. void CFSafeRelease(CFTypeRef cf) { if (cf != NULL) { CFRelease(cf); } } Source: Loading iOS fonts dynamically. Swift equivalent: extension UIFont { static func registerFont(bundle: Bundle, fontName: String, fontExtension: String) -> Bool { guard let fontURL = bundle.url(forResource: fontName, withExtension: fontExtension) else { fatalError("Couldn't find font \(fontName)") } guard let fontDataProvider = CGDataProvider(url: fontURL as CFURL) else { fatalError("Couldn't load data from the font \(fontName)") } guard let font = CGFont(fontDataProvider) else { fatalError("Couldn't create font from data") } var error: Unmanaged<CFError>? let success = CTFontManagerRegisterGraphicsFont(font, &error) guard success else { print("Error registering font: maybe it was already registered.") return false } return true } } A: If I understand correctly, you are trying to provide a font with your Cocoapod, and you intent the iOS apps which include the pod to be able to use your custom font. This post_install hook seems to work: Pod::Spec.new do |s| # ... s.resources = "Resources/*.otf" # ... s.post_install do |library_representation| require 'rexml/document' library = library_representation.library proj_path = library.user_project_path proj = Xcodeproj::Project.new(proj_path) target = proj.targets.first # good guess for simple projects info_plists = target.build_configurations.inject([]) do |memo, item| memo << item.build_settings['INFOPLIST_FILE'] end.uniq info_plists = info_plists.map { |plist| File.join(File.dirname(proj_path), plist) } resources = library.file_accessors.collect(&:resources).flatten fonts = resources.find_all { |file| File.extname(file) == '.otf' || File.extname(file) == '.ttf' } fonts = fonts.map { |f| File.basename(f) } info_plists.each do |plist| doc = REXML::Document.new(File.open(plist)) main_dict = doc.elements["plist"].elements["dict"] app_fonts = main_dict.get_elements("key[text()='UIAppFonts']").first if app_fonts.nil? elem = REXML::Element.new 'key' elem.text = 'UIAppFonts' main_dict.add_element(elem) font_array = REXML::Element.new 'array' main_dict.add_element(font_array) else font_array = app_fonts.next_element end fonts.each do |font| if font_array.get_elements("string[text()='#{font}']").empty? font_elem = REXML::Element.new 'string' font_elem.text = font font_array.add_element(font_elem) end end doc.write(File.open(plist, 'wb')) end end The hook finds the user project, and in the first target (you probably can complete this solution by asking CocoaPods to give you the real target) it looks for its Info.plist file(s) (normally there is only one). Finally it looks for the UIAppFonts key of the file, creates it if not found, and fill the array with the font names if they are not already there. A: For those of you finding this in 2018+, I got custom fonts to work with interface builder support (XCode 9) with these two steps: Add your fonts to the resource bundle of your framework s.resources = "PodName/**/*.{ttf}" Load fonts at runtime using Adam's answer above #import <CoreText/CoreText.h> void CFSafeRelease(CFTypeRef cf) { // redefine this if (cf != NULL) { CFRelease(cf); } } + (void) loadFonts { NSBundle *frameworkBundle = [NSBundle bundleForClass:self.classForCoder]; NSURL *bundleURL = [[frameworkBundle resourceURL] URLByAppendingPathComponent:@"PodName.bundle"]; NSBundle *bundle = [NSBundle bundleWithURL:bundleURL]; NSURL *fontURL = [bundle URLForResource:@"HindMadurai-SemiBold" withExtension:@"ttf"]; NSData *inData = [NSData dataWithContentsOfURL:fontURL]; CFErrorRef error; CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData); CGFontRef font = CGFontCreateWithDataProvider(provider); if (!CTFontManagerRegisterGraphicsFont(font, &error)) { CFStringRef errorDescription = CFErrorCopyDescription(error); NSLog(@"Failed to load font: %@", errorDescription); CFRelease(errorDescription); } CFSafeRelease(font); CFSafeRelease(provider); }
{ "pile_set_name": "StackExchange" }
Q: How do I synchronize change in a UILabel text with a related animation? I have an animation of a drinking glass filling up from empty to full, using CAKeyframeAnimation. The animation works perfectly fine. I need to update a UILabel with the percentage corresponding to the fullness of the glass, i.e. it will read "0%" when the animation begins, and "100%" when it ends. The keyframe animation runs for 5 seconds. I don't see a good way of updating this label. I can think of two options: starting another thread and running a polling-type loop that updates the text at the cost of processing power. break down the animation into 100 parts and use CABasicAnimation to update the text and then proceed with the next bit of glass animation. Is there a better way to do this? Thanks in advance A: You can use either a NSTImer or dispatch_after() blocks to update the label at some scheduled interval: // assume an ivar "NSTimer *myTimer" and "int count", initially 0 // fires 20 times, so update is 0.05 myTimer = NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(updateLabel:) userInfo:nil repeats:YES - (void)updateLabel:(NSTimer *)timer { ++count; if(count >= 20) { [timer invalidate]; } CGFloat percent += 0.05; myLabel.text = [NSString stringWithFormat:... }
{ "pile_set_name": "StackExchange" }
Q: How to benchmark / test the speed of MySQL, Postgresql, MongoDB, where there are so many cache layers around? I think with SQLite3, at least it doesn't keep any cached page because there is no server and each write will exit SQLite3, so it can't do any caching directly. But when it is MySQL, Postgresql, or MongoDB, there will be a layer which, when the data is thought to be saved already, it is actually in the memory cache of the DBMS... to be written later to the disk. And even when it is written to the disk, there is an OS layer that keeps sectors that are to be written to the disk. And then there is the hard drive's cache. With it being 8MB, so maybe when the test is inserting data creating a 800MB database, then the error can be 1% or less. But what about the other layers? There really needs to be flushing all the way to the OS layer. Otherwise, with computers having 4GB of RAM or 8GB of RAM, the whole database can easily reside in RAM when it is thought to be quite fast. How do we tell the test to flush the data all the way to the hard disk physical layer or at least out of the OS layer? A: When you are doing benchmarking, you can never negate all the speed optimizations at every layer down to the OS or even CPU level, including caching. You don't need that. What you can do is to benchmark performance in the different lifecycle states of your system. Also, if you know what data is cached when (approximately) you can do benchmark before and after that. For example - clean start, first DB dataset access, subsequent DB access, etc. It is best to establish the bottlenecks first and then benchmark only there in greater details. Another good practise is to simulate a real life system load and benchmark that. Any syntetic benchmarks are practically pointless. Good luck ;)
{ "pile_set_name": "StackExchange" }
Q: How to write SQL to fetch the data of a column in another column I have 2 tables tblA & tblB. Now I want to fetch the name by op_code. tblA op_code | date | num ------------------------------------------------ a | 03/01 | 34 b | 04/03 | 5556 c | 03/05 | 555 tblB id | op_code | Name ------------------------------------------------ 1 | a | Jet 2 | b,c | Mike 3 | d | Tom As the op_code data in tblB is a combination data, so I try to write sql as below. select a.*, b.* from tblA a LEFT JOIN tblB b on a.op_code in (SUBSTRING_INDEX(b.op_code, ',', 13)) It doesn't work. Is there any suggestion? A: You may use FIND_IN_SET() here: SELECT a.*, b.* FROM tblA a LEFT JOIN tblB b ON FIND_IN_SET(a.op_code, b.op_code) > 0; But, as storing CSV data in your SQL tables is viewed as bad practice, because it is unnormalized data, you should only view this a temporary workaround query. A much better plan would be to commit to having just one record for each op_code relationship in the B table. Just for fun, here is another way to write your query using REGEXP: SELECT a.*, b.* FROM tblA a LEFT JOIN tblB b ON b.op_code REGEXP CONCAT('[[:<:]]', a.op_code, '[[:>:]]'); Here is a demo for the second version of the query: Demo
{ "pile_set_name": "StackExchange" }
Q: Adding simple error bars to Seaborn factorplot I have a factorplot that I have generated from a summary table, rather than raw data: Using the following code: sns.factorplot(col="followup", y="probability", hue="next intervention", x="age", data=table_flat[table_flat['next intervention']!='none'], facet_kws={'ylim':(0,0.6)}) Plotted here are the mean values from the summary table, but I would also like to plot the credible interval, whose upper and lower bounds are specified in two other columns. The table looks like this: Is there a way, perhaps using the FacetGrid returned by factorplot of tacking on the error bars to the points? A: You can pass plt.errorbar to FacetGrid.map but it requires a small wrapper function to reformat the arguments properly (and explicitly passing the category order): import numpy as np from scipy import stats import seaborn as sns import matplotlib.pyplot as plt # Reformat the tips dataset to your style tips = sns.load_dataset("tips") tips_agg = (tips.groupby(["day", "smoker"]) .total_bill.agg([np.mean, stats.sem]) .reset_index()) tips_agg["low"] = tips_agg["mean"] - tips_agg["sem"] tips_agg["high"] = tips_agg["mean"] + tips_agg["sem"] # Define a wrapper function for plt.errorbar def errorbar(x, y, low, high, order, color, **kws): xnum = [order.index(x_i) for x_i in x] plt.errorbar(xnum, y, (y - low, high - y), color=color) # Draw the plot g = sns.factorplot(x="day", y="mean", col="smoker", data=tips_agg) order = sns.utils.categorical_order(tips_agg["day"]) g.map(errorbar, "day", "mean", "low", "high", order=order)
{ "pile_set_name": "StackExchange" }
Q: Insert "-" between numbers while typing on edit text I am trying to format the value on edit text, as the user types. What i want is that the user should be be able to type, and see changes as the input is given. My requirement is that after, 3 digits types, a hyphen should be appended, after the first hyphen, another 4 digits will be typed, then another hyphen is to be appended, then after seven digits and then after 1. So basically, the formatting should look like this: 123-1234-1234567-1. Now, the problem is such that i am able to achieve this with standard text watcher, but while using backspace key, or delete on soft input keyboard, this malfunctions. My code is below: mEditText = (TextInputEditText) findViewById(R.id.myEditText); mEditText.addTextChangedListener(mTextWatcher); My Text watcher: private TextWatcher mTextWatcher= new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { String str = charSequence.toString(); mEditText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View view, int keyCode, KeyEvent keyEvent) { if(keyCode != KeyEvent.KEYCODE_DEL && mEditText.getText().toString().length() != 0){ if(mEditText.getText().length()==4 ||mEditText.getText().length()==9 ||mEditText.getText().length()==17 ||mEditText.getText().length()==19) { String tempString; char[] stringArray; tempString=mEditText.getText().toString()+"-"; char c=tempString.charAt(tempString.length()-2); if(c!='-') { stringArray = tempString.toCharArray(); stringArray[tempString.length()-2]=stringArray[tempString.length()-1]; stringArray[tempString.length()-1]=c; tempString=new String(stringArray); mEditText.setText(tempString); mEditText.setSelection(tempString.length()); tempString=null; } } } return false; } }); } @Override public void afterTextChanged(Editable editable) { if (editable.length() == 3) { editable.append('-'); } } }; Then, my xml: <android.support.design.widget.TextInputLayout android:id="@+id/phone_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="50dp"> <android.support.design.widget.TextInputEditText android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:maxLength="18" android:inputType="number"/> </android.support.design.widget.TextInputLayout> I want the operations to be performed in onTextChanged, as this method is called when the user is typing. My formatting is working fine, but if the user points the cursor to any digit in between and deletes a number, the formatting breaks, and another hyphen is appended at the end. So basically, i want to elegantly handle delete key on soft keyboard(i know no events are given for this), and then if the user types another number, it should be placed at the cursor location, and not at the end. A: You can achieve that with PatternedTextWatcher. Simple one line solution 1) Add this to your gradle file compile 'com.szagurskii:patternedtextwatcher:0.5.0' 2) Then your EditText will look like this mEditText = findViewById(R.id.mEditText); mEditText.addTextChangedListener(new PatternedTextWatcher("###-####-#######-#")); Final Result Works like a charm without any flaw
{ "pile_set_name": "StackExchange" }
Q: head_title drupal in html.html.twig in title tags {{ head_title|safe_join(' | ') }} This code display " home | " how to remove( | ) from display in home page? also in other page display " page | Home " i want title in other page display "Home | page " ? A: It's easier and better to override this using the Metatag module. The D8 version UI looks different than the picture below which is from D7. This video goes over the D8 version.
{ "pile_set_name": "StackExchange" }
Q: How do I scale a 8x8 pixel art Bitmap to be 100 pixels width and height without any distortion in Android? I'm making a game that is Pixel-based in Android. I have several 8x8 sprites that need to be resized to fit on a 100x100 area. As a test to see if it would work, I tried to just make the image fill the entire canvas. It kind of worked, but it made the 8x8 sprite turn into a 12x12 sprite, making the pixels look really odd and distorted. Here's what I have so far: Bitmap grass = BitmapFactory.decodeResource(getResources(), R.drawable.small); Paint configuration = new Paint(); configuration.setDither(false); configuration.setAntiAlias(false); Matrix myMatrix = new Matrix(); myMatrix.postScale(canvas.getWidth() / grass.getWidth(), canvas.getWidth() / grass.getHeight()); Bitmap resizedBitmap = Bitmap.createBitmap(grass, 0, 0, grass.getWidth(), grass.getHeight(), myMatrix, false); canvas.drawBitmap(resizedBitmap, 0, 0, null); A: If you work on bitmaps then you simply can't. You'd minimize the distortion by scaling up by non-fractional factor so each pixed would be repeated same number of times (i.e. image 10x10 to 20x20 is scaled by factor of two, but 8x8 to 12x12 is 1,5 so no luck). The solution would be to have all assets in vector form (i.e. SVG) and then render them on run-time according to device density and other specs or prepare separate assets for various type of devices (which would blow application size up a bit)
{ "pile_set_name": "StackExchange" }
Q: Unable to get Connection while using Hibernate Spatial We are using Weblogic, Hibernate 4.2.7, Hibernate Spatial 4.0 and Oracle as Database. Upon Performing Save operation some times we are observing Unable to get Connection Can you suggest any configuration we missed for Spatial ? Stack Trace : Caused by: org.hibernate.spatial.helper.FinderException: Tried retrieving OracleConnection from weblogic.jdbc.wrapper.JTSConnection_weblogic_jdbc_wrapper_PooledConnection_oracle_jdbc_driver_LogicalConnection using method getConnectionCacheCallbackPrivObj, but received null. at org.hibernate.spatial.dialect.oracle.DefaultConnectionFinder.find(DefaultConnectionFinder.java:75) at org.hibernate.spatial.dialect.oracle.DefaultConnectionFinder.find(DefaultConnectionFinder.java:44) at org.hibernate.spatial.dialect.oracle.OracleJDBCTypeFactory.createStruct(OracleJDBCTypeFactory.java:119) ... 79 more A: Hibernate Spatial for Oracle DB requires the native oracle connection (take a look to documentation section The ConnectionFinder Interface). You must adjust weblogic configuration or implement your own ConnectionFinder to provide the Oracle connetion to Hib-Spa. By example, if you were using use DBCP connection poll you just need set accessToUnderlyingConnectionAllowed property to true. Good luck!
{ "pile_set_name": "StackExchange" }
Q: Updating different columns with their corresponding where clause Let say Table1 and Table 2, Table 1 with columns DDcl1, DDcl2, DDcl3, ... I need to update these tables with update A set DDcl1 = 'Y' from Table1 A join Table2 B on A.id = B.id where B.Ref = 'cl1' update A set DDcl2 = 'Y' from Table1 A join Table2 B on A.id = B.id where B.Ref = 'cl2' update A set DDcl3 = 'Y' from Table1 A join Table2 B on A.id = B.id where B.Ref = 'cl3' Is there a way to update these tables with their corresponding where clauses in much easier way? I need to update more than 10 columns and with the above query it will take me for long writing it. A: update A set [DDcl1]= case when B.Ref = 'cl1' then 'Y' else 'N' end, [DDcl2]= case when B.Ref = 'cl2' then 'Y' else 'N' end --............. Add more codition from Table1 A join Table2 B on A.id = B.id
{ "pile_set_name": "StackExchange" }
Q: How can I compute $\lim_{|r|\to\infty}\int_{\Bbb R}|f(x+r)+f(x)|^p\ dx$ with $f\in L^p$? This is an exercise in real analysis: Suppose $f\in L^p(\Bbb{R})$ for $1\leq p<\infty$. Compute $$ \lim_{|r|\to\infty}\int_{\Bbb R}|f(x+r)+f(x)|^p\ dx. $$ For $p=1$ and nonnegative $f$, one gets $2\|f\|_{L^1}^1$. For $p=2$, $$ \begin{align} \int |f(x+r)+f(x)|^2\ dx&=\int f^2(x+r)+2f(x+r)f(x)+f^2(x)\ dx\\ &=2\|f\|_{L^2}^2+2\int f(x+r)f(x)dx. \end{align} $$ Then one can deal with the second term in the last equality with the dominated convergence theorem. But I don't see how to do the general case. $2\|f\|_p^p$ might be a reasonable guess though. A: The limit is indeed $2\|f\|_p^p$. Let $\varepsilon > 0$. We can decompose $f$ as $g + h$, where $g$ has compact support on $\Bbb R$ and $\|h\|_p < \varepsilon$. Define the translation operator $T_rh(x) := h(x + r)$. Choose a positive integer $k$ such that for $|r| > k$, the support of $T_rg$ is disjoint from the support of $g$. Hence, for $|r| > k$, \begin{align}\int_{\Bbb R} |g(x + r) + g(x)|^p\, dx &= \int_{\operatorname{supp}(g)}|g(x+r) + g(x)|^p\, dx + \int_{\operatorname{supp}(T_rg)} |g(x + r) + g(x)|^p\, dx\\ &= \int_{\operatorname{supp}(g)} |g(x)|^p\, dx + \int_{\operatorname{supp}(T_rg)} |g(x + r)|^p\\ &= \int_{\Bbb R} |g(x)|^p + \int_{\Bbb R} |g(x + r)|^p\\ &= \int_{\Bbb R} |g(x)|^p + \int_{\Bbb R} |g(x)|^p\\ &= 2\|g\|_p^p. \end{align} In other words, $$\|T_rg + g\|_p = 2^{1/p}\|g\|_p\quad \text{if}\quad |r| > k.$$ By the triangle inequality, if $|r| > k$, then \begin{align} \|T_rf + f\|_p - 2^{1/p}\|f\|_p & = \|(T_r g + g) + (T_rh + h)\|_p - 2^{1/p}\|g + h\|_p\\ & \le \|T_rg + g\|_p + \|T_rh + h\|_p - 2^{1/p}(\|g\|_p - \|h\|_p)\\ & \le (\|T_rg + g\|_p - 2^{1/p}\|g\|_p) + (\|T_rh + h\|_p + 2^{1/p}\|h\|_p)\\ & \lesssim_p \varepsilon \end{align} and \begin{align} \|T_rf + f\|_p - 2^{1/p}\|f\|_p &= \|(T_rg + g) + (T_rh + h)\|_p - 2^{1/p}\|g + h\|_p\\ &\ge \|T_rg + g\|_p - \|T_rh + h\|_p - 2^{1/p}(\|g\|_p + \|h\|_p)\\ &= (\|T_rg + g\|_p - 2^{1/p}\|g\|_p) - (\|T_rh + h\|_p + 2^{1/p}\|h\|_p)\\ &\gtrsim_p -\varepsilon. \end{align} Thus $$\Bigl|\|T_rf + f\|_p - 2^{1/p}\|f\|_p\Bigr| \lesssim_p \varepsilon \quad (|r| > k),$$ which shows that $\|T_rf + f\|_p \to 2^{1/p}\|f\|_p$ as $|r| \to \infty$. This implies $$\lim_{|r|\to \infty} \int_{\Bbb R} |f(x + r) + f(x)|^p = 2\|f\|_p^p.$$ Note. Using this result, one can show the Schroedinger operator $e^{it\Delta} : L^p(\Bbb R) \to L^q(\Bbb R)$ is not continuous for any triple $(p,q,t)$ satisfying $1 \le q < p < \infty$ and $t\in \Bbb R\setminus\{0\}$.
{ "pile_set_name": "StackExchange" }
Q: Sharing Internet Connection I have a Cable Internet (Assigned IP etc) to connect to internet and I want to connect another computer to same line of cable as well. Both in Same room. Any suggestion, affordable solution please? A: A common approach is to get a wifi or ethernet router. Connect this device to the cable internet device, then connect your computer to the wifi/ethernet router. Take a look at http://compnetworking.about.com/cs/homenetworking/a/homenetguide.htm
{ "pile_set_name": "StackExchange" }
Q: Why differential equations? Natural phenomena (e.g. heat flow) and systems (e.g. electrical circuits) are usually described using differential equations. Why is that? Also, usually people use "constant coefficients linear differential equations" of low order (one or two, rarely three). Is this use (constant coefficients, linear, low order) justified by the adequacy with the modeled phenomena or just by model simplification? There is also this seemingly equivalent version used when dealing with discrete systems (i.e. the independent variable is discrete) called "difference equation" instead of "differential equation" such that: Constant coefficients differential equation: $$\sum_{k=0}^N a_k \frac{d^ky(t)}{dt^k}= \sum_{k=0}^Mb_k \frac{d^kx(t)}{dt^k}$$ Constant coefficients difference equation: $$\sum_{k=0}^N a_k y[n-k]= \sum_{k=0}^Mb_k x[n-k]$$ I can't see how the difference is equivalent to the derivative. I know that this might not be a physics question but any insights would be appreciated. A: Given that time and space are believed to be continuous one would expect that the equations governing changes in time and space would reflect this continuity. In other words, we can make sense of the concept of two points arbitrarily close in space or two moments arbitrarily close in time, something that difference equations do not capture. The precise form of the differential equation depends on the physical phenomena and is not restricted to equations with constant coefficients. (As an aside: the great mathematician Henri Poincare was troubled by the quantized nature of some quantities (energy in particular), precisely asking if this would imply the rewriting of the laws of physics in the form of difference equations.) A: Well, Aristotle said that physics is the study of change and he then related change to motion, of which he said the primary kind of motion is physical motion. This means, that although there was no kinetic theory of heat in his time, he would not have been surprised to be told that heat (a form of change) was related to motion (of atoms). Now, since Newtons/Liebniz discovery of the calculus, physical motion is quantified and expressed through differential equations; this, in part, is conventional as the same can be expressed through integral equations. The kind of equations that come up are justified both by model simplification and adequacy, for example the first differential equation that one generally comes across is F=ma, which is a second order differential equation with a constant coefficient, which in this case is mass. Generally we take mass to be a constant, but it may vary as in a rocket which is rapidly burning fuel so it's mass is varying. Why order two? Well this comes from observation, recalling that motion is unaffected by position (all places are alike), and is also unaffected by the frame velocity (all constant frame velocities are alike), together this is Galilean relativity, and Newtons equation is the simplest possible with regards to these constraints. The real puzzle here is why motion is independent of the underlying frame velocity, and it turns out after Einstein that it's not and there is an absolute speed, not zero, the minimal speed possible as one might have suspected intuitively, but the speed of light which is a maximal speed. However, not all equations in physics are such, for example the equations in GR are notoriously non-linear, furthermore they are a system of partial differential equations. Difference equations are not the same as differential equations, as the former relies on a discrete change and the latter on an infinitesimal change, but there are analogous techniques in solving such equations.
{ "pile_set_name": "StackExchange" }
Q: Is this operation $*$ binary on $\mathbb{R}$? Consider the operation $*$ on the set of reals $\mathbb{R}$ defined as follows: $a*b=c$, where $c$ is the smallest real number greater than both $a$ and $b$. My question: Is the operation $*$ binary on $\mathbb{R}$? My confusion: For an operation $*$ to be binary on set $S$, the closure property must be satisfied. I know that the result $a*b=c$ surely belongs to $\mathbb{R}$ but can we say that the operation is well-defined for any pair $(a,b)$ as giving such $c\in\mathbb{R}$ explicitly is not possible? Thanks. A: A binary operation on a set $S$ is simply a function $f : S\times S\to S$. You need to check that $(a,b)\mapsto a\ast b$ is well-defined (i.e., actually a function whose codomain is $\Bbb R$). The ``smallest real number greater than a given real number" is a problematic concept: there is no smallest real number greater than a given number! For example, consider $0$. What is the smallest real number greater than $0$? It would have to be the smallest positive number. But suppose there was one, and call it $\epsilon$. Then $0 < \epsilon/2 < \epsilon$, so $\epsilon/2$ is a smaller positive number than $\epsilon$, contradicting our assumption that $\epsilon$ was the smallest! A small modification of your argument shows that $a\ast b$ is not a well-defined real number (that is, no real number exists satisfying the defining property of $a\ast b$), so that $\ast$ is not a binary operation on $\Bbb R$.
{ "pile_set_name": "StackExchange" }
Q: jquery load content immediately and then update every 10 seconds I just got this little script working, but there is some problem. I want that content updated every 10 seconds, but when site loaded it takes 10 seconds before content shows up, then updating works. So how I can get that working so it loads content immediately and then start refreshing every 10 seconds. Thank you. hr = new Date().getHours(); for (var i=0; i < data.length; i++) { if (hr >= data[i][0] && hr <= data[i][1]) { $("#someContent").html(data[i][2]); break; } } A: First of all create a function that updates the content: function updateContent() { $("#someContent").html(data[i][2]); } Then create an init function: function init() { updateContent(); setInterval(updateContent, 10000) } Call the init function once when ready: init(); Explanation: You need to seperate the "logic" from the "wiring". This means you split the code that does stuff from code that calls stuff. After you've done this. you can write additional wiring (calls) to the same logic, this keeps your code DRY. Note: The solution above is only safe if the updateContent() function is sync. This means: if it affecting the DOM directly. If it's going to load AJAX it is unsafe to use setInterval() as the server might need more time to answer than is provided by the interval. If you deal with asynchronous code you want to reschedule after completion. A quick and dirty example: function updateContent() { someFunctionReturningAPromise() .then(() => setTimeout(updateContent), 10000) .catch(e => console.log(e)); } updateContent()
{ "pile_set_name": "StackExchange" }
Q: Algorithm to add sum of every possible xor-sum sub-array I participated in one algorithmic competition. I got stuck in one problem, I am asking the same here. Problem Statement XOR-sum of a sub-array is to XOR all the numbers of that sub-array. An array is given to you, you have to add all possible such XOR-sub-array. Example Input Array :- 1 2 Output :- 6 Explanation F(1, 1) = A[1] = 1, F(2, 2) = A[2] = 2 and F(1, 2) = A[1] XOR A[2] = 1 XOR 2 = 3. Hence the answer is 1 + 2 + 3 = 6. I found an $O(N^2)$ solution, but it was too inefficient one and wasn't accepted in the competition. I saw the best solution of this problem on Code Chef. But in this code, I didn't understand below module, please help me to understand that. for (int i=0, p=1; i<30; i++, p<<=1) { int c=0; for (int j=0; j<=N; j++) { if (A[j]&p) c++; } ret+=(long long)c*(N-c+1)*p; } In pseudocode: Set $r = 0$ For $i$ from $0$ to $29$, let $p = 2^i$. Set $c=0$ Iterate over the array $A$. For each element $A[j]$: If $A[j] \mathbin\& p \ne 0$ then increment $c$. ($\&$ is bitwise and.) Add $c \times (N-c+1) \times p$ to $r$ A: After the first couple of lines the array $A$ contains the XOR of every prefix of the input numbers in binary. So a $1$ bit at position $k$ in $A[j]$ tells us that there are an odd number of input numbers in the range $0...j$ with $1$ at their position $k= \log p$. For every $i,j$ s.t. $i \leq j$, if the $k$th bit of $A[i-1]$ is $1$ and the same bit in $A[j]$ is $0$ then there are an odd number of $1$s at bit-position $k$ of the input numbers in the range $i...j$. The same conclusion would be true if the $k$th bit was $0$ for $A[i-1]$ and $1$ for $A[j]$. Please observe that these are the only two situations where the number of ones at position $k$ is odd in the range $i...j$. Therefore the number of pairs $(A^k[i-1],A^k[j])=(0,1)$ or $(1,0)$ is equal to the number of ranges in the input such that their XOR at position $k$ is $1$. Every such range contributes $p=2^k$ to the total sum. In that code, $c$ is the number of ones and $(N-c)$ is the number of zeros at position $k = \log p$. The "$+1$" is to count for the ranges of length one and a $1$ in their $k$th position.
{ "pile_set_name": "StackExchange" }
Q: Jquery Scroll to bottom in Firefox AND Chrome function run_battle() { if(battlenow.length>0) { var div = document.getElementById('show_battle'); $("#show_battle").animate({ scrollTop: $("#show_battle").prop("scrollHeight") - $('#show_battle').height() }, 100); var attempt = battlenow.shift(); div.innerHTML += attempt; $("#show_battle").animate({ scrollTop: $("#show_battle").prop("scrollHeight") - $('#show_battle').height() }, 100); setTimeout("run_battle()",800); } } This is what I have so far. It works great in firefox. Yet in Chrome, it doesn't work at all. I'm using Jquery 1.7.1, So that's why I'm using .prop instead of .attr. The battlenow array is like this. battlenow.push('Alan hit Joe<br><br>'); battlenow.push('Joe fainted<br><br>Battle Over'); If that helps any. Thank you. A: Here's the code that I use that works in all browsers to scroll to a particular element. This code scrolls the minimal amount to get the element on screen, you might want something different. Note the check for webkit browsers: (function($) { $.fn.scrollMinimal = function() { var cTop = this.offset().top; var cHeight = this.outerHeight(true); var windowTop = $(window).scrollTop(); var visibleHeight = $(window).height(); if (cTop < windowTop) { $(jQuery.browser.webkit ? "body": "html") .animate({'scrollTop': cTop}, 'slow', 'swing'); } else if (cTop + cHeight > windowTop + visibleHeight) { $(jQuery.browser.webkit ? "body": "html") .animate({'scrollTop': cTop - visibleHeight + cHeight}, 'slow', 'swing'); } }; }(jQuery)); Called like: $('#actions').scrollMinimal();
{ "pile_set_name": "StackExchange" }
Q: Should you submit player score and authenticate often? I'm writing my first game. Every time the game is saved, I have it authenticate the local player and submit a highscore. Should I be authenticating and submitting scores often, or only when the score has changed? Will GameCenter block incoming connections if I do this too many times? A: You should only authenticate right when the app is opened. You should submit the score at the end of each game. For games that have a story, submit a score at the end of each level / section. Games stay authenticated: After authenticating their account on a device, that player remains connected on that device, even when the player switches to other applications or reboots the device. A player only disconnects from Game Center only by launching the Game Center application and explicitly signing out. Source: Apple Doc
{ "pile_set_name": "StackExchange" }
Q: Комбинатор on и каррированая функция fst Наткнулся на следующие выражение, с использованием комбинатора on: foo :: Num c => c -> c -> c foo = curry fst `on` (^2) Вопрос: Как работает данная конструкция? В частности мне непонятно следующие: Почему мы используем fst в качестве каррированной функции, если на вход мы подаем два аргумента которые идут после комбинатора on Как данные аргументы возводятся в квадрат, если они становятся каррированными только перед комбинатором on Что происходит в данной конструкции на самом деле, исходя из конкретного примера использования A: Почему мы используем fst в качестве каррированной функции, если на вход мы подаем два аргумента которые идут после комбинатора on fst не каррированная функция, мы как раз делаем ее каррированной с помощью комбинатора curry т.е. была функция fst fst :: (a, b) -> a а получаем новую функцию curry fst curry fst :: a -> b -> a Как данные аргументы возводятся в квадрат, если они становятся каррированными только перед комбинатором on Из сигнатуры полученной функции видно, что теперь это функция от двух аргументов, которая возвращает результат совпадающий по типу с первым аргументом, т.е. она вполне может принять возведенные в квадрат числа и вернуть число. Что происходит в данной конструкции на самом деле, исходя из конкретного примера использования. Выполним подстановку согласно определению on foo = curry fst `on` (^2) => foo = \x y -> (curry fst) ((^2) x) ((^2) y) => foo x y = curry fst (x^2) (y^2) Теперь подстановку curry fst curry fst => \a b -> fst (a, b) => \a b -> a Теперь подставляем полученную функцию в предыдущее определение foo x y = (\a b -> a) (x^2) (y^2) => foo x y = x^2 Итого, foo принимает два аргумента, второй игнорирует, а первый возводит в квадрат. Даже если проигнорировать тот факт, что on здесь совершенно не нужна, curry fst не нужна тем более, ее можно было бы заменить на эквивалентную ей const. foo = const `on` (^2)
{ "pile_set_name": "StackExchange" }
Q: File to Zip Exists C# I have numerous large files that I have to transfer. My TX program keeps hanging when I zip everything into one large file. So I want to zip the individual files. namespace WindowsFormsApplication1 { public partial class UncompressFolder : Form { public UncompressFolder() { InitializeComponent(); } void ProcessFiles(string path, string choice="U") { string[] files; files = Directory.GetFiles(path); foreach (string file in files) { // Process each file if (!file.ToUpper().Contains("zip")) { FileInfo fi = new FileInfo(file); string startPath = fi.DirectoryName; string zipPath = fi.DirectoryName + @"\zipped\"; string zipFile = zipPath + fi.Name+".zip"; string extractPath = startPath + @"\unzipped"; if (!Directory.Exists(extractPath)) { Directory.CreateDirectory(extractPath); } if (choice == "Z") { // zip it --> always give me the "File's In Use Error" // option I had tried but did not work --> Directory.CreateDirectory(zipPath); System.IO.Compression.ZipFile.CreateFromDirectory(startPath, zipFile); } else {// unzip -- works fine System.IO.Compression.ZipFile.ExtractToDirectory(file, extractPath); } } } } private void button1_Click(object sender, EventArgs e) { this.folderBrowserDialog1.ShowDialog(); ProcessFiles(folderBrowserDialog1.SelectedPath, "U"); } private void button2_Click(object sender, EventArgs e) { this.folderBrowserDialog1.ShowDialog(); ProcessFiles(folderBrowserDialog1.SelectedPath,"Z"); } } } I saw the posts about people zipping into their existing files and I don't think that's what I'm doing. I would be so happy and appreciative if someone could help me figure this out. A: Zipping a file into the same folder that you are zipping is what probably causes this exception to be thrown. Try to change your code logics so that the zipped file is created outside the target folder: // Exception ZipFile.CreateFromDirectory(@"C:\MyPath", @"C:\MyPath\MyArchive.zip"); // No Exception ZipFile.CreateFromDirectory(@"C:\MyPath", @"C:\MyOtherPath\MyArchive.zip"); Avoid doing bizarre tricks like copying the target folder into another location and passing that one to the CreateFromDirectory method. This will slow things down a lot and will occupy unnecessary space on your drive, especially if your folder contains big files. On a side note, never change your directory paths manually by concatenating strings. This can, sometimes, produce weird results. Use Path.Combine instead, which can internally handle everything much better: String zipPath = Path.Combine(fi.DirectoryName, @"\zipped\"); Also, refactor your code so that the necessary paths are computed only when a specific action is required. This will slightly increase the process performance: FileInfo fi = new FileInfo(file); string startPath = fi.DirectoryName; if (choice == "Z") { string zipPath = fi.DirectoryName + @"\zipped\"; string zipFile = zipPath + fi.Name+".zip"; Directory.CreateDirectory(zipPath); ZipFile.CreateFromDirectory(startPath, zipFile); } else { string extractPath = startPath + @"\unzipped"; if (!Directory.Exists(extractPath)) Directory.CreateDirectory(extractPath); ZipFile.ExtractToDirectory(file, extractPath); }
{ "pile_set_name": "StackExchange" }
Q: Any additional settings for express-session secure cookies on Heroku besides trust proxy? I'm trying to set-up secure cookies on an express app running on Heroku. I've tried both app.set('trust proxy', true) and setting proxy: true in the session config. In both cases, the cookie fails to be modified once deployed to Heroku using an SSL cert. Other things: I never implemented resave = true in the session since mongo-connect has a touch method. userSessionStore = new MongoDBStore({ url: 'foo', collection: 'bar', touchAfter: 3600, }); const sess = { secret: process.env.SESSION_SECRET, name: 'name', resave: false, saveUninitialized: true, cookie: { maxAge: 1 * 24 * 60 * 60 * 1000 }, store: userSessionStore }; if (process.env.NODE_ENV === 'production') { sess.cookie = { secure: true, httpOnly: true, domain: baseURL }; } app.use(session(sess)); if (process.env.NODE_ENV === 'production') { app.set('trust proxy', true); } A: This problem was due to the baseURL variable not matching both the host and the subdomain on heroku. Since heroku hosts many apps at foo.herokuapp.com, matching the subdomain is required.
{ "pile_set_name": "StackExchange" }
Q: Convert string array into field names using javascript Was wondering if there was a nice way in javascript, preferably es6, to convert a string array that was a result from a map function into field names in a dynamically created object. For example, say I get the following result from my map function: ["checkbox1Value", "checkbox4Value"] I would like to do this with those results: const answer = { //some other fields dynamically created checkbox1Value: true, checkbox4Value: true } Anyway of doing this via es6? A: You could use computed property names and map the single objects and assign it to a single object. var array = ["checkbox1Value", "checkbox4Value"], object = Object.assign(...array.map(k => ({ [k]: true }))); console.log(object); A: let result = ["checkbox1Value", "checkbox4Value"]; const answer = result.reduce((acc, cur) => {acc[cur] = true; return acc}, {}); console.log(answer); .reduce is really just a fancy for loop (an "ES6 way of doing it"). If you are shooting for maximum efficiency, use a regular for loop instead. A: const myArray = ["checkbox1Value", "checkbox4Value"]; let obj = {}; myArray.forEach(val => { obj[val] = true; }) console.log(obj);
{ "pile_set_name": "StackExchange" }
Q: Get All IDs Of A Post Type Using WP_Query I am trying to get a list of a custom post type's IDs using WP_Query, but it is returning undesired result, which is a memory leak and stuck browser. Here is the code I use: $the_query = new WP_Query("post_type=post&posts_per_page=-1&field=ids"); if ($the_query->have_posts()) { while ($the_query->have_posts()){ echo get_the_ID(); } } It makes my browser infinitely trying to load the page. May be somebody know what's wrong with the code above.. A: I know you want solution "using WP_Query", but why not use get_posts() for this? $posts_ids = get_posts('post_type=post&posts_per_page=-1&fields=ids'); // $posts_ids is now an array of IDs echo implode(',', $posts_ids); // prints: 123, 124, 125, 126, ... // or foreach( $posts_ids as $id ) { echo $id; } A: You are missing the the_post() function call in the loop. Just add $the_query->the_post(); in your loop. Apart from that, your loop should work EDIT You should also not forget to reset your postdata after the query is done
{ "pile_set_name": "StackExchange" }
Q: fork() and pipes() in c What is fork and what is pipe? Any scenarios explaining why their use is necessary will be appreciated. What are the differences between fork and pipe in C? Can we use them in C++? I need to know this is because I want to implement a program in C++ which can access live video input, convert its format and write it to a file. What would be the best approach for this? I have used x264 for this. So far I have implemented the part of conversion on a file format. Now I have to implement it on a live stream. Is it a good idea to use pipes? Capture video in another process and feed it to the other? A: A pipe is a mechanism for interprocess communication. Data written to the pipe by one process can be read by another process. The primitive for creating a pipe is the pipe function. This creates both the reading and writing ends of the pipe. It is not very useful for a single process to use a pipe to talk to itself. In typical use, a process creates a pipe just before it forks one or more child processes. The pipe is then used for communication either between the parent or child processes, or between two sibling processes. A familiar example of this kind of communication can be seen in all operating system shells. When you type a command at the shell, it will spawn the executable represented by that command with a call to fork. A pipe is opened to the new child process and its output is read and printed by the shell. This page has a full example of the fork and pipe functions. For your convenience, the code is reproduced below: #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> /* Read characters from the pipe and echo them to stdout. */ void read_from_pipe (int file) { FILE *stream; int c; stream = fdopen (file, "r"); while ((c = fgetc (stream)) != EOF) putchar (c); fclose (stream); } /* Write some random text to the pipe. */ void write_to_pipe (int file) { FILE *stream; stream = fdopen (file, "w"); fprintf (stream, "hello, world!\n"); fprintf (stream, "goodbye, world!\n"); fclose (stream); } int main (void) { pid_t pid; int mypipe[2]; /* Create the pipe. */ if (pipe (mypipe)) { fprintf (stderr, "Pipe failed.\n"); return EXIT_FAILURE; } /* Create the child process. */ pid = fork (); if (pid == (pid_t) 0) { /* This is the child process. Close other end first. */ close (mypipe[1]); read_from_pipe (mypipe[0]); return EXIT_SUCCESS; } else if (pid < (pid_t) 0) { /* The fork failed. */ fprintf (stderr, "Fork failed.\n"); return EXIT_FAILURE; } else { /* This is the parent process. Close other end first. */ close (mypipe[0]); write_to_pipe (mypipe[1]); return EXIT_SUCCESS; } } Just like other C functions you can use both fork and pipe in C++. A: there are stdin and stdout for common input and output. A common style is like this: input->process->output But with pipe, it becomes: input->process1->(tmp_output)->(tmp-input)->process2->output pipe is the function that returns the two temporary tmp-input and tmp-output, i.e. fd[0] and fd[1].
{ "pile_set_name": "StackExchange" }
Q: Convert SVGSVGElement to String I've searched for an answer all over but I can't find a way to convert a SVGSVGElement to a string. I'm using Chrome(22). I apologize if this has been answered before but I wasn't able to find it (here or on Google). I have an SVG (XML) image embedded in an HTML page and am manipulating the SVG with Javascript (adding/removing shapes, etc). My goal is to take the modified SVG XML image in memory and save it to a file (by posting to a php form). The post and php form are working, but the issue I'm currently having is that I can't get the string representation of the modified SVG image. I've posted a simplified page below where I'm just trying to get the raw XML from the loaded SVG and paste it into the textarea. If you test the html below you'll see that the textarea just contains the string: "[object SVGSVGElement]". I can access each element in the SVG with Javascript and manipulate the elements and attributes, but I can't seem to just get the whole thing into a string. I've tried JQuery and JQuery SVG but wasn't able to get it working. console.log() is able to show the svg/xml, but it's not a string, so I can't seem to store/send it. Any assistance is greatly appreciated! I would even settle for a way to convert any SVG*Element object to a string as I can use the .childNodes[x] property to traverse through all of them, but these are still objects and I can't seem to just get the raw XML. Test.html: <html> <head> <script type='text/javascript' src='js/jquery.js'></script> <script> function startup() { svgOutput = document.getElementById("svgCanvas").getSVGDocument().documentElement; console.log(svgOutput); document.getElementById("output").value = svgOutput; } </script> </head> <body style="margin: 0px;" onload="startup()"> <textarea id="output"></textarea><br/> <embed src="svg1.svg" id="svgCanvas" width="75%" height="75%" type="image/svg+xml" codebase="http://www.adobe.com/svg/viewer/install" ></embed> </body> </html> svg1.svg: <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events"> <image id="svgBackground" x="0px" y="0px" width="100%" height="100%" preserveAspectRatio="none" xlink:href="bg1.jpg"/> <g id="1"> <text id="shape" x="30" y="30" font-size="16pt" fill="black" visibility="hidden">circle</text> <text id="elementName" x="30" y="30" font-size="16pt" fill="black" visibility="hidden">Element 1</text> <circle id="circle" cx="12%" cy="34%" r="15" opacity="1" fill="grey" stroke="darkgrey" stroke-width="5px"/> </g> <g id="2"> <text id="shape" x="30" y="30" font-size="16pt" fill="black" visibility="hidden">circle</text> <text id="elementName" x="30" y="30" font-size="16pt" fill="black" visibility="hidden">Element 2</text> <circle id="circle" cx="21%" cy="63%" r="15" opacity="1" fill="grey" stroke="darkgrey" stroke-width="5px"/> </g> </svg> A: You can use XMLSerializer to convert elements to a string. var s = new XMLSerializer(); var str = s.serializeToString(documentElement); A: SVG is a DOM element, so you can simply use outerHTML attribute of SVG Elements to get the serialized HTML. var stringData = document.getElementById('my-svg').outerHTML;
{ "pile_set_name": "StackExchange" }
Q: Initialize gitolite repository in existing folder I'm fairly new to Git and Gitolite, but yesterday I managed to get it up and running. The thing is, I have a folder with many projects (let's call it /projects) and I'm trying to migrate them to Git. I symlinked Gitolites /repositories folder to this /projects folder, so now every new repo is created in the /projects folder. It works allright. But now I want to make a repo for every project (subfolder) in the /projects folder. If I initialize a new repo in Gitolite (let's call it /myproject), it creates a new folder called myproject.git instead of using the old myproject folder with the files I'm already working with. So, how can I turn all the individual projects folders into Git repositories, using Gitolite? I'd like not to manually download and append all those files. A: That is the way Gitolite works: it manages bare repositories (the xxx.git folders), not working tree (directories full of files, like projects/myprojects/). So: don't symlink repositories to /projects: both are for very different purpose. You can inititiate and import each project directly in their own directory (/projects/myproject/.git), and then import it to Gitolite, following "how to configure a migrated git repository in gitolite". Pierre De LESPINAY mentions in the comments the official documentation: "appendix 1: bringing existing repos into gitolite" Move the repos to $HOME/repositories. Make sure that: They are all bare repos. All the repo names end in ".git". All the files and directories are owned and writable by the gitolite hosting user (especially true if you copied them as root). Run gitolite setup. If you forget this step, you can also forget about write access control! back on your workstation: If the repos are normal repos, add them to conf/gitolite.conf in your clone of the admin repo, then commit and push the change. If the repos are wildcard repos that already match some repo regex in the conf file, you need to manually create the gl-creator file, like so: echo username > ~/repositories/path/to/repo.git/gl-creator
{ "pile_set_name": "StackExchange" }
Q: Strange delay for touch events in UIView I am working on an OpenGL application for the iPhone... My app has only 2 views: An OpenGL view and, as a subview for the OpenGL view, a view with the sole purpose of catching touch events... The problem is that after about 10-15 minutes of keeping the app running on the device, I get a big (0.5s-1s) delay between every touchesMoved:withEvent: call The animation runs smooth, and CPU usage is also not the problem (10% at most) I have no idea what might be causing this A: That is weird, eh. This happens ON THE DEVICE right? When you are not running tethered from XCode? I would guess you are using up a lot of memory, either a leak or just in some way using up more and more memory as time goes on. Are you familiar with the various memory tools to watch what is going on? Also, what about this: launch a few other large apps that remain in the background. Run your app until the problem exhibits. Then, kill the other apps. Does the problem suddenly go away? If so that would suggest you're low on memory. Would be interested to hear.
{ "pile_set_name": "StackExchange" }
Q: Change the access point subnetmask I have one main router, one DSL modem and one access point TP-Link TL-WR-845N. My DSL modem is connected to phone port and my main router is connected to the DSL modem and my access point is connected to the main router. All the connections between my routers and modems are with LAN cable. I want to change my access point subnetmask to 255.255.0.0 but when I try to do it it gives me 5003 that told me The LAN IP should not be on the same subnet with the WAN IP. please input another one. But I changed my main router subnetmask to 255.0.0.0 Can someone help me to change these settings? My access point info: Working mode: Dynamic IP address WAN IP address: 192.168.0.100 LAN IP addresses: 192.168.2.1 Subnetmask: 255.255.255.0 My main router info: Lan IP address: 192.168.0.1 Subnetmask: 255.255.255.0 Working mode: wireless router mode WAN IP address: 192.268.1.2 My DSL router info: LAN IP address: 192.168.1.1 Subnetmask: 255.0.0.0 The main problem that I have is my printer is connected to my main router with 192.168.0.102 address and when I connect my mobile phone to access point I can't access my printer via AirPrint but when I connect my mobile phone to main router I can access my printer via AirPrint! So I think that I should change my access point subnetmask to 255.255.0.0 that the AirPrint could find my printer! A: Your TP-Link TL-WR-845N is a router (http://www.tp-link.in/products/details/cat-9_TL-WR845N.html) so you are causing a double-NAT problem for your LAN. The easiest solution for you will be to: Plan your network - draw it on a piece of paper and identify each important device and write what IP/subnet it has/should have. Set a DHCP scope within your main router - so you don't set any device to have a static IP address within any DHCP scope (such as an AP). Suggest: 192.168.0.10-192.168.0.100 - giving your 90 available DHCP clients. Plug out the WAN port - It is important to not use the WAN socket for any secondary router-go-AP devices because this causes double-NATing and prevents the devices on each separate network from communicating. Log on to your TP-Link TL-WR-845N web interface Configure it to have a LAN IP outside your normal DHCP pool scope (e.g. 192.168.0.2). Configure it to have a subnet that matches your main router (255.255.255.0) Turn off the AP's DHCP server (this is crucial). Connect the AP to your main router using one of it's LAN ports (not the WAN port) You should be able to connect a [wifi] client and it'll get an IP (and correct subnet) from your main router's DHCP server and you should be able to see and print to your printer. Done.
{ "pile_set_name": "StackExchange" }
Q: Row replacement operation not changing the determinant Can someone prove why a row replacement operation does not change the determinant of a matrix? **row replacement operation being adding one row to another or something of that sort A: One way to think about it, using the property: $\det(AB)=\det(A)\det(B)$: Adding a multiple of one row to another is equivalent to left multiplication by an elementary matrix. Let $B$ be some $n\times n$ matrix, $A$ be an $n\times n$ elementary matrix which acts as an operator which adds $k$ copies of row $i$ to row $j$. So applying that same row operation to $B$ will result in the matrix $AB$. Then without a loss of generality, $A$ has the form: $$\begin{bmatrix}1 & & & & & \\ & \ddots & & & & & \\ & & 1 & & & & \\ & & & \ddots & & & \\ & & k & & 1 & & \\ & & & & & \ddots & \\ & & & & & & 1\end{bmatrix}$$ where $a_{ji}=k$. The determinant of a triangular matrix is the product of the diagonal. $A$ has a unit diagonal, so $\det(A)=1$. Therefore, $$\det(AB)=\det(A)\det(B)=1\det(B)=\det(B).$$ A: If you have a matrix $\mathrm A \in \mathbb{R}^{n \times n}$ and you replace its $i$-th row by a linear combination of the $n$ rows of $\mathrm A$, this corresponds to left-multiplying $\mathrm A$ by $$\mathrm E := \mathrm I_n - \mathrm{e}_i \mathrm{e}_i^T + \mathrm{e}_i \mathrm{c}^T = \mathrm I_n + \mathrm{e}_i (\mathrm{c} - \mathrm{e}_i)^T$$ where $\mathrm{e}_i$ is a vector with $n-1$ zeros and with a one on the $i$-th entry, and the entries of $\mathrm{c}$ are the coefficients of the linear combination. Thus, the determinant of the new matrix is $$\det (\mathrm E \mathrm A) = \det(\mathrm E) \cdot \det (\mathrm A)$$ Using Sylvester's determinant identity, $$\det (\mathrm E) = \det (\mathrm I_n + \mathrm{e}_i (\mathrm{c} - \mathrm{e}_i)^T) = \det (1 + (\mathrm{c} - \mathrm{e}_i)^T \mathrm{e}_i) = 1 + (c_i - 1) = c_i$$ Hence, replacing a row by a linear combination of rows does change the determinant if the coefficient that multiplies the row being replaced is not $1$. For example, replacing a row by the same row multiplied by $2$ then doubles the determinant.
{ "pile_set_name": "StackExchange" }
Q: Custom 500 error page in Hybris I have to redirect the 500 error page you see in the picture on an empty page in Hybris. How can do this? A: Have you tried enabling error-page in web.xml ? <error-page> <exception-type>java.lang.Exception</exception-type> <location>/WEB-INF/pages/error/serverError.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/WEB-INF/pages/error/serverError.jsp</location> </error-page>
{ "pile_set_name": "StackExchange" }
Q: How to iterate and find from map, pair>? This is my map: map<pair<string, int>, pair<string, Array> > matchMap; This is the function: void Schedule::studentSchedule() { string s, c; cout << "Enter the student and course name to create schedule" << endl; cin >> s >> c; list<string>::iterator studentLoc; map<pair<string, int>, pair<string, Array> >::iterator courseL; studentLoc = find(getStudentList().begin(), getStudentList().end(), s); courseL = find(getMatchMap().begin(), getMatchMap().end(), c); if (studentLoc != getStudentList().end() && courseL != getMatchMap().end()) {} } I can not find the string here because I am getting an error: courseL = find(getMatchMap().begin(),getMatchMap().end(),c); How can I find the element which I want ? This is the error: In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:71, from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61, from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4: C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_equals_val<_Value>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Value = const std::__cxx11::basic_string<char>]': C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_equals_val<const std::__cxx11::basic_string<char> >]' C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_equals_val<const std::__cxx11::basic_string<char> >]' C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3905:28: required from '_IIter std::find(_IIter, _IIter, const _Tp&) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Tp = std::__cxx11::basic_string<char>]' C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:24:63: required from here C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:241:17: error: no match for 'operator==' (operand types are 'std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > >' and 'const std::__cxx11::basic_string<char>') { return *__it == _M_value; } ~~~~~~^~~~~~~~~~~ In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:67, from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61, from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4: C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_iterator.h:860:5: note: candidate: 'template<class _IteratorL, class _IteratorR, class _Container> bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator<_IteratorL, _Container>&, const __gnu_cxx::__normal_iterator<_IteratorR, _Container>&)' operator==(const __normal_iterator<_IteratorL, _Container>& __lhs, A: Have you tried to use find? courseL = matchMap.find(pair<string, int>{c, 1}); The key to your map is of type pair<string, int>, so to use find you need to provide a valid key.
{ "pile_set_name": "StackExchange" }
Q: Unqualified name lookup: Why local declaration hides declaration from using directive Consider this code: namespace A { int i = 24; } namespace B { using namespace A; int i = 11; int k = i; // finds B::i, no ambiguity } And basic.lookup.unqual.2: §6.4.1 Unqualified name lookup [basic.lookup.unqual] The declarations from the namespace nominated by a using-directive become visible in a namespace enclosing the using-directive; see [namespace.udir]. For the purpose of the unqualified name lookup rules described in [basic.lookup.unqual], the declarations from the namespace nominated by the using-directive are considered members of that enclosing namespace. For me the standard says pretty clear that for the purpose of unqualified name lookup (the i in int k = i) the declaration of i from A is considered member of B so i should be ambiguous in int k = i, however both gcc and clang compile and resolve i to the local B::i. I have searched the standard (basic.scope.hiding and namespace.udir) and did not find an exception or a rule to contradict the above one. I have found that for qualified name lookup, but not for unqualified name lookup. Why is i unambiguous? A: The key is 10.3.4/2 "During unqualified name lookup, the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace." The nominated namespace is A, the using directive is in B, and the smallest (in fact only) common namespace is the global namespace. Thus i appears as if declared in the global namespace, and is hidden by B::i.
{ "pile_set_name": "StackExchange" }
Q: Superfish - File not found: sites/all/libraries/superfish/sfsmallscreen.js I just downloaded and enabled the latest (dev) version of superfish module, as well as the library... I am getting the following error: File not found: sites/all/libraries/superfish/sfsmallscreen.js Should I remove this line from the libraries path: sites/all/libraries/superfish/sftouchscreen.js Or just download a previous (recommended) version of superfish? A: Download the Superfish library and extract it to sites/all/libraries/superfish (so that the superfish.js will be located at http://example.com/sites/all/libraries/superfish/superfish.js) A: use command for drush user: "drush superfish-plugin" then it create new libraries folder and contains superfish library.then add your libraries file in config file.it works.
{ "pile_set_name": "StackExchange" }
Q: SSRS Printer pop up not showing in Internet Explorer 11 I cannot get SSRS base report print pop up in Internet Explorer 11. But it successfully worked with ie 8.. Server os is 2012, SQL version is 2008 R2, client Pc is windows 10. A: In some older versions of SSRS you have to put IE in compatibility mode to get some of the features to work. You have two options, you can fix it client side or server side. Client Side: Fix the SSRS Compatibility Issue in IE 11 This has to be applied to all users' browsers. Open the IE11 browser Press F12 – which would open a developer tool at the bottom of the browser Click "Emulation" tab Change the "Document mode" to "Edge" Try to access the report. You should now be able to access the report in IE11 without any issues. Server Side: Fix the SSRS Compatibility Issue at the Server Level This change will reflect in all users' browsers, you don't need to make any changes for the client browser settings. It is recommended to take a backup of the reportviewer.aspx file located at \Microsoft SQL Server\MSRS12.MSSQLSERVER\Reporting Services\ReportServer\Pages. Open the reportviewer.aspx file located in \Microsoft SQL Server\MSRS12.MSSQLSERVER\Reporting Services\ReportServer\Pages in notepad. Change the meta tag from meta http-equiv="X-UA-Compatible" content="IE=5" to meta http-equiv="X-UA-Compatible" content="IE=Edge" Save the file and try to access the report in IE11, you should now be able to access the report without any issues. This exact issue is described in this blog post.
{ "pile_set_name": "StackExchange" }
Q: Boolean expression: What's the inverse of a 'let myString = aPossibleString'? I'm trying to do the equivalent in Objective-C: if (causeStr != nil) { ... } I would get a compiler error if do this: if !(let myString = causeStr) { } So I'm left with this: if let myString = causeStr { } else { // ... do something } Is there a more-elegant way to do this? A: Yes, there's a more elegant way, and coincidentally it's the same as in obj-c: if myString == nil { ... } Note: Your 1st snippet of code should be: if (causeStr == nil) { ... } otherwise it means I misunderstood your question...
{ "pile_set_name": "StackExchange" }
Q: Start java with Java EE or Spring I already know the syntax of Java, my next educational goal is to learn a framework (or library), some friends advice me to go for Spring some other advice me to go for Java EE 6. I wonder which is better to start learning and practicing with. Would you please help me to choose a book or manual to enter the practical world of Java? A: I think it's better to start learning basic Java EE concepts (as you said you are php developer and you just started to learn java syntax). Because to understand Java EE frameworks you need to know what is Servlet and JSP and other basic concepts like filters or servlet container (like tomcat). After you developed some simple Java EE application with Servlet and JSP you would be ready to learn more advanced concepts and frameworks (like Spring). My advice is start to read Head First Servlet & JSP or any online resources that learns you these concepts. Good luck.
{ "pile_set_name": "StackExchange" }
Q: Portable audio player I want to buy an audio player that satisfies these conditions: MicroSD slot which can read 64GB card or has device memory of at least this size Hardware buttons which I can use without unlocking the display No lags when navigating between songs At least average audio quality FLAC support Price limit: 500$ Can you recommend me any device which meets these conditions? EDIT: I don't want to hack anything - replacing firmware etc. EDIT 2: Price limit raised. I've tried these two devices so far FiiO X1 2nd gen Astell & Kern JR Sleek Silver 64GB Both had the same problem: when I transferred about 3000 songs to the player (to a card in case of FiiO) and played them, it had huge lags between songs (after pushing the next button). A: SanDisk Sansa Clip+ $50 for 4gb and $100 for 8gb anyway both have SDcard slot. MicroSD card slot. Robust file support. FM radio and recording. Rechargeable battery lasts up to 15 hours. MP3, WMA, Secure WMA, FLAC. I tried it before the sound quality really good. Edit: The maximum Memory size MicroSD card is 16GB according to this article Or Sandisk Fuze The Fuze and all SanDisk's players (Fuze+ included) will work well with cards up to 32GB. You can hack the newer 64GB cards (which are a new format, SDXC or exFAT) by re-formatting to FAT32 and use them too, but it isn't officially sanctioned by SanDisk (or any manufacturer). Resource link You can change the firmware from here to unlock the number of files + to run 64GB external SDcard A: Finally, I've found the right device. It's Fiio X5 3gen. It handles playing files in big folders (10000+ files) without any delay even if the random mode is on. It has all features I wanted, sometimes it's even more than I expected (two card slots). The only disadvantage I've found so far is that the device is quite big (it's a lot thicker than average phone)
{ "pile_set_name": "StackExchange" }
Q: Going back to old position in lex During my lex processing, I need to go back in the lex input file, to process the same input several times with different local settings. However, just doing fseek(yyin, old_pos, SEEK_SET); does not work, since the input data are buffered by lex. How can I (portably) deal with this? I tried to add a YY_FLUSH_BUFFER after the fseek(), but it didn't help, since the old file position was incorrect (it was set to the point after filling the buffer, not to the point where I evaluate the token). A: The combination of YY_FLUSH_BUFFER() and yyseek(yyin, position, SEEK_SET) (in either order, but I would do the YY_FLUSH_BUFFER() first) will certainly cause the next token to be scanned starting at position. The problem is figuring out the correct value of position. It is relatively simple to track the character offset (but see the disclaimer below if you require a portable scanner which could run on non-Posix platforms such as Windows): %{ long scan_position = 0; %} %% [[:space:]]* scan_position += yyleng; "some pattern" { scan_position += yyleng; ... } Since it's a bit tedious to insert scan_position += yyleng; into every rule, you can use flex's helpful YY_USER_ACTION macro hook: this macro is expanded at the beginning of every action (even empty actions). So you could write the above more simply: %{ long scan_position = 0; #define YY_USER_ACTION scan_position += yyleng; %} %% [[:space:]]* "some pattern" { ... } One caveat: This will not work if you use any of the flex actions which adjust token length or otherwise alter the normal scanning procedure. That includes at least yyless, yymore, REJECT, unput and input. If you use any of the first three, you need to reset scan_position -= yyleng; (that needs to go just before the invocation of yyless, yymore or REJECT. For input and unput, you need to increment / decrement scan_position to account for the character read outside of the scanning process. Disclaimer: Tracking positions like that assumes that there is a one-to-one correspondence between bytes read from an input stream and raw bytes in the underlying file system. For Posix systems, this is guaranteed to be the case: fread(3) and read(2) will read the same bytes and the b open mode flag has no effect. In general, though, there is no reliable way of tracking file position. You could open the stream in binary mode and deal with the system's idiosyncratic line endings yourself (this will work on Windows but there is no portable way of establishing what the line ending sequence is, so it is not portable either). But on other non-Posix systems, it is possible that a binary read produces a completely different result (for example, the underlying file might use fixed-length records so that each line is padded (with some system-specific padding character) to make it the correct length. That's why the C standard prohibits the use of computed offset values: For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET. (§7.21.9.2 "The fseek function", paragraph 4). There is no way to turn buffering off in flex -- or any version of lex that I know of -- because correctly handling fallback depends on being able to buffer. (Fallback happens when the scan has proceeded beyond the end of a token, because the token matches the prefix of a longer token which happens not to be present.) I think the only portable solution would be to copy the input stream token by token into your own buffer (or temporary file) and then use yy_push_buffer_state and yy_scan_buffer (if you're using a buffer) to insert that buffer into the input stream. That solution would look a lot like the tracking code above, except that YY_USER_ACTION would append the tokens read to your own string buffer or temporary file. (You would want to make that conditional on a flag so that it only happens in the segment of the file you want to rescan.) If you have nested repeats, you could track the position in your own buffer/file in order to be able to return to it.
{ "pile_set_name": "StackExchange" }
Q: swift 2 get integer value from unwrap variable let g : String? = self.EKOMemberShipss[0].SUB_TYP_Price let x:Int? = Int(g!) self.valuePla.text = "\(x)" Result g String? " Optional(50)" x Int? nil None I just want to get x = 50 A: Check both the SUB_TYP_Price and the ability to be converted to Int On success the optional is unwrapped respectively if let g = self.EKOMemberShipss[0].SUB_TYP_Price, x = Int(g) { self.valuePla.text = "\(x)" } Edit: According the screenshotSUB_TYP_Price is already String? so the downcast is not needed.
{ "pile_set_name": "StackExchange" }
Q: Problems creating required field validator dynamically I am storing settings in the database for which objects need to be validated along with there properties. To do this I am hoping to create them dynamically from a class which is called on page load. I am able to create the validators from the class with what I believe are the correct minimum properties but afterwards they clearly don't work and when I do a submit I get no error message in the summary. I have submitted my last attempt below which shows me trying to add them into a placeholder. //In the class. public class ObjectSetup { static public DataTable GetPageValidators(int PageID) { DataTable dt = new DataTable(); using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["GetConnector"].ConnectionString)) { DataSet ds = new DataSet(); SqlCommand sqlComm = new SqlCommand("PL_Objects_Validation_Get", conn); sqlComm.Parameters.AddWithValue("@PageID", PageID); sqlComm.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = sqlComm; da.Fill(ds); dt = ds.Tables[0]; } foreach (DataRow R in dt.Rows) { Guid ControlID = new Guid(); RequiredFieldValidator RFV = new RequiredFieldValidator(); RFV.ID = ControlID.ToString(); RFV.ControlToValidate = R[0].ToString(); RFV.ErrorMessage = R[1].ToString(); RFV.Display = ValidatorDisplay.None; RFV.ForeColor = System.Drawing.Color.Red; RFV.Enabled = true; RFV.Visible = true; PlaceHolder PlaceHolder1 = new PlaceHolder(); PlaceHolder1.Controls.Add(RFV); } return dt; } //In the pages code-behind. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataTable dtValidators = ObjectSetup.GetPageValidators(3); } } A: As @Sam stated, you should create your controls in the Page_Init event. You also need to re-create dynamic controls every time on postbacks, so try the following: protected void Page_Init(Object sender, EventArgs e) { DataTable dtValidators = ObjectSetup.GetPageValidators(3); } Also are you actually adding your dynamic placeholder (PlaceHolder1) to the page anywhere? One last point, if you use new Guid() your controls will all have the same ID, use Guid.NewGuid() instead, or you can not set the Control.ID property at all.
{ "pile_set_name": "StackExchange" }
Q: Genetic Algorithm Results Presentation I have data of an experiment that I ran using the genetic algorithm and am trying to present it in a paper. What is a good/ classic way of representing the results of the genetic algorithm. I was thinking of doing a scatterplot representing the maximum fit individuals by their generations. Is this a good representation of the results? A: When you gauge the performance of a Genetic Algorithm (or any other stochastic algorithm), you run it multiple times and then aggregate the results to eliminate the effect of some runs being "lucky" or "unlucky". Then it's about presenting such aggregated results. For a single run (among many of those), you are typically concerned with the best individual in the fitness only (unless you are analyzing the population dynamics which I think you don't), because that's the output of the algorithm at any given time during its runtime. When you have such best individuals for each run, you present the results. Typical visual representation of a GA is an "evolution plot" or "progress plot" (I personally use the first term and other researchers use it too) and it looks something like this (from my master thesis): I know, it's a little bit messy. However, the solid lines are the medians of the aggregated runs. That means that at X evaluations, for each algorithm the solid line is at the median fitness of all the best individuals from each of the run of the particular algorithm (mean is also used sometimes, but it is not resistant to outliers). The error bars stretch from 1st to 3rd quartile, in my case (standard deviation is also used sometimes, but then the error bars are symmetrical about the solid line and do not show the distribution as much as the quantiles). If you are not interested in the progress of the evolution but rather in the final results, you can use e.g. boxplot to properly show the distribution of final values of the algorithms. It looks something like this (again, from my master thesis, corresponds to the evolution plot above): This one was created in MATLAB. There is an online tool for creating boxplots: http://boxplot.bio.ed.ac.uk If you have only a single algorithm to present, you can also combine the evolution plot with boxplot - an evolution plot made of boxplots! You just put a boxplot every N-th evaluation (N depends on the figure size to be readable). The quartile error bars and median solid line is a sort-of a boxplot, in a (distorted) way. The last option is to present the results textually (or in a table) supported by some statistical tests. For comparison of two algorithms (the final values), you can use e.g. the Mann-Whitney U-test. Comparing more than two algorithms becomes tricky and you need to find a friendly statistician to help you out :).
{ "pile_set_name": "StackExchange" }
Q: How can I execute an external program without php script interrupt For example: //test.php #! /usr/local/php/bin/php <?php exec('nohup ./loop.php > loop.out'); echo 'I am a superman!'; //loop.php #! /usr/local/php/bin/php <?php $count = 0; while (true) { echo "Loop count:{$count}\n"; $count++; } When I run ./test.php I can not get the output 'I am a superman!', as you know loop.php is an endless loop, test.php is interrupted by loop.php, so how can I get the output? Any help is appreciated. A: There is a bunch of ways you can achieve this: Running background process using &: exec('nohup ./loop.php > loop.out 2>&1 &'); Using pcntl_fork and running your process from child: $pid = pcntl_fork(); switch ($pid){ case -1: die('Fork failed'); break; case 0: exec('nohup ./loop.php > loop.out'); exit(); default: break; } echo "I'm not really a superman, just a parent process'; There is more ways to do this, just lurk into PHP documentation and questions in php here...
{ "pile_set_name": "StackExchange" }
Q: Solving a non-linear integro-differential equation I am trying to solve the following equation $$ f^2(x) - g^2(x) = \alpha\int_0^x f(u) (x-u)du $$ For $\alpha=0$ we get $f=g$. I would like to see how the solution moves away from $g$ when I increase the value of $\alpha$. In order to derive a closed-form solution I first tried Laplace transforms since $$ \mathcal{L} \left\{ \int_0^\cdot f(u) (\cdot-u)du \right\}(s) = \frac{1}{s^2} \mathcal{L}\left\{ f\right\}(s) =: \frac{F(s)}{s^2} $$ The problem is that I did not found any general formula for the Laplace transform of $f^2$. Is there any ways to relate the Laplace transform of $f^2$ to $F$ (or a polynomial/series in $F$) ? If not is there any other method to solve this problem analytically ? A: With the function $g(x)$ supposed to be given, on can express the unknown function $f(x)$ as a series of the parameter $\alpha$. This allows to see how $f(x)$ moves away from $g(x)$ when the value of $\alpha$ incresses : $f(x) = g(x)+\alpha g_1(x) + \alpha^2 g_2(x)+...$ The analytical form of $g_1(x)$ and $g_2(x)$ are shown below. One could continue with the same method to compute the next terms, but this will be more and more arduous. On a purely formal way, one can derive the recurrence formula giving $g_k(x)$ from the preceeding terms $g(x), g_1(x), g_2(x), ..., g_{k-1}(x)$ But this involves multiple integrals which will be arduous to compute, depending on the given $g(x)$. This is also without considering the question of the convergence of so complicated series.
{ "pile_set_name": "StackExchange" }
Q: using php and regex to change @import to php include? Very very long story short, I am basically trying to use a regex (or maybe even string replace) to change @import url('narf.css'); to <?php include('narf.css'); ?> So far, I have come up with this, BUT it does not close the PHP tag.... $var = str_replace('@import url', '<?php include', $var); Aside from this, I am kinda stuck. I am HORRIBLE at regex syntax and everything I have tried or tried to look up has lead me down a dead end road. Any help would be MORE than appreciated. A: $var = preg_replace('/@import url\(([^)]+)\);/', '<?php include $1; ?>', $var); To break it down: @import url\( - literally matches @import url(. ([^)]+) - Captures everything inside the parenthesis into the first back-reference. \); - literally matches );. If you have some whitespace somewhere in there, you's have to account for that too...
{ "pile_set_name": "StackExchange" }
Q: Is there fully-automatic fill-paragraph-mode for code comments? I'm looking for a minor mode to keep paragraphs filled at all times while typing (similar to what aggressive-indent-mode does for indentation). It also needs to be smart enough to only fill comments (and maybe strings depending on the language). Some things that I've tried are: auto-fill-mode automatically fills while you are typing new paragraphs but doesn't refill when you edit paragraphs. refill-mode does constantly refill paragraphs but it tries to wrap code into paragraphs as well as comments. I tried adding fill-paragraph to the after-change-functions hook but it screws up undo and plenty of other things (this is probably all fixable but would take some effort). Any better ideas? A: I came up with a minimal way of implementing this functionality: just bind space bar to also call (fill-paragraph)! (defun fill-then-insert-space () (interactive) (fill-paragraph) (insert " ")) (global-set-key (kbd "SPC") #'fill-then-insert-space) There are a couple of caveat's that I've stumbled across so far: elisp-mode (possibly others) does some fancy code filling when you call fill-paragraph, this may or may not be what you want. Can probably be fixed with by testing if point is in a comment or docstring but I'm not sure how to do that. You sometimes can't easily enter multiple spaces (because the fill-paragraph kills any trailing spaces). Since the space-bar now acts like just-one-space it's probably ok to replace that binding with (insert " "). I made a minor-mode containing this functionality, it's available on github or in the melpa package aggressive-fill-paragraph.
{ "pile_set_name": "StackExchange" }
Q: $f$ an isometry from a hilbert space $H$ to itself such that $f(0)=0$ then $f$ linear. This question was on an exam and I am not sure how to answer it. I mostly tried writing zero in different ways and tried lots of algebra to get something out. I also tried to use the fact that $H$ is a hilbert space but couldn't get anywhere. Any suggestions? If $H$ is a hilbert space and $f:H\to H$ is an isometry ($\|f(x)-f(y)\|=\|x-y\|$) such that $f(0)=0$, then $f$ is linear. A: In fact, in any strictly convex real Banach space $B$ an isometry $f$ with $f(0)=0$ is linear. Note that for any $a, b \in B$, $(a+b)/2$ is the only $v \in B$ with $\|a-v\| = \|v-b\|=\|a-b\|/2$. So $f((a+b)/2)$ is the only $v$ with $\|f(a) - v\| = \|v - f(b)\| = |f(a) - f(b)|/2$, and thus $f((a+b)/2) = (f(a) + f(b))/2$. From this it's not hard to show that $f(ra) = r f(a)$ for any rational $r$, and by continuity this is true for any scalar, and then $$f(sa + tb) = f((2sa + 2tb)/2) = (f(2sa)+f(2sb))/2 = s f(a) + t f(b)$$ A: You can prove that $\langle f(x),f(y) \rangle = \langle x,y \rangle$ for any real Hilbert Space by deriving the following expressions for $\|f(x) - f(y)\|^2$ and $\|x-y\|^2$: \begin{align*} \|f(x)-f(y)\|^2 &= \langle f(x) - f(y), f(x) - f(y)\rangle \\ &= \|f(x)\|^2 - 2\langle f(x),f(y)\rangle + \|f(y)\|^2\\ \end{align*} and \begin{align*} \|x-y\|^2=\langle x-y,x-y\rangle &= \|x\|^2 - 2\langle x,y\rangle + \|y\|^2 \end{align*} Since $\|f(x)-f(0)\| = \|x - 0\|$, and $f(0) = 0$, you know $\|f(x)\| = \|x\|$. Therefore, after setting the two expressions equal to each other, the correct terms match up to give preservation of the inner product, as claimed. Then you can use this to show that $$\|f(x+y) - f(x) - f(y)\|^2 = \langle f(x+y) - f(x)-f(y), f(x+y)-f(x)-f(y)\rangle = 0,$$ therefore proving that $f$ is additive. The same should work for $f(\lambda x)$. Showing the preservation of the inner product for a complex Hilbert space won't work using the same trick; the farthest I've gotten with it is showing that the real part of $\langle f(x),f(y)\rangle$ is equal to the real part of $\langle x,y\rangle$. All of the proofs I've seen that show equality in the complex case assume that $f$ is already linear and just use the polarization identity $$\langle x,y\rangle = \frac{1}{4}(\|x+y\|^2 - \|x-y\|^2 +i\|x+iy\|^2 -i\|x-iy\|^2)$$ on $\langle f(x),f(y)\rangle$. I suspect it is true in the complex case, I just haven't found out why. A: There is similar general result by Mazur and Ulam. In fact every bijective isometry $f:E\to F$ between normed spaces $E$ and $F$ is the composition of isometric linear operator $T:E\to F$ and shift on vector $f(0)$.
{ "pile_set_name": "StackExchange" }
Q: how to use gpio pins in nRF52840 development kit? The GPIO pins are like P0.00, P0.01, P1.01, P1.02 and so on. I didnt know how to use this. I would like to know, how to use the GPIO pins in nRF52840 for simple LED and push button circuit? It would be really helpful. A: The GPIO pins on the nRF52840 development kits are mapped as follows:- P0.00 - P0.31 : SIO0 - SIO31 P1.00 - P1.15 : SIO32 - SIO47 In other words, P0.01 is SIO1, P1.01 is SIO33, P1.02 is SIO34 and so on. The macro mapping can be found in Nordic_SDK/modules/nrfx/hal/nrf_gpio.h (Line 71).
{ "pile_set_name": "StackExchange" }
Q: Name of a special matrix I have a matrix which is kind of symmetrical with the other diagonal, i.e., something like $$A = \left[ \begin{array}{c c c c} a & b & c & d \\ e & f & g & c \\ h & i & f & b \\ j & h & e & a \end{array} \right]$$ Does this matrix have a special name in literature? What are it's properties? And a matrix that is symmetrical by both diagonals $$A = \left[ \begin{array}{c c c c} a & b & c & d \\ b & e & f & c \\ c & f & e & b \\ d & c & b & a \end{array} \right]$$ What's the name of it? Any interesting properties? A: (Turning the comments into an answer) Yes, the first matrix is persymmetric, and the second is bisymmetric.
{ "pile_set_name": "StackExchange" }
Q: SQL expression to scala I'm trying to rewrite a spark SQL expression in scala. spark.sql( s""" |SELECT | *, | CASE | WHEN status = 'ACCEPTED' THEN 1 | WHEN status = 'REJECTED' THEN 2 | WHEN status = 'PENDING' THEN 3 | ELSE 0 | END AS updated_state |FROM fact_recruiter_inmail_proposal |""".stripMargin ) This is my rewrite which throws a syntax error table.withColumn( "updated_state", .when(col("status") === "ACCEPTED", 1) .when(col("status") === "REJECTED", 2) .when(col("status") === "PENDING", 3) .otherwise(0) ) What am I doing wrong? A: Drop the dot before the first when: table.withColumn( "updated_state", when(col("status") === "ACCEPTED", 1) .when(col("status") === "REJECTED", 2) .when(col("status") === "PENDING", 3) .otherwise(0) ) This compiles
{ "pile_set_name": "StackExchange" }
Q: rails searchlogic plugin search in multiple columns I have a form to a search engine. I want to search for the searchterm in all fields of a specific model. I'm using the searchlogic plugin. It gives me a lot of new finders but i cannot do a OR between two fields. for example: How can i do a "SELECT * from my_table WHERE field1 LIKE '%xpto%' OR field2 LIKE '%xpto%' ? Specially in the form parameter that will be passed to my controller, if you know searchlogic you know what i'm speaking about, i'm trying to pass something like: field1_or_field2_like("xpto") but it dont works. Any idea? A: Based on this post from the plugin's author there is not intended to be support for this, although as Jongsma indicated you can implement it with your own named_scope.
{ "pile_set_name": "StackExchange" }
Q: Issue in @selector of Objective-C [mobile_Obj AuthenticateMobileServer:self action:@selector(Handler:) AccountNO:@"123" UserName:@"Sun" Password:@"123***"]; In the above method call , can we have two threads running simultaneously?? One thread running: AuthenticateMobileServer method Second thread runnig: Handler method Please let me knw is it possible or not, if so how to create thread for each of them? Thank You. A: Maybe you could create a method that to be called by @selector which creates the threads instead. Take a look at the NSOperation docs, as well as this tutorial.
{ "pile_set_name": "StackExchange" }
Q: UITabBar Size increased on iPhone X I am facing the issue that my tabbar is stretched on the new iPhone X. I am using a regular UITabBarController with no further styling for height etc. I want it to be like the iPhone 8 picture so placed against the bottom of the view and not stretched like it is at this moment. Is this easy? iPhone X iPhone 8 A: its because of the lack of home button on the X its done like that to give the User some room for the upward swipe gesture to get to the home page (if you were able to lower it more you'd be screwing over your iPhone X users)
{ "pile_set_name": "StackExchange" }
Q: jQuery don't call ASP.NET WebMethod I know there are plenty of questions like this one but I just can't solve my problem with those answers. I have basic page and on it: <body> <form id="form1" runat="server"> <div id="Result"> <asp:ScriptManager ID="ScriptManager1" EnableScriptGlobalization="true" EnableScriptLocalization="true" EnablePageMethods="true" EnablePartialRendering="true" runat="server" /> <script type="text/javascript"> $(document).ready(function () { $("#txtSearch").bind("change", search); }); function test() { alert("asdadadaads"); } function search() { $.ajax({ type: "POST", url: "~/Search.aspx/GetRegion", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { alert(msg.d) } }); } </script> <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox> </div> </form> I am able to call test function and it shows alert. Also in Firebug I see that search() function is also called but I can't step into my code behind WebMethod. WebMethod is like this: [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static void GetRegion() { SearchService.Service1 client = new Service1(); } I am getting crazy with this so thanks if you can help :) A: Remove ~ from url in $.ajax request. No need of ScriptManager// Won't matter even if you not changed Put search() function outside the (document).ready() function.// Won't matter even if you didn't change Change $("#txtSearch").bind("change", search); => $("#txtSearch").change(search);// Won't matter even if you didn't change Also make sure same id txtSearch rendered (may not render same if master pages are used). You can use <%:txtSeacrh.ClientId%> to get clientId in HTML markup. There is no need to use bind function if txtSearch exists in the DOM while the page loads.Also jQuery prefers to use on function instead. $( "#txtSearch" ).on( "change", search); jsFiddle
{ "pile_set_name": "StackExchange" }
Q: How to attach objects to ends of bezier curves? How would one go about attaching instances of a mesh to the ends of a bunch of bezier curves? Basically, I am modelling some cables, which should be terminated by ring terminals, and I'm looking for a low maintenance solution for adding these. Ideally, I only want one mesh defining the terminals' appearance, and these should align automatically with the direction of the vertices they're attached to. A: With the add-on Animation Nodes you can create copys of objects and automatically place them at specific locations. The node setup shown below loops over all objects in a group with the cables in it. The first loop “Get Splines” returns a list of all splines in the objects. For every spline an instance of the desired object is created. The second loop “Place Objects” evaluates each spline at the end (Parameter 1.00) and calculates location, tangent and normal. Parameter 0.0 would evaluate the spline at the start but then you will also have to mirror the tangent vector. The tangent and normal are used to calculate the rotation angle for the object. You might want to replace the Guide with a random vector instead of using the spline's normal so that the terminals' orientation is more realistic.
{ "pile_set_name": "StackExchange" }