text
stringlengths
64
89.7k
meta
dict
Q: How to create an application specific effective exception Hierarchy I am a newbie with designing stuff though I have some experience as a developer. My question is related to the statement - "It is always a good practice to design the exception hierarchy at the start of the project" After much of reading and researching the definition of a checked and unchecked exception is well clear. However, I still wonder what is the best practices in designing the exception hierarchy for an application. Is the below approach right? Create your own application specific top level exceptions MyAppRuntimeException MyAppCheckedException Subclass MyAppCheckedException with all your business exceptions where you want the caller to take a specific exception. For example TryWithADifferentInputException - This is not the right input, correct it TryAlternateServiceException - This service is not available, but you can choose another service that will do the job Similarly subclass your runtime exception which spiral up and are captured only by something like the spring exception resolver and display appropriate message on front end. Another thing that bugs me is how to come up with most of the exception scenarios at the start of the project. What should be the strategy to do so. A: Hello hailMurphy and welcome to SO! IMO, it is not necessary to design an entire exception hierarchy for every app. Rather, you should only introduce new exceptions if none of the existing stock ones adequately address the error you're encountering. Your TryWithADifferentInputException for instance could probably easily be replaced with an IllegalArgumentException or possibly IllegalStateException. I find that 99% of the time, I'm well able to do with the existing ones. As for knowing which exceptions to expect before you actually start writing code: The complex parts of your program, such as class structure, algorithms, protocols, etc. should be thought out and documented before you actually fire up your IDE and get hands-on. UML is a common way to do this. During that process, as you're pen-and-papering your algorithm or protocol, try looking at border cases (what happens when this value becomes zero? What if this argument is null? Will my algorithm still work? Good! Will it break? Exception!) and playing devil's advocate (what if the network connection breaks down halfway through my protocol? Can I recover from this, or does it leave me in an unrecoverable state?) you should be able to see exception scenarios. If you do find yourself in need for creating custom exceptions, derive them directly from whichever ancestor seems most fit - Error, IllegalStateException, RuntimeException, IOException, etc. Don't create your own complete hierarchy unless there is a scenario where you need to only catch all of your own exceptions and none of the stock ones. Honestly, though, I can't see a scenario where that might be useful. On a more general note, exceptions should be a "last resort" to deal with errors that can't be otherwise recovered from, and not as a form of control flow. If you're expecting something to happen naturally as part of your application (such as bad user input), you should generally not deal with it through exceptions. If you have an algorithm that breaks unrecoverably in a lot of cases, it can be an indication that you haven't found the right one yet.
{ "pile_set_name": "StackExchange" }
Q: How to configure IIS authentication password? I am developing a C# / ASP.NET web application in VS 2008 on a 32-bit XP. I created a Login.aspx file for the user to enter a user name and password initially before seeing any data. This functionality works now from VS. I added users and roles by entering ASP.NET Configuration. However, after publishing to IIS 6.0, the password does not work there. How do I configure Directory Security in IIS for the same user name and password to work? A: If you're using forms authentication the user information is probably on the database. This is not connected with IIS so I can think in 2 options 1) You're pointing to a different database that doesn't have the user you're logging in with. 2) An exception was threw related to the authentication process and on the exception handling code you're showing the message "invalid password". EDIT Here you have a complete example about how to use forms authentication with membershipprovider http://msdn.microsoft.com/en-us/library/ms998347.aspx and here some more links about forms authentication http://msdn.microsoft.com/en-us/library/xdt4thhy.aspx http://msdn.microsoft.com/en-us/library/aa480476.aspx
{ "pile_set_name": "StackExchange" }
Q: Problems calculating 8-point FFT of an 8-point sine wave by hand I need a small help for my assignment, which is to solve the 8-point FFT without using Matlab or C. Preliminary information: 8-point sine wave: [0, 0.7071, 1, 0.7071, 0, -0.7071, -1, -0.7071] 8-point complex exponential: [1, 0.7071-j0.7071, -j, -0.7071-j0.7071] So here's the attempts I did: 1.) Bit reversing the 8-point sine wave and rearrange it to: [0, 0, 1, -1, 0.7071, -0.7071, 0.7071, -0.7071] 2.) Perform each butterfly calculation: First pass: [0, 0, 0, 2, 0, 1.414, 0, 1.414] Second pass: [0, -j2, 0, 2, 0, 1.414-j1.414, 0, 1.414+j1.414] And the last: [0, -j4, 0, 2-j2, 0, 2.828, 0, 2.828-j2.828] However, the last pass which is the result does not match with the actual FFT result in Matlab: [0, -j4, 0, 0, 0, 0, 0, j4] Any steps I might have missed? Opinions and pointers are greatly appreciated. Thanks. A: I will start from very beginning. So having signal: $ x[n] = [0; \ 0.7071; \ 1; \ 0.7071; \ 0; \ -0.7071; \ -1; \ -0.7071] $ and given exponent: $ w[n] = [1; \ 0.7071 - 0.7071i; \ -i; \ -0.7071 - 0.7071i;\ -1;\ -0.7071 + 0.7071i; \ i; \ 0.7071 + 0.7071i]$. First we need to inverse the bits and rearrange our signal. For 8 samples we will obtain following change in indices: $ [0;\ 1;\ 2;\ 3;\ 4;\ 5;\ 6;\ 7] \Rightarrow [0;\ 4;\ 2;\ 6;\ 1;\ 5;\ 3;\ 7] $, thus our signal becomes: $ x[n] = [0; \ 0; \ 1; \ -1; \ 0.7071; \ -0.7071; \ 0.7071; \ -0.7071] $. Now according to following schematic: We calculate "butterflies" in following manner: Where: $ W_{N}^{k} = e^{\dfrac{-2\pi i k}{N}} $ (rotating vector on our complex plane with step angle of $2 \pi/N $ ) Starting from a first butterfly in first stage ($x[0]$ and $x[4]$ as the inputs) we have following: $ A = 0, B = 0, W_8^0=w[0]=1$, giving output: $ [0; 0] $, next butterfly: $ A = 1, B = -1, W_8^0=w[0]=1$, giving output: $ [0; 2] $, next butterfly: $ A = 0.7071, B = -0.7071, W_8^0=w[0]=1$, giving output: $ [0; 1.4142] $, next butterfly is the same with output: $ [0; 1.4142] $. So now, after first pass our vector is as follows (same to the one obtained by Peter Griffin): $x'[n]=[0; \ 0; \ 0; \ 2; \ 0; \ 1.4142; \ 0; \ 1.4142] $ At second stage, first butterfly consists of samples: $x'[0]$ and $x'[2] $, where $ W_8^0=1 $. We can therefore calculate the output as: $[0+1\cdot 0; \ 0-1\cdot 0] = [0; \ 0] $. These are outputs $x''[0]$ and $x''[2]$ of the second stage. Next butterfly is given by inputs $x'[1]$ and $x'[3] $, where $ W_8^2=w[2]=-i $. We calculate output $x''[1]$, $x''[3]$ as: $[0-i\cdot 2; \ 0-(-i)\cdot 2] = [-2i; \ 2i] $ Two following butterflies are calculated in the same manner: $[0+1\cdot 0; \ 0-1\cdot 0] = [0; \ 0] \Rightarrow x''[4]$, $x''[6]$ $[1.4142-i\cdot 1.4142; \ 1.4142-(-i)\cdot 1.4142] = [1.4142-1.4142i; \ 1.4142+1.4142 i] \Rightarrow x''[4], \ x''[6]$ So our vector after second stage is following: $x''[n] = [0; \ -2i; \ 0; \ 2i; \ 0; \ 1.4142-1.4142i; \ 0; \ 1.4142+1.4142i] $ - you've made a mistake here. Finally, we calculate results for third stage. By looking at the main schematic, first butterfly consists of samples: $x''[0], x''[4] = [0; 0]$. The $W_N^k$ coefficient is given by $W_8^0=w[0]=1$. Calculating butterfly we obtain: $[0+1\cdot 0; \ 0+(-1)\cdot 0] = [0; \ 0] $ - these are final FFT values $X[0], X[4]$. Moving to next butterfly based on samples $x''[1], x''[5] = [-2i; 1.4142-1.4142i]$ with coefficient $W_8^1=w[1]=0.7071 - 0.7071i$. Result: $[-2i+(0.7071 - 0.7071i)\cdot (1.4142-1.4142i); \ -2i-(0.7071 - 0.7071i)\cdot (1.4142-1.4142i)] = [-4i; \ 0] $ And next butterfly based on samples $x''[2], x''[6] = [0; \ 0]$, with $W_8^2=w[2]=-i$ will give $[0+(-i)0; \ 0-(-i)0] = [0; \ 0] $ And the last butter fly based on samples $x''[3], x''[7] = [2i; \ 1.4142+1.4142i]$, with $W_8^3=w[2]=-0.7071 - 0.7071i$ will result in: $[2i+(-0.7071 - 0.7071i)\cdot (1.4142+1.4142i); \ 2i-(-0.7071 - 0.7071i)\cdot (1.4142+1.4142i)] = [0; \ 4i] $ So our final vector is following: $X[k] = [0; \ -4i; \ 0; \ 0; \ 0; \ 0; \ 0; \ 4i] $ Which means MATLAB is calculating FFT correctly ;) One final remark - always take care about $W_N^k$ factor - look on the schematic and it's pretty obvious. Good luck!
{ "pile_set_name": "StackExchange" }
Q: How to align the top lines of frames? I want to align the top lines of the left and right frames. How to do it? \documentclass[12pt]{book} \usepackage[a4paper,margin=25mm,showframe=true]{geometry} \usepackage{xcolor} \usepackage{accsupp} \newcommand*{\noaccsupp}[1]{\BeginAccSupp{ActualText={}}#1\EndAccSupp{}} \usepackage{showexpl} \lstset { language={[LaTeX]TeX}, alsolanguage={PSTricks}, numbers=left, numbersep=1em, numberstyle=\tiny\color{red}\noaccsupp, frame=single, framesep=\fboxsep, framerule=\fboxrule, rulecolor=\color{red}, xleftmargin=\dimexpr\fboxsep+\fboxrule\relax, xrightmargin=\dimexpr\fboxsep+\fboxrule\relax, breaklines=true, basicstyle=\small\tt, keywordstyle=\color{blue}, %identifierstyle=\color{magenta}, commentstyle=\color[rgb]{0.13,0.54,0.13}, backgroundcolor=\color{yellow!10}, tabsize=2, columns=flexible, explpreset={pos=r}, morekeywords={ graphicspath, includegraphics, }, } \begin{document} \LTXexample How to align the top lines of frames?\\ How to align the top lines of frames? \endLTXexample How to align the top lines of frames? \LTXexample How to align the top lines of frames?\\ How to align the top lines of frames? \endLTXexample \end{document} Note: accsupp only works when this input file is compiled with either xelatex or pdflatex. Compiling it with latex followed by dvips and ps2pdf will not produce a PDF output that allows us not to copy the line numbers. A: A "simple" workaround using TikZ: \documentclass[12pt]{book} \usepackage[a4paper,showframe=true]{geometry} \usepackage{xcolor} \usepackage{tikz} \usepackage{accsupp} \newcommand*{\noaccsupp}[1]{\BeginAccSupp{ActualText={}}#1\EndAccSupp{}} \usepackage{showexpl} \makeatletter \renewcommand*\SX@put@r[3]{% \setlength\@tempdimc{\linewidth-#1-\SX@hsep}% \begin{tikzpicture}[baseline={(expl.north)}] \node[draw=red,anchor=base west,line width=1pt,inner sep=1pt,fill=yellow!10] (expl){\SX@CodeArea{\@tempdimc}{#3}}; \end{tikzpicture}% \hfill% \tikz[baseline={(expl.north)}]\node[inner sep=0pt]% (expl){\SX@ResultArea{#1}{#2}}; } \makeatother \lstset { language={[LaTeX]TeX}, alsolanguage={PSTricks}, numbers=left, numbersep=1em, numberstyle=\tiny\color{red}\noaccsupp, rulecolor=\color{red}, breaklines=true, basicstyle=\small\tt, keywordstyle=\color{blue}, %identifierstyle=\color{magenta}, commentstyle=\color[rgb]{0.13,0.54,0.13}, tabsize=2, columns=flexible, explpreset={pos=r}, morekeywords={ graphicspath, includegraphics, }, } \begin{document} \begin{LTXexample} How to align the top lines of frames?\\ How to align the top lines of frames? \end{LTXexample} How to align the top lines of frames? \begin{LTXexample} How to align the top lines of frames?\\ How to align the top lines of frames? \end{LTXexample} \end{document} A: define after loading package showexpl \makeatletter \renewcommand\SX@CodeArea[2]{% \setlength\@tempdima{#1}% \sbox\@tempboxa{\parbox\@tempdima{#2}}% \@tempdima=\dp\@tempboxa\raisebox{\dimexpr -\baselineskip-\fboxsep-\fboxrule-2pt}{\usebox\@tempboxa} \rlap{\raisebox{-\@tempdima}[0pt][0pt]{\SX@attachfile}}} \makeatother 2pt is the interlineskip A: I'll try to explain where the problem is located, and a possible workaround. Be warned, the workaround is very ugly! The problem is located at different places in the code of showexpl and listings packages (listings is used by showexpl). The way the package works is the following: it outputs the code into a intermediate file, then it uses listings package to input the code and typeset it nicely formatted, with listings options (in your case, with a red frame around). Finally it stores the result of "executing" that code through TeX into a temporal box, and outputs that box too, side to side with the one created by listings. The problem is thus how to align the box created by listings (framed in red) and the one created by latex (framed in black in your example). The package showexpl uses parbox to create both boxes, so apparently it would be enough to insert [t] at the appropiate places, to have "top aligned" parboxes. So the first guess is to add the following in your preamble (after including showexpl package): \makeatletter \renewcommand\SX@CodeArea[2]{% \parbox[t]{#1}{#2} \rlap{\parbox[t]{#1}{\SX@attachfile}}} \renewcommand\SX@ResultArea[2]{% \SX@justification% \parbox[t]{#1}{#2}% } \makeatother However, this alone won't work. Now the two parboxes are "top" aligned, but "top" alignment only means "move the baseline of the parbox to the baseline of the first line of the parbox". The problem is that the left box (red frame) and the right box (black frame) have a different concept of what the "first line" is. We have to insert an empty first line ("null box" or \hbox{}) at the beginning of both parboxes, so that they align properly. In order to insert a \hbox{} at the beginning of the left box, we have to make listings to insert that command before it renders the listing. This can be done using listings basicstyle option: basicstyle=\small\tt\hbox{}, (yucks!) In order to insert a \hbox{} at the beginning of the right box, we have to modify the code in showexpl which builds that box (called \SX@ResBox). Unfortunately that code is deeply buried inside a macro definition (\SX@put@code@result), so we have to rewrite the complete macro (63 lines of code!) in order to change only two lines inside it. So the final, complete, code is: \documentclass[12pt]{book} \usepackage[a4paper,margin=25mm,showframe=true]{geometry} \usepackage{xcolor} \usepackage{accsupp} \newcommand*{\noaccsupp}[1]{\BeginAccSupp{ActualText={}}#1\EndAccSupp{}} \usepackage{showexpl} \makeatletter % Add [t] to the parbox \renewcommand\SX@CodeArea[2]{% \parbox[t]{#1}{#2} \rlap{\parbox[t]{#1}{\SX@attachfile}}} % Add [t] to the parbox \renewcommand\SX@ResultArea[2]{% \SX@justification% \parbox[t]{#1}{#2}% } % Add \hbox{} at the creation of \SX@ResBox, look up the comment \renewcommand*\SX@put@code@result{% \begingroup \expandafter\lstset\expandafter{\SX@explpreset}% \let\lst@float=\relax\let\SX@float=\relax \expandafter\lstset\expandafter{\SX@@explpreset}% \ifx\lst@float\relax\else \let\SX@float=\lst@float\let\lst@float=\relax \g@addto@macro\SX@@explpreset{,float=false}% \edef\@tempa{\noexpand\lst@beginfloat{lstlisting}[\SX@float]}% \expandafter\@tempa \fi \ifx\lst@caption\@empty \lstset{nolol=true}% \fi \if@SX@wide\def\SX@overhang{\marginparwidth+\marginparsep}\fi \trivlist\item\relax \stepcounter{ltxexample}\label{\SX@IDENT}% \SX@defaultWD\SX@width{\SX@width}% \ifdim\SX@width<\z@ \@tempswatrue \def\@tempa{t}% \ifx\@tempa\SX@pos\@tempswafalse\fi \def\@tempa{b}% \ifx\@tempa\SX@pos\@tempswafalse\fi \setlength\@tempdima{\linewidth+\SX@overhang}% \if@tempswa\@tempdima=.5\@tempdima\fi% \edef\SX@width{\the\@tempdima}% \fi \ifx\SX@rframe\@empty \long\def\SX@frame##1{##1}% \else \let\SX@frame\fbox \setlength\@tempdima{\SX@width-2\fboxsep-2\fboxrule}% \edef\SX@width{\the\@tempdima}% \fi \isSX@odd{\def\@tempa{l}}{\def\@tempa{r}}% \makebox[\linewidth][\@tempa]{% \parbox{\linewidth+\SX@overhang}{% \let\@addtofilelist\@gobble \let\lst@ifdisplaystyle=\iftrue \SX@KillAboveCaptionskip\lst@MakeCaption{t}% \lst@belowskip=\z@ \let\SX@MakeCaption\lst@MakeCaption \let\lst@MakeCaption\@gobble \setbox\SX@ResBox\vtop{\hbox{}\hbox{% <---- HERE, modified line \SX@frame{% \@nameuse{\if@SX@varwidth varwidth\else minipage\fi}% \SX@width\relax\SX@resultInput% \@nameuse{end\if@SX@varwidth varwidth\else minipage\fi}}}}% <-- Also here, to close a brace \edef\SX@width{\the\wd\SX@ResBox}% \@ifundefined{SX@put@\SX@pos}% {\@latex@error{Parameter `\SX@pos' undefined}\@ehd}% {\@nameuse{SX@put@\SX@pos}% {\SX@width}{\box\SX@ResBox}{\SX@codeInput}}% \let\lst@MakeCaption\SX@MakeCaption \lst@MakeCaption{b}\SX@KillBelowCaptionskip }% }% \endtrivlist \ifx\SX@float\relax\else\expandafter\lst@endfloat\fi \gdef\SX@@explpreset{}% \endgroup } \makeatother \lstset { language={[LaTeX]TeX}, alsolanguage={PSTricks}, numbers=left, numbersep=1em, numberstyle=\tiny\color{red}\noaccsupp, frame=single, framesep=\fboxsep, framerule=\fboxrule, rulecolor=\color{red}, xleftmargin=\dimexpr\fboxsep+\fboxrule\relax, xrightmargin=\dimexpr\fboxsep+\fboxrule\relax, breaklines=true, basicstyle=\small\tt\hbox{}, % <--- Add \hbox{} here too keywordstyle=\color{blue}, %identifierstyle=\color{magenta}, commentstyle=\color[rgb]{0.13,0.54,0.13}, backgroundcolor=\color{yellow!10}, tabsize=2, columns=flexible, explpreset={pos=r}, morekeywords={ graphicspath, includegraphics, }, } \begin{document} \LTXexample How to align the top lines of frames?\\ How to align the top lines of frames? \endLTXexample How to align the top lines of frames? \LTXexample How to align the top lines of frames?\\ How to align the top lines of frames? \endLTXexample \end{document} Which works as desired
{ "pile_set_name": "StackExchange" }
Q: Can diagonal plus fixed symmetric linear systems be solved in quadratic time after precomputation? Is there an $O(n^3+n^2 k)$ method to solve $k$ linear systems of the form $(D_i + A) x_i = b_i$ where $A$ is a fixed SPD matrix and $D_i$ are positive diagonal matrices? For example, if each $D_i$ is scalar, it suffices to compute the SVD of $A$. However, this breaks down for general $D$ due to lack of commutativity. Update: The answers so far are "no". Does anyone have any interesting intuition as to why? A no answer means that there's no nontrivial way to compress the information between two noncommuting operators. It isn't terribly surprisingly, but it'd be great to understand it better. A: The closest positive answers to your question that I could find is for sparse diagonal perturbations (see below). With that said, I do not know of any algorithms for the general case, though there is a generalization of the technique you mentioned for scalar shifts from SPD matrices to all square matrices: Given any square matrix $A$, there exists a Schur decomposition $A=U T U^H$, where $U$ is unitary and $T$ is upper triangular, and $A+\sigma I = U (T + \sigma I) U^H$ provides a Schur decomposition of $A + \sigma I$. Thus, your precomputation idea extends to all square matrices through the algorithm: Compute $[U,T]=\mathrm{schur}(A)$ in at most $\mathcal{O}(n^3)$ work. Solve each $(A+\sigma I) x = b$ via $x := U (T +\sigma I)^{-1} U^H b$ in $\mathcal{O}(n^2)$ work (the middle inversion is simply back substitution). This line of reasoning reduces to the approach you mentioned when $A$ is SPD since the Schur decomposition reduces to an EVD for normal matrices, and the EVD coincides with the SVD for Hermitian positive-definite matrices. Response to update: Until I have a proof, which I do not, I refuse to claim that the answer is "no". However, I can give some insights as to why it's hard, as well as another subcase where the answer is yes. The essential difficulty is that, even though the update is diagonal, it is still in general full rank, so the primary tool for updating an inverse, the Sherman-Morrison-Woodbury formula, does not appear to help. Even though the scalar shift case is also full rank, it is an extremely special case since it commutes with every matrix, as you mentioned. With that said, if each $D$ was sparse, i.e., they each had $\mathcal{O}(1)$ nonzeros, then the Sherman-Morrison-Woodbury formula yields an $\mathcal{O}(n^2)$ solve with each pair $\{D,b\}$. For example, with a single nonzero at the $j$th diagonal entry, so that $D=\delta e_j e_j^H$: $$ [A^{-1}+\delta e_j e_j^H]^{-1} = A^{-1} - \frac{\delta A^{-1} e_j e_j^H A^{-1}}{1+\delta (e_j^H A^{-1} e_j)}, $$ where $e_j$ is the $j$th standard basis vector. Another update: I should mention that I tried the $A^{-1}$ preconditioner that @GeoffOxberry suggested on a few random SPD $1000 \times 1000$ matrices using PCG and, perhaps not surprisingly, it seems to greatly reduce the number of iterations when $||D||_2/||A||_2$ is small, but not when it is $\mathcal{O}(1)$ or greater. A: If $(D_{i} + A)$ is diagonally dominant for each $i$, then recent work by Koutis, Miller, and Peng (see Koutis' website for work on symmetric diagonally dominant matrices) could be used to solve each system in $\mathcal{O}(n^2 \log(n))$ time (actually $\mathcal{O}(m\log(n))$ time, where $m$ is the maximum number of nonzero entries in $(D_{i} + A)$ over all $i$, so you could take advantage of sparsity as well). Then, the total running time would be $\mathcal{O}(n^2 \log(n) k)$, which is better than the $\mathcal{O}(n^3 k)$ approach of solving each system naïvely using dense linear algebra, but slightly worse than the quadratic run time you're asking for. Significant sparsity in $(D_{i} + A)$ for all $i$ could be exploited by sparse solvers to yield an $\mathcal{O}(n^2 k)$ algorithm, but I'm guessing that if you had significant sparsity, then you would have mentioned it. You could also use $A^{-1}$ as a preconditioner to solve each system using iterative methods, and see how that works out. Response to update: @JackPaulson makes a great point from the standpoint of numerical linear algebra and algorithms. I will focus on computational complexity arguments instead. The computational complexity of the solution of linear systems and the computational complexity of matrix multiplication are essentially equal. (See Algebraic Complexity Theory.) If you could find an algorithm that could compress the information between two non-commuting operators (ignoring the positive semidefinite part) and directly solve the collection of systems you're proposing in quadratic time in $n$, then it's likely that you could use such an algorithm to make inferences about faster matrix multiplication. It's difficult to see how positive semidefinite structure could be used in a dense, direct method for linear systems to decrease its computational complexity. Like @JackPaulson, I'm unwilling to say that the answer is "no" without a proof, but given the connections above, the problem is very difficult and of current research interest. The best you could do from an asymptotic standpoint without leveraging special structure is an improvement on the Coppersmith and Winograd algorithm, yielding a $\mathcal{O}(n^{\alpha}k)$ algorithm, where $\alpha \approx 2.375$. That algorithm would be difficult to code, and would likely be slow for small matrices, because the constant factor preceding the asymptotic estimate is probably huge relative to Gaussian elimination. A: A first order Taylor expansion can be used to improve convergence over simple lagging. Suppose we have a preconditioner (or factors for a direct solve) available for $A+D$, and we want to use it for preconditioning $A$. We can compute $$\begin{align} A^{-1} &= (A+D-D)^{-1} (A+D) (A+D)^{-1} \\ &= [(A+D)^{-1} (A+D-D)]^{-1} (A+D)^{-1} \\ &= [I - (A+D)^{-1} D]^{-1} (A+D)^{-1} \\ &\approx [I + (A+D)^{-1} D] (A+D)^{-1} \end{align}$$ where the Taylor expansion was used to write the last line. Application of this preconditioner requires two solves with $A+D$. It works fairly well when the preconditioner is shifted away from 0 by a similar or larger amount than the operator we are trying to solve with (e.g. $D\gtrsim 0$). If the shift in the preconditioner is smaller ($D \lesssim \min \sigma(A)$), the preconditioned operator becomes indefinite. If the shift in the preconditioner is much larger than in the operator, this method tends to produce a condition number about half that of preconditioning by the lagged operator (in the random tests I ran, it could be better or worse for a specific class of matrices). That factor of 2 in condition number gives a factor of $\sqrt 2$ in iteration count. If the iteration cost is dominated by the solves with $A+D$, then this is not a sufficient factor to justify the first order Taylor expansion. If matrix application is proportionately expensive (e.g. you only have an inexpensive-to-apply preconditioner for $A+D$), then this first order method may make sense.
{ "pile_set_name": "StackExchange" }
Q: get values from table as key value pairs with jquery I have a table: <table class="datatable" id="hosprates"> <caption> hospitalization rates test</caption> <thead> <tr> <th scope="col">Funding Source</th> <th scope="col">Alameda County</th> <th scope="col">California</th> </tr> </thead> <tbody> <tr> <th scope="row">Medi-Cal</th> <td>34.3</td> <td>32.3</td> </tr> <tr> <th scope="row">Private</th> <td>32.2</td> <td>34.2</td> </tr> <tr> <th scope="row">Other</th> <td>22.7</td> <td>21.7</td> </tr> </tbody> </table> i want to retrieve column 1 and column 2 values per row as pairs that end up looking like this [funding,number],[funding,number] i did this so far, but when i alert it, it only shows [object, object]... var myfunding = $('#hosprates tbody tr').each(function(){ var funding = new Object(); funding.name = $('#hosprates tbody tr td:nth-child(1)').map(function() { return $(this).text().match(/\S+/)[0]; }).get(); funding.value= $('#hosprates tbody tr td:nth-child(2)').map(function() { return $(this).text().match(/\S+/)[0]; }).get(); }); alert (myfunding); A: var result = $('#hosprates tbody').children().map(function () { var children = $(this).children(); return { name: children.eq(0).text(), value: children.eq(1).text() }; }).get(); This will build an array in the form: [ { name : "...", value: "..." }, { name : "...", value: "..." }, { name : "...", value: "..." } ] etc To get the name of the first row, use: alert(result[0].name); For the value: alert(result[0].value); Edit: if you want the result EXACTLY as you specify: var result = $('#hosprates tbody').children().map(function () { var children = $(this).children(); return "[" + children.eq(0).text() + "," + children.eq(1).text() + "]" }).get().join(",");
{ "pile_set_name": "StackExchange" }
Q: Porting application defined MBeans from OC4J Applications that use Spring JMX deployed on OC4J have their "Application Defined MBeans" visible through Enterprise Manager. When these applications are ported to Weblogic 12c, can these MBeans be made visible in the Weblogic console, and if so, how? A: There's a pretty good summary here. Like the author of that blog, I am using the WLST solution rather than attempting to extend the Weblogic console. To that I would add: I didn't find it necessary to set -Dcom.sun.management.jmxremote=true I did have to set the property name="registrationBehaviorName" value="REGISTRATION_IGNORE_EXISTING" in my MBean exporter otherwise an InstanceAlreadyExistsException was thrown out of an interceptor when I exercised the app
{ "pile_set_name": "StackExchange" }
Q: how to decide which wildcard to use in java? Where should one use extends, where should one use super, and where is it inappropriate to use a wildcard at all? Is their any principle or rule or it all related to one's own understanding and scope of application. Like currently i need only two numbers to add in list so i will used, public List<Integer> addToNewList(integerList , Integer element){ integerList.add(element); return integerList; } But Later on Scope of my application increase and now it require all numbers, so make it generic for maximum support. ex : public <T extends Number> List<T> addToList(List<? extends T> genericList , T element){ genericList.add(element); return genericList; } In short i just want to know, when should one use these wildcards and when not ? A: I understood the when to use and when not to use and there is one awesome principle i found in one book : The Get and Put Principle: use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don’t use a wildcard when you both get and put. Here is a method that takes a collection of numbers, converts each to a double, and sums them up: public static double sum(Collection<? extends Number> nums) { double s = 0.0; for (Number num : nums) s += num.doubleValue(); return s; } Since this uses extends, all of the following calls are legal: List<Integer>ints = Arrays.asList(1,2,3); assert sum(ints) == 6.0; List<Double>doubles = Arrays.asList(2.78,3.14); assert sum(doubles) == 5.92; List<Number>nums = Arrays.<Number>asList(1,2,2.78,3.14); assert sum(nums) == 8.92; The first two calls would not be legal if extends was not used. EXCEPTION : You cannot put anything into a type declared with an extends wildcard—except for the value null, which belongs to every reference type. Whenever you use the add method, you put values into a structure, so use a super wildcard. Here is a method that takes a collection of numbers and an integer n, and puts the first n integers, starting from zero, into the collection: public static void count(Collection<? super Integer> ints, int n) { for (int i = 0; i < n; i++) ints.add(i); } Since this uses super, all of the following calls are legal: List<Integer>ints = new ArrayList<Integer>(); count(ints, 5); assert ints.toString().equals("[0, 1, 2, 3, 4]"); List<Number>nums = new ArrayList<Number>(); count(nums, 5); nums.add(5.0); assert nums.toString().equals("[0, 1, 2, 3, 4, 5.0]"); List<Object>objs = new ArrayList<Object>(); count(objs, 5); objs.add("five"); assert objs.toString().equals("[0, 1, 2, 3, 4, five]"); The last two calls would not be legal if super was not used. EXCEPTION : you cannot get anything out from a type declared with a super wildcard— except for a value of type Object, which is a super type of every reference type. This principle is also explained in following question Get and Put rule
{ "pile_set_name": "StackExchange" }
Q: How to change color of the drives' used space in Windows 7? The default in Windows 7 is blue and red. How do I change those colors to something like gray and black to match my custom theme? A: Well, it is certainly possible, as the desktop modders on DeviantART have been doing it. I would think that will need to use Resource Hacker (last beta version for x64) or similar resource editor, like XN Resource Editor and open shellstyle.dll. The bitmap that you will need to replace will be in there somewhere.
{ "pile_set_name": "StackExchange" }
Q: Testing Repositories in Entity Framework Hi I'm new to EF but am trying to go by the book and create tests for my repositories. The tests fails here. desiner.cs base(global::System.Configuration.ConfigurationManager.ConnectionStrings["pij_localConnectionString"].ConnectionString, mappingSource) I presume I need to move the connection strings out of the webconfig. What is the normal protocol/method for doing this? A: If you have created a unit test project and start testing from there then you just need to copy your connection string (pij_localConnectionString) to the app.config file of your test project. Basically any connection string data should be exist in the config file of the project that the .Net threads are initiated from by CLR (i.e. your startup project). You don't need to remove it from your web.config by the way.
{ "pile_set_name": "StackExchange" }
Q: Custom ValidationTextBox in Dojo I am new to Dojo programming and trying to create a ValidationTextBox for username input. I would like to have three criteria: 1. users can only input alphanumeric characters and 2. minimum length of a username is 6 character 3. this field is required So far my input looks like: <input name="username" type="text" id="username" class="reqd1" required="true" trim="true" lowercase="true" promptMessage="Username" invalidMessage="Please only enter alphanumeric characters." maxlength="12" regExp="[\w]+" intermediateChanges="false" dojoType="dijit.form.ValidationTextBox" /> I have three questions: 1. how I can check for the the minimum character of the username field? 2. Is there a way to change the invalidMessage programatically? 3. How I can check the length of the username field without using regEx? A: regExp="\w{6,12}" dijit.byId("username").set("invalidMessage", "new message"); I think regExp is the best way in your case
{ "pile_set_name": "StackExchange" }
Q: Frame transfer from one switch to another configured with VLANS Hi, My question is related to the Vlan. And this question would consist of 2 parts. 1)Would Switch 1 know all the devices present in Vlan 2 or Vlan 3, including the ones present in the Switch 2. For ex: Would Vlan 2 of Switch 1 know about Host H and Host F and vice-versa. If not, 2)Say, Im sending data from Host B in Vlan 2 to Host H present in Switch 2 Vlan 2, so if the Switch 1 doesnt have any info in its table, it sends a broadcast and ultimately Host H receives it, if im not wrong. Now, how will Host H send the data back to Host B? Host H will only be aware of the Destination MAC addres, so how does the switch know that the data has to be sent through fa0/4 tagging the frame. As far as my knowledge goes, each vlan will be knowing about only their devices, so using what info does the switch forward it out of the fa0/4. Please help me on this. The concept is pretty confusing. An explanation, with the flow of the data from the beginning starting from Host B to Host H and then finally from Host H to Host B would be helpful. A: First, to have packets move between VLANs, you need a router. Switches maintain MAC address tables, one for each VLAN on the switch. The MAC address table has the interface where a frame with the source MAC address was last seen. It is highly likely that one switch will have the MAC addresses of the hosts on the other switch for a VLAN pointing to the link between the switches because any frames from the hosts on the other switch that find their way to the first switch will have the source MAC addresses placed in the switch MAC address table for that VLAN. If a switch needs to send a frame to a destination MAC address, it first looks for the destination address in the MAC address table (and updates the MAC address table with the source MAC address). It will switch the frame for the destination MAC address to the interface it finds for that MAC address in the MAC address table, or if the destination address doesn't have an entry in the MAC address table, the switch will flood (broadcast is a frame type, so flood is the correct term, even if the action seems to be the same) the frame to all other interfaces than the one where the frame entered. It only takes one frame to put the source MAC address in the table (but every frame will update the table with the source MAC address of the frame), so the table gets built quickly. That is because every time a host uses ARP to discover a destination MAC address, it broadcasts an ARP request that goes to every other switch interface. The switch will see both the ARP request and ARP reply, so it will have the source MAC addresses of each host in its MAC address table with the interfaces on which the source MAC addresses were seen. The entries in a MAC address table will eventually time out if there is no activity for a MAC address. That is to eliminate entries for hosts that have been shut down. Most business-grade switches will let you configure the time out period.
{ "pile_set_name": "StackExchange" }
Q: Removing product attributes from the order email I have 3 attributes assigned to each product (size, color, logo). All of my products are configurable products thus each SKU contains the size, color, and logo along with the actual SKU for the product (they were auto-generated during the creation process). What I would like to show on the order email is just the product name, SKU, Qty, and subtotal and can not figure out how to remove the attributes from being displayed under each product ordered. The issue for my client is typically there are multiple products purchased on each order and when printing the order via email it can get quite long. Below is what is shown today on the email under Item (I used '...' to simulate spaces): Item..............................SKU.....................................Qty.................Subtotal Mens Shirt.....................X123-Blue-Small-Logo1.......1.......................$20.00 Color Blue Size Small Logo Logo1 What I would like to show is only the item name and NOT each attribute underneath. Essentially it would look something like the below (I added '...' to simulate spaces): Item.....................SKU...............................................QTY.................Subtotal Mens Shirt............X123-Blue-Small-Logo1..................1.......................$20.00 Womans Shirt......X456-Blue-Medium-Logo2...............2.......................$30.00 Has anyone ran into this before and know where I can go to 'hide' the attributes from being shown on the order email. I have been to many forums looking at the sales.xml and items.phtml files, however I have not yet found the exact place where the attributes are being called and displayed on the order email. Any assistance would be greatly appreciated. A: it is so simple. Goto app/design/frontend/your Package/your template/template/email/order/items/order/default.phtml hav Here you have find the code <?php if ($this->getItemOptions()): ?> <dl style="margin:0; padding:0;"> <?php foreach ($this->getItemOptions() as $option): ?> <dt><strong><em><?php echo $option['label'] ?></em></strong></dt> <dd style="margin:0; padding:0 0 0 9px;"> <?php echo nl2br($option['value']) ?> </dd> <?php endforeach; ?> </dl> <?php endif; ?> <?php $addInfoBlock = $this->getProductAdditionalInformationBlock(); ?> <?php if ($addInfoBlock) :?> <?php echo $addInfoBlock->setItem($_item)->toHtml(); ?> <?php endif; ?> <?php echo $this->escapeHtml($_item->getDescription()) ?> Just remove it. it will works
{ "pile_set_name": "StackExchange" }
Q: Obout Grid: Hiding an Image on a grid for certain rows only Using the obout grid with the following column: <obg:Column ID="Image" DataField="" HeaderText="" Width="50" runat="server"> <TemplateSettings TemplateId="ImageTemplate" /> </obg:Column> And the following Template: <Templates> <obg:GridTemplate runat="server" ID="ImageTemplate"> <Template> <img src="images/test.png" title="test" /> </Template> </obg:GridTemplate> </Templates> I am trying to hide the image on certain rows programmatically: protected void grd_RowDataBound(object sender, GridRowEventArgs e) { if (testpassed()) { e.Row.Cells[1].Text = ""; // Column 2 is the image } } But it is not hiding the image. How do I hide the image programmatically using an obout grid for certain rows only? Thanks before hand. A: If found the answer in case someone runs into this in the future: protected void grd_RowDataBound(object sender, GridRowEventArgs e) { // Check if this is a DataRow if (e.Row.RowType == GridRowType.DataRow) { // Check if we are hiding the image if (testpassed()) { // Retrieve Image Cell (Column 2 in my case) GridDataControlFieldCell cell = e.Row.Cells[1] as GridDataControlFieldCell; // Retrieve Literal Control with Image Source Html (Found at Level 5) LiteralControl imgTag = cell.Controls[0].Controls[0].Controls[0].Controls[0].Controls[0] as LiteralControl; // Remove Html <img src.. code from Literal Control in order to hide image imgTag.Text = ""; } } }
{ "pile_set_name": "StackExchange" }
Q: Is it good practice to use data API for access cross platform All, Question: Should I have a common data access API between various cross platform applications or keep the data access specific to the UI even though it would result in duplication? Background: I’ve been developing various applications many with sub applications to interact with various pieces of our internal services. I basically have a desktop application that holds all these smaller applications / features and allows them to be used in a Launcher – almost MDI (but not) style and a web application that has various subset applications inside for our mobile devices. We’re getting to the point where many of our applications will have a desktop and mobile version of them and I’m curious about the best way to structure this. Currently I have a large common class library that stores all my data access in the form of an API which basically interacts with an internal DATA CONNECTIONS class inside the common class library alongside various common helper methods. Additional: Primary data access is Entity Framework which requires a NuGet package for each project using the common class although I also have various manual data access methods as well. One of the concerns I have is that my naming scheme is messy I feel like by having the UI structured by “Application Name” and then having duplicate folders in my common classes also structured by the same name. Basically, looks like this: A: What you appear to be missing here is a good story for what happens between your data access layer and your user interface. Should you have a common data access API? Of course. But your UI will not necessarily be getting data directly from your data access layer. Why? Because the data that your UI needs might look different than what you get from your data access layer. Your data access layer is optimized for efficiency; your UI is optimized for display. Let's say you want to display an invoice. Invoices have a rather specific structure. You have an invoice header containing addresses, invoice line items, and a summary block with totals. From the data layer's perspective, this information comes from several different tables. From the UI perspective, it's a single data structure. So you can either have the UI pull all of the necessary information from the data access layer directly, or have some intermediate software layer retrieve the data, assemble the invoice for you and provide a single data structure to the UI directly. The latter approach is more desirable for several reasons, mostly having to do with separation of concerns.
{ "pile_set_name": "StackExchange" }
Q: Ng-table select filtering issue I am trying to filter the ng-table data with select drop down, the issue is select dropdown the values are not populating and ofcos filtering doesn't work, i am using ng-table 2.1.0 version. i tried changing the $scope.names object to hardcoded object i.e., $scope.names=[{title:'Moroni'},{title:'Enos'},{title:'Jacob'}]; then values are populating in select dropdown i am assuming there must be property 'title' for every object, but still filtering doesn't work either, is there anything missing here? plunker Here Any help is much appreciated. A: As I can see from the expression in ngOptions attribute: ng-options="data.id as data.title for data in $selectData" The format of the option should be {id: ..., title: ...}. So I think you can change your angular.forEach block with something like this: var titles = data.map(function(obj) { return obj.title; }); $scope.names = titles.filter(function(title, i) { return titles.indexOf(title) === i; }) .map(function(title) { return {title: title, id: title}; }); This is not the fastest method to generate this array (added this just to illustrate the structure). More performant ways to do this could be found here. Working fiddle.
{ "pile_set_name": "StackExchange" }
Q: Is the Golden Superman canon, and what were his exact powers? In Superman one million, Superman spends 15,000 years, I think, inside the sun. I'm just wondering how powerful he is compared to other characters in the DC universe, and if it's canon. A: Superman Prime (One Million) is arguably one of the most powerful versions of Superman to have ever existed (canon or not). He was so powerful, he was responsible for lending a portion of his fantastic powers to his descendants to utilize across the solar system to protect Human endeavors. As to his connection to DC canon, the character appears in a what was dubbed "a possible future". The Justice Legion came back in time to the canon DC Universe to recruit the Justice League, so his canonical nature is deterministic at best. That possible future was erased with the previous DC Universe, so this version of Superman currently cannot exist under canon. Superman Prime (Kal-El) left Earth after the death of Lois Lane and traveled the Universe for 700 years before returning to Earth. During his travels, he acquired vast abilities and skills from every being he met and gained perfection over all the abilities he received. He left the Earth defended by his descendant who was dubbed "Superman Secundus". It is believed Kal-El broke through the Source Wall during his travels and training and studied under the Source itself, meaning he could have a portion of the Source's power or more, the true extent of abilities he received from the Source are unknown. (The Source is believed to be the originator of metahuman ability in the DC Universe and the center of the power of Jack Kirby's New Gods line of heroes.) The Source Wall, the boundary to the DC Multiverse and believed to be the source of metahuman abilities in the DC Universe. Beings who seek its power and are deemed unworthy become part of the wall adding to its protection. When he returned he forged a covenant with his descendants, he would bestow upon them a small fraction of his power as long as they served for truth and justice. He also gained the abilities of his lineage and magnified them with his own power; ie. the Superman of the 67th Century married the queen of the 5th Dimension, GZNTPLZK, which in turn gave Superman Prime the abilities and powers of a 5th Dimension Imp. (See: Mr. Mxyzptlk) After the covenant he left and returned to his Fortress of Solitude in the center of the Super Sun." Superman Prime's Fortress of Solitude is inside what was now dubbed the Super Sun. All of his descendants draw their power from it and must recharge regularly or lose them after only a few days. Kal-El is the creator of the Superman Dynasty which protected Humanity in his absence. During is absence, the Superman Dynasty added to their powers by adding to their genetic heritage over the centuries. Superman Prime was still more powerful than they were, even after their genetic improvements. In addition to the entire suite of superhuman abilities (super-strength, invulnerability, speed, vision powers, etc) common to the most powerful versions of Superman, Superman Prime had several advantages which pushed his powers to a level unforeseen by nearly any version of the character: Vast Energy Absorption Powers: Superman Prime remained in the Earth's sun for 15,000 years. It was theorized there was no upper limit to his powers at this point. Given his feats after only a few decades of living on Earth, this extended time "sun-dipping" increased his powers to a level that dwarfed his incredibly powerful descendant, Kal Kent, who was already more powerful than the gravitation pull of a collapsing star and capable of traveling faster than light. Kal Kent is considered the equal of the most powerful canon version of Superman known up to that time: The Superman of Earth-One. Reality Alteration: Shown as capable, with the aid of the Superman of the 5th dimension, of turning a fragment of DNA inside-out through time into a full-fledged human being with the soul of the original individual, presumably among other capabilities. He resurrects Lois Lane giving her an immortal and probably superhuman physiology from a strand of DNA. He also restores Krypton, almost as if he snatched it out of Time itself. Power Bequeathment: Superman Prime is noted as being capable of sharing a portion of his power with his descendants, this fraction alone itself being a degree of power "far beyond any held by any metahumans ever" (though tying them inextricably to the Super-Sun that Prime inhabits as the source of their powers). Kal Kent is the distant descendant of Superman and the leader of Justice Legion Alpha in the 853 century AD. Immortality: Superman Prime has not visibly aged since the late 20th/early 21st century. It is this version of the character which gave rise to the idea that Superman might age slowly or not at all as long as he was exposed to solar radiation. In addition: Superman Prime also had access to what is believed to be the last Green Lantern ring and had the capability of powering and using it. This version of Superman is reputedly the apotheosis of everything Superman could ever hope to become, saving the Universe many times over, leaving a cosmic legacy of defenders across the galaxy, reaching and accessing the Source, moving through time and restoring/saving his entire doomed planet and species, and losing and finding his one true love. This version of Superman has the power to alter reality, courtesy of his access to Fifth Dimensional energies and thus is arguably more powerful than any version of the character to have ever existed. Apocrypha It is rumored that the vastly powerful Superman Prime exists in the same timeline as the Superman who appears in All-Star Superman, and is what the Superman of that series will become in the future. Kal Kent (or someone who looked suspiciously like him) claims to be from the far future and appears in All-Star Superman #6. Superman Prime (One Million) is also not to be confused with the canon character Superman-Prime aka Superboy-Prime (whose real name is Clark Kent) hailed from a Pre-Crisis reality (Earth-Prime) where superheroes didn't exist and were just comic book characters. When the Pre-Crisis DC Universe collapsed, Superboy-Prime was one of the few survivors. Unfortunately that happy ending was not to be as he returned to the Post-Crisis universe as a power-mad despot with powers rivaling that of the Earth-One Superman (making him the most powerful version of Superman since that Silver Age, Pre-Crisis powerhouse.) He was responsible for the deaths of Conner Kent/Kon-El (Post-Crisis clone-Superboy) and Panthra of the Teen Titans among many others before his imprisonment in the Source Wall. A: The DC One Million continuity is separate from the current New 52 continuity, meaning that "Golden Superman" - known as Superman Prime - is not considered part of the same continuity. Even when it was introduced, DC One Million was considered a "possible" future of the DC universe and not completely canon. It DID cross over into several Post-Crisis titles, however, which would indicate that it is considered at least partially canon: As for his powers & abilities, Superman Prime is essentially Superman to the Nth degree. He has all of the abilities normally associated with Superman plus the following: The ability to alter objects at the molecular/atomic level The ability to share a fraction of his power with anyone from his bloodline The ability to see light in the infrared spectrum Possesses a Green Lantern ring (possibly the last one) Immortality due to his centuries of absorbing solar energy Also, it's important to note that - due to his extensive years of soaking up solar energy - Superman Prime's abilities have all been enhanced & "super-charged" to the point that he is basically a god. He has absorbed so much solar energy that his skin has transmuted into a golden alloy, literally containing the power of a sun within his own body. Although his appearances have been limited, it's quite possible that he is the most powerful living being in the DC One Million continuity.
{ "pile_set_name": "StackExchange" }
Q: Automotive relay contact rating, Can it handle 120vac? I have this automotive relay, I would like to use it to switch a 120vac stereo that pulls around 9 amps. If the relay contact ratings are for 12vdc 30amps, how many amps can it handle at 120vac? Will using this type of relay be safe? A: It's probably not safe for 120V AC. A relay will typically be able to handle a lower DC voltage than AC, but 12V versus 120V is a big difference.
{ "pile_set_name": "StackExchange" }
Q: Using to upper incorrectly? Working code until I entered toupper My program worked like it was supposed to until I added the toupper part into my program. I've tried looking at my error code but it's not really helping. The errors are: no matching function to call 2 arguments expected, one provided So I know the error is in those two statements in my while loop. What did I do wrong? I want to make a name like john brown go to John Brown #include <iostream> #include <iomanip> #include <fstream> #include <string> using namespace std; int main(){ string firstname[5]; string lastname[5]; ifstream fin( "data_names.txt" ); if (!fin) { cout << "There is no file" << endl; } int i = 0; while( i < 5 && (fin >> firstname[i]) && (fin >> lastname[i]) ) { firstname[0] = toupper(firstname[0]); lastname[0] = toupper(lastname[0]); i++; } cout << firstname[0] << " " << lastname [0] << endl; cout << firstname[1] << " " << lastname [1] << endl; cout << firstname[2] << " " << lastname [2] << endl; cout << firstname[3] << " " << lastname [3] << endl; cout << firstname[4] << " " << lastname [4] << endl; return 0; } A: std::toupper works on individual characters, but you are trying to apply it to strings. Besides adding #include <cctype>, you need to modify your while loop's body: firstname[i][0] = toupper(firstname[i][0]); lastname[i][0] = toupper(lastname[i][0]); i++; Then it should work as expected. Live demo here As M.M helpfully pointed out in the comments, you should also check that your strings aren't empty before accessing their first characters, i.e. something like if (!firstname[i].empty()) firstname[i][0] = toupper(...); is strongly recommended. Mind you, you will probably need more sophisticated logic if you get names like McDonald :)
{ "pile_set_name": "StackExchange" }
Q: Is it possible to set "this" in anonymous function? I've got a function, public SharpQuery Each(Action<int, HtmlNode> function) { for (int i = 0; i < _context.Count; ++i) function(i, _context[i]); return this; } Which calls the passed in function for each element of the context. Is it possible to set what "this" refers to inside Action<int, HtmlNode> function? For example, sharpQuery.Each((i, node) => /* `this` refers to an HtmlNode here */); A: With a slight change in the function, you can achieve the desired effect. public SharpQuery Each(Action<MyObject, int, HtmlNode> function) { for (int i = 0; i < _context.Count; ++i) function(this, i, _context[i]); return this; } Then you could write your function call like so: sharpQuery.Each((self, i, node) => /* do something with `self` which is "this" */); Note: The anonymous function will only have access to public members however. If the anonymous function was defined within the class, it will have access to protected and private members as usual. e.g., class MyObject { public MyObject(int i) { this.Number = i; } public int Number { get; private set; } private int NumberPlus { get { return Number + 1; } } public void DoAction(Action<MyObject> action) { action(this); } public void PrintNumberPlus() { DoAction(self => Console.WriteLine(self.NumberPlus)); // has access to private `NumberPlus` } } MyObject obj = new MyObject(20); obj.DoAction(self => Console.WriteLine(self.Number)); // ok obj.PrintNumberPlus(); // ok obj.DoAction(self => Console.WriteLine(self.NumberPlus)); // error A: No. Well, yes, if the Action was created in such a scope where 'this' was available and bound in a closure -- but transparently: no. Pass in all needed information or make sure it's captured/available in the Action itself. There are other hacks like thread-locals, etc. Best avoided.
{ "pile_set_name": "StackExchange" }
Q: ruby rest-client: make it never timeout? I am trying to use ruby rest-client to upload a large number of images to a site that I'm writing. My code looks like: RestClient.post url, :timeout => 90000000, :open_timeout => 90000000, :file_param => file_obj However, I am getting this error: RestClient::RequestTimeout: Request Timeout from /Library/Ruby/Gems/1.8/gems/rest-client-1.6.1/lib/restclient/request.rb:174:in `transmit' from /Library/Ruby/ But when I look at the server log Completed in 61493ms (View: 2, DB: 1) | 201 Created So there doesn't appear to be any reason why this is timing out. Anyone have any idea if there is a timeout param I am not correctly setting? Thanks A: This syntax sets the timeout as request header (see RestClient.post signature), if you want to use the timeout parameter you must use: RestClient::Request.execute(:method => :post, :url => @url, :timeout => 90000000) see: https://github.com/rest-client/rest-client/blob/master/lib/restclient/request.rb#L12 A: Looking at the docs, you can pass -1 through RestClient.execute timeout param: # * :timeout and :open_timeout passing in -1 will disable the timeout by setting the corresponding net timeout values to nil It can be used as follows: resource = RestClient::Resource.new( "url", :timeout => -1, :open_timeout => -1 response = resource.get :params => {<params>} A: I have used following code and works like a charm as pointed out by Richard resource = RestClient::Resource.new "url", :timeout => $TIMEOUT, :open_timeout => $OPEN_TIMEOUT response = resource.get :params => { ..... }
{ "pile_set_name": "StackExchange" }
Q: Why does Try/catch in ActionBlock not catch this error sometimes? I'm using an ActionBlock in a web crawler I'm writing. Sometimes when I call actionBlock.Completion.Wait(); I get the following error One or more errors occurred. With the inner exception being System.Threading.Tasks.TaskCanceledException: A task was canceled. This is the full code block below. actionBlock = new ActionBlock<URLsToCheckObject>(URLToCheck => { try { // get more urls etc here and post below actionBlock.Post(new URLsToCheckObject { URLAddress = CleanURL, Host = host }); if (actionBlock.InputCount == 0) actionBlock.Complete(); } catch (Exception ex) { try { Logger.AddToDebugLog("Block 3 catch...", WebsiteToCrawl); } catch { } } }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 3, CancellationToken = cancellationSource.Token }); actionBlock.Post(new URLsToCheckObject { URLAddress = WebsiteToCrawl.website, Host = host }); try { Logger.AddToDebugLog("Waiting on action block..", WebsiteToCrawl); actionBlock.Completion.Wait(); } catch (Exception ex) { try { Logger.AddToDebugLog("Block 4 catch..." + ex.Message, WebsiteToCrawl); } catch { } try { Logger.AddToDebugLog("Block 4 catch..." + ex.InnerException, WebsiteToCrawl); } catch { } try { Logger.AddToDebugLog("Block 4 catch...", WebsiteToCrawl); } catch { } } Why would the try/catch that wraps the entire contents of the ActionBlock not catch this exception? A: The exception comes normally from: cancellationToken.ThrowIfCancellationRequested(); since you did not uses the CancellationToken inside your lambda, but it is used as a parameter for: new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 3, CancellationToken = cancellationSource.Token } the TaskCanceledException does not come from your lambda (but probably from inside of ExecutionDataflowBlockOptions or ActionBlock) so it is outside the scope of your try/catch inside the lambda, and so it does not catch.
{ "pile_set_name": "StackExchange" }
Q: What is the java Vector.element() C# equivalent Here is the java code i incompletely tried to translate static Enumeration enumerate() { Vector list = new Vector(); Enumeration e = cache.keys(); while (e.hasMoreElements()) { Vector v = (Vector) cache.get(e.nextElement()); for (int i = 0; i < v.size(); i++) { list.addElement(v.elementAt(i)); } } return list.elements(); } This is the C# translation but not complete public static IEnumerable<Http> enumurate() { List<Http> list = new List<Http>(); IEnumerator e = cache.Keys.GetEnumerator(); while (e.MoveNext())/*While e has more element*/ { var vector = (List<Http>)cache[e.Current]; for (int i = 0; i < vector.Count; i++) { list.Add(vector.ElementAt<Http>(i)); } } return //Something missing!! } Any help please ! A: In C# List<Http> implements IEnumerable<Http> so you can simply return your list: return list; To convert the code to C# even more, you could just skip the adding of elements to the list and yield results directly: public static IEnumerable<Http> enumerate() { IEnumerator e = cache.Keys.GetEnumerator(); while (e.MoveNext())/*While e has more element*/ { var vector = (List<Http>)cache[e.Current]; for (int i = 0; i < vector.Count; i++) { yield return vector.ElementAt<Http>(i); } } } Also, you can avoid using enumerators directly and make the code even more readable: public static IEnumerable<Http> enumerate() { foreach (var key in cache.Keys) { foreach (var http in (List<Http>)cache[key]) { yield return http; } } }
{ "pile_set_name": "StackExchange" }
Q: Get the Video URL after uploading a video to Youtube using Data API - php I'm trying to upload a video to YouTube using the PHP Data API $yt = new Zend_Gdata_YouTube($httpClient); $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry(); $filesource = $yt->newMediaFileSource('mytestmovie.mov'); $filesource->setContentType('video/quicktime'); $filesource->setSlug('mytestmovie.mov'); $myVideoEntry->setMediaSource($filesource); $myVideoEntry->setVideoTitle('My Test Movie'); $myVideoEntry->setVideoDescription('My Test Movie'); // Note that category must be a valid YouTube category ! $myVideoEntry->setVideoCategory('Comedy'); // Set keywords, note that this must be a comma separated string // and that each keyword cannot contain whitespace $myVideoEntry->SetVideoTags('cars, funny'); // Optionally set some developer tags $myVideoEntry->setVideoDeveloperTags(array('mydevelopertag', 'anotherdevelopertag')); // Optionally set the video's location $yt->registerPackage('Zend_Gdata_Geo'); $yt->registerPackage('Zend_Gdata_Geo_Extension'); $where = $yt->newGeoRssWhere(); $position = $yt->newGmlPos('37.0 -122.0'); $where->point = $yt->newGmlPoint($position); $myVideoEntry->setWhere($where); // Upload URI for the currently authenticated user $uploadUrl = 'http://uploads.gdata.youtube.com/feeds/users/default/uploads'; // Try to upload the video, catching a Zend_Gdata_App_HttpException // if availableor just a regular Zend_Gdata_App_Exception try { $newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry'); } catch (Zend_Gdata_App_HttpException $httpException) { echo $httpException->getRawResponseBody(); } catch (Zend_Gdata_App_Exception $e) { echo $e->getMessage(); } Does anyone know how to get the URL of the uploaded video from the $newEntry object. Any help will be appreciated :) A: Try this: try { $newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry'); $id = $newEntry->getVideoId(); // YOUR ANSWER IS HERE :) echo $id; }
{ "pile_set_name": "StackExchange" }
Q: How to apply perspective transform to Bezier curve? I found that both Bezier curves and B-splines are described with a formula $p(t)=\sum\limits_{i=0}^d B^i_m p_i$ but in the case of B-splines $B^i_m$ are B-spline blending functions, while for Bezier curve these are Bernstein polynomials. Also I found, that perspective transform can easily be applied to NURBS, which is similar to B-spline but each control point is associated with weight, which can also be represented in homogeneous coordinates $p_i = \left( \begin{array}{c} x_iw_i \\ y_iw_i \\ w_i \end{array} \right)$ And the plot will be the follows: $p(t)=\frac{\sum\limits_{i=0}^d B^i_m p_i}{\sum\limits_{i=0}^d B^i_m w_i}$ (is this correct?) My question is: how important is replacing B-spline blending function to Bernstein polinomials? Can I transform Bezier curves by applying the same technique? And also direct formulas would be appreciated :) UPDATE Also I am not sure about summation indice. In Bezier formula, the order of polynomial coincides with the number of control points, while in B-spline is not. Even on Wolfram's page the formula for "rational Bezier curve" is given with free order index: Does this mean that Stephen also not sure about polynomials? :) A: Your formula for a NURB curve is not quite correct. You missed out the $w_i$ in the numerator. It should be $$ p(t)=\frac{\sum\limits_{i=0}^d B^i_m(t) w_ip_i}{\sum\limits_{i=0}^d B^i_m(t) w_i} $$ You can apply perspective projections to either Bezier curves or b-spline curves in the same way. Bezier curves are actually just a special case of b-spline curves. Suppose you are working with curves of degree $m$, and you use the knot sequence consisting of $m+1$ zeros followed by $m+1$ ones: $(0,0,\ldots, 0,1,1,\ldots, 1)$. The b-spline basis functions constructed from this knot sequence are actually Bernstein polynomials, so the associated b-spline curve will actually be a Bezier curve. The limits in the summations are directly related to the numbers of control points. If a b-spline curve has $d+1$ control points $P_0, \ldots, P_d$, the summation runs from $0$ to $d$, regardless of its degree. A Bezier curve of degree $m$ has $m+1$ control points, so the summation runs from $0$ to $m$.
{ "pile_set_name": "StackExchange" }
Q: coding a web page for viewing on iphone Now I've seen loads of websites that look great on the iphone, such as http://twitter.com and http://deviantart.com however I can't for the life of me get the right structure within my mobile web application to make it show up as if it was an iphone application. I've discovered iphone jquery ( http://jqtouch.com ) which seems to be the most promising javascript lib for developing nice effects to make everything look authentic. However I'm still having issues with getting the website to fill the screen on iphone safari. I can never find any resourceful websites that actually explain how to get the effect of having it fully zoomed in and filling the screen. Are there any libraries that help develop websites for mobile devices such as iphones. A: To run fullscreen the webpage needs to be run as a webapp (bookmaked on the homescreen). You also need to indicate in your HTML that it is a web app. Taken from this website : <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta names="apple-mobile-web-app-status-bar-style" content="black-translucent" />
{ "pile_set_name": "StackExchange" }
Q: Disable beep sound when plugging/unplugging laptop charger My issue is the same as in this question, but none of the answers there helped solving my problem, so I'm hoping to get alternative suggestions here. My laptop (Acer Aspire S5-391 with Windows 10 Home 64 bit) makes an annoying beep sound whenever I plug or unplug the charger, which I'd like to disable. The following solutions I found in the linked question and in other places did not work for me: My BIOS doesn't provide a setting for power control beep. My playback device settings don't show the "PC speaker" bar, so I can't mute it. I don't have the Realtek audio driver, so I can't uninstall it. When I automatically search for a new audio driver via device manager, the search won't terminate. When I donwload the driver from the Acer Support site, I am only offered the Realtek driver (which seems to be a possible cause of the problem according to some sites) which anyway fails to install. My device manager doesn't show Non-Plug and Play Drivers, even after enabling "Show hidden devices", and therefore I can't see and disable the "Beep" device. According to LPChip's comment on DavidPostill's answer, in Windows 10 the "Beep" entry is labelled as "System devices" > "System speakers", so see the next bullet point. Edit after DavidPostill's updated answer My device manager doesn't show "system speakers" under "system devices" (which seems to be the equivalent to the above for Windows 10), so I can't disable them. Possibly my laptop doesn't have separate system speakers so the beep comes from the normal built-in speakers, in which case I probably won't be able to manipulate something in the device manager without also affecting all other sounds. "Default beep" in the system sounds I already have disabled (so this apparently isn't the correct option anyway). Gloabally disabling sounds mutes the beep, but is not a desired workaround for me - I only want to get rid of the charger beep, but still want to hear other default system sounds (or at least some, I alreay configured these in the control panel, but didn't find an option specifically for the charger beep; I think this is a matter of driver or BIOS settings rather than default Windows settings, but am not completely sure). A: My laptop makes an annoying beep sound whenever I plug or unplug the charger. Windows 8.1/Windows 10: Disable the System Speaker device: Open "Device Manager". Scroll down to "System Devices". Click on "+" Right click on "System Speaker". Select "Disable" Restart your computer. Beep should be permanently disabled. Windows 7: Disable the Beep device: Open "Device Manager". Go to "View" > "Show hidden devices". Scroll down to "Non-Plug and Play Drivers". Click on "+" Right click on "Beep". Select "Disable" Restart your computer. Beep should be permanently disabled. Source Disabling awful power cord beep?
{ "pile_set_name": "StackExchange" }
Q: Is Mincha an עת רצון? Someone told me that mincha is an עת רצון because מידת הרחמים is strongest at that point. Is there a source for this? A: The Shitta Mekubetset to Bava Kamma (82a) (middle of the first paragraph) cites a Gaon that it is an "et ratson". This is found in Otsar HaGeonim Megillah (23b) in the name of R. Sar Shalom Gaon. Tosafot to Pesahim (107a) writes the same. Numerous contemporaneous and later sources writes this as well.
{ "pile_set_name": "StackExchange" }
Q: how does this page implement the face recognition algorithm? Lately I've been very interested in this subject, for example I found a very interesting page that actually does it and it does it remarkable well http://www.pictriev.com/ How do they achieve such a grade of accuracy? A: Things like recognition algorithms are part of the field of artificial intelligence, specifically the branch of machine learning. An algorithm like this could be be implemented in many ways, for instance with neural networks which try and simulate brains. This question has a list of Python packages to do with machine learning.
{ "pile_set_name": "StackExchange" }
Q: How SEO friendly is Unicode URL? As the title says, how SEO friendly is a URL containing Unicode characters. Edit: To clarify, I meant URL with non-ASCII characters but valid Unicode. A: All URLs can be represented as Unicode. Unicode just defines a range of code-points from U+0000 to U+10FFFF, which allows you to define any characters. If what you mean is "How SEO friendly are URLs containing characters above U+007F" then they should be as good as anything else, as long as the word is correct. However, they won't be very easy for most users to type if that's a concern, and may not be supported by all internet browsers/libraries/proxies etc. so I'd tend to steer clear. A: If I were a Google other search engines authority I wouldn't consider the unicode URL-s an advantage. I have been using unicode urls for more than two years in my Persian website but believe me I just did it because I felt I was forced to do this. We know Google handles Uncode urls very well but I can't see the unicode words in URL-s when I'm working with them in google webmaster tools here is an example: http://www.learnfast.ir/%D9%88%D8%A8%D9%84%D8%A7%DA%AF-%D8%A2%DA%AF%D9%87%DB%8C there are only two Farsi words in such a messy and lengthy URL. I believe other Unicode url users don't like this either but they do this only for SEO optimization not for categorizing their contents or directing their users to the right address. Of course unicode is excellent for crawling the contents but there should be other ways to index URL-s. more over, English is our international language; Isn't it? It can be beneficially used for URL-s. There should be other means for indexing Unicode Urls. (Sorry for too much words from an amateur webmaster). A: FWIW, Amazon (Japan) uses Unicode URL for their product pages. http://www.amazon.co.jp/任天堂-193706011-Wiiスポーツ-リゾート-「Wiiモーションプラス」1個同梱/dp/B001DLXXCC/ref=pd_bxgy_vg_img_a (As you can see, it causes trouble with systems like the Stackoverflow wiki formatter)
{ "pile_set_name": "StackExchange" }
Q: Why does it matter how many taxpayers' dollars I have spent? When you finish a puzzle, you get a number of taxpayers' dollars spent. It is always a pretty large number, and it doesn't seem to have a point. What is the purpose of the number? Is it my score or something? A: It has no bearing on the game proper, but it seems to be related to how many attempts it took you to finish a puzzle. It's more something you can use to compare against friends, and not something that has any meaning aside from that (that I noticed).
{ "pile_set_name": "StackExchange" }
Q: Expression Language access a map value by key I am iterating a list named listEvents (of type List<String>) in JSP using <c:forEach> tag. Inside the for loop I need to display a value from a HashMap<String,String>. The key for the hashmap will be the element in the list. Please find below the code snippet. <c:forEach items="${listEvents}" var="listEvent" varStatus="eventCount"> <c:out value="${eventMap[listEvent]}</ </c:forEach> When I try with the above code, I am getting PropertyNotFoundException ["Key" property not found on java.lang.String]. How do I fix this? A: This is the right way to do it: <c:forEach var="listEvent" items="${eventMap}" varStatus="eventCount"> ${listEvent.value} </c:forEach> To access the key add this line: ${listEvent.key}
{ "pile_set_name": "StackExchange" }
Q: Woocommerce get category loop, exclude another category I don't know if I'm explaining this correctly, but I have a loop that's pulling all products assigned to a specific category (in this case, Current Season - this is for a performing arts organisation). But each product is actually assigned to multiple categories for various reasons, and in this case I want all products assigned to 'current-season', but NOT also assigned to the category 'series'. I've tried the following, but it has done nothing to change my query display. It's still showing everything assigned to 'current-season'. $args_right = array( 'post_type' => 'product', 'posts_per_page' => 999, //'product_cat' => 'current-season', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => 'series', 'operator' => 'NOT IN' ), array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => 'current-season', 'operator' => 'IN' ) ), 'meta_key' => 'date', 'orderby' => 'meta_value_num', 'order' => 'ASC' ); I'm sure I'm just missing something very obvious. I bang my head against the wall, and then wind up going "D'UH"!! Thanks in advance! A: i beleive your problem with the 'meta_key' => 'date' if you want to order the posts by date you can use the following query. $args_right = array( 'post_type' => 'product', 'posts_per_page' => 12, 'orderby' => 'date', 'order' => 'ASC', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'terms' => array('current-season'), 'field' => 'slug', 'operator' => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'. ), array( 'taxonomy' => 'product_cat', 'terms' => array('series'), 'field' => 'slug', 'operator' => 'NOT IN' // Possible values are 'IN', 'NOT IN', 'AND'. ) ), ); $loop = new WP_Query($args_right); if ($loop->have_posts()) { while ($loop->have_posts()) : $loop->the_post(); wc_get_template_part('content', 'product'); endwhile; } else { echo __('No products found'); } wp_reset_postdata(); Reference I tested this query locally and it's displaying all product with current-season category and if one product in this category assigned to another category or sub-category series it's excluded
{ "pile_set_name": "StackExchange" }
Q: Is there a way I can add multiple data sources to ListView? Currently, I am trying to make a table, which retrieves failed products and passed products from an Entity with LINQ. Lets assume I've done that, but have 2 lists, A regular List(Of String), and a SortedDictionary(Of String, int32) (To hold the product, and the number of times the testpoint has failed). Now, when I want to output them to ListView, in a Webform, how can I make it, so that List(Of String), will be output on the listview, and the SortedDictionary, be output after the List(Of String)? Thank you. EDIT: Although I could just add the SortedDictionary values to the end of the List aswell, but how would I go around doing so? Because I will create a listview with 2 columns, one which holds the descriptive text, and then a List(Of String) value. And the SortedDictionary would follow, requiring two columns. A: No. You can try to aggregate all data in one source and to add it to ListView.
{ "pile_set_name": "StackExchange" }
Q: BubbleChart ignores Ticks option BubbleChart does not display ticks to the Ticks option specs. BubbleChart[RandomReal[1, {10, 3}], Ticks -> {{#/10 // N, FromLetterNumber[#]} & /@ Range[10], Automatic}] Is this a bug or have I spec'ed it incorrectly? Version 10.2 on Win 8.1 Pro 64-bit A: Ticks generally aren't visible on graphics, when Frame->True is set. Module[{ticks = {#/10., FromLetterNumber[#]} & /@ Range[10]}, GraphicsGrid[{{BubbleChart[RandomReal[1, {10, 3}], Ticks -> {ticks, Automatic}, Axes -> True, Frame -> False], BubbleChart[RandomReal[1, {10, 3}], FrameTicks -> {ticks, Automatic}, Axes -> False, Frame -> True]}}]] Note the section on options in the help docs for BubbleChart, particularly the subsection which states: "BubbleChart has the same options as Graphics with the following additions and changes".
{ "pile_set_name": "StackExchange" }
Q: Read a thread Field from an other class I'm running a computation expensive code in background with the use of thread. This code return progress as he run. And in the main thread i want to read this value so i can show the user the progress Here is my setup : A process class : Public class ProcessThread implements Runnable { public int progress; ProcessThread{ } public void run(){ // Update progress as the processing goes } } And a main class: Public class MainClass { Private ProcessThread myProcessThread; MainClass{ myProcessThread = new ProcessThread(); (new Thread(myProcessThread)).start(); } Public void readProcess(){ // Called from anywere in the main thread. System.out.print("Progress = " + myProcessThread.progress); } } I wanted to know the best way to lock variables (using wait(), notify(), ...) so it's thread safe to read and write them. Thanks for any advice. Best A: You do not need to synchronize reading of the process variable. One thing you could do is to make it volatile to ensure that the main thread sees the latest state of the variable. On volatile: (In all versions of Java) There is a global ordering on the reads and writes to a volatile variable. This implies that every thread accessing a volatile field will read its current value before continuing, instead of (potentially) using a cached value. (However, there is no guarantee about the relative ordering of volatile reads and writes with regular reads and writes, meaning that it's generally not a useful threading construct.) (In Java 5 or later) Volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex.[9]
{ "pile_set_name": "StackExchange" }
Q: Golang s3 getting no file found and server panic on uploading image Hello first of i am new to Golang and am trying to upload a photo to my s3 Bucket however I am getting an error every time I try, the error I get is this err opening file: open 55fc14631c00004800082775.jpeg: no such file or directory2016/11/30 19:28:10 http: panic serving [::1]:58502: runtime error: invalid memory address or nil pointer dereference goroutine 5 [running] My buckets permission are set to read and write for everyone so it must be something in this code is that wrong and I am following this tutorial https://medium.com/@questhenkart/s3-image-uploads-via-aws-sdk-with-golang-63422857c548#.ahda1pgly and I am trying to upload a public image found here http://img.huffingtonpost.com/asset/,scalefit_950_800_noupscale/55fc14631c00004800082775.jpeg my current code is this below func UploadProfile(w http.ResponseWriter) { creds := credentials.NewStaticCredentials(aws_access_key_id, aws_secret_access_key,token) _, err := creds.Get() if err != nil { fmt.Printf("bad credentials: %s", err) } config := &aws.Config{ Region :aws.String("us-west-1"), Endpoint :aws.String("s3.amazonaws.com"), S3ForcePathStyle:aws.Bool(true), Credentials :creds, } svc := s3.New(session.New(), config) file, err := os.Open("55fc14631c00004800082775.jpeg") if err != nil { fmt.Printf("err opening file: %s", err) } defer file.Close() fileInfo, _ := file.Stat() var size int64 = fileInfo.Size() buffer := make([]byte, size) file.Read(buffer) fileBytes := bytes.NewReader(buffer) fileType := http.DetectContentType(buffer) path := "http://img.huffingtonpost.com/asset/,scalefit_950_800_noupscale/" + file.Name() params := &s3.PutObjectInput{ Bucket: aws.String("MyBucket"), Key: aws.String(path), Body: fileBytes, ContentLength: aws.Int64(size), ContentType: aws.String(fileType), } resp, err := svc.PutObject(params) if err != nil { fmt.Printf("bad response: %s", err) } fmt.Printf("response %s", awsutil.StringValue(resp)) fmt.Fprintf(w,"done") } I do not know why this is not working as my Credentials and buckets are correct . In addition the IMG address works for the image above so do not know why the file is nil <img height="200" width="200" src="http://img.huffingtonpost.com/asset/,scalefit_950_800_noupscale/55fc14631c00004800082775.jpeg"/> A: @user1591668, Your error is "err opening file: open 55fc14631c00004800082775.jpeg: no such file or directory". Sounds like not related to AWS's SDK. Check that your binary actually starts in the same directory where your image file is ("working directory") or, to test this assumption, you can try with an absolute path to the image. Cheers, Dennis
{ "pile_set_name": "StackExchange" }
Q: Как выполнить скрипты находящиеся в подпапках из файла в родительской папке программы Структура программы: parentfolder сontrol_panel.py Folder_1 sub_script_1.py Folder_2 sub_script_2.py sub_script_1.py и sub_script_2.py создают внутри своих папок подпапки 1.1folder и 1.2folder соответственно. Как теперь запустить sub_script_1.py и sub_script_2.py из файла сontrol_panel.py чтобы подпапки 1.1folder и 1.2folder создались внутри Folder_1 и Folder_2 а не в родительской. # sub_script_1.py для примера, sub_script_2.py имеет аналогичный код только вместо '1.1 folder' имеет '1.2 folder' import os def create_folders(): if not os.path.exists('1.1 folder'): os.makedirs('1.1 folder') create_folders() Пробовал через import и subprocess, но подпапки создаются в родительской папке. # Вариант с subprocess который создает подпапки в родительской папке import subprocess def main(): python_path = 'C:\\Users\\Home\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe' '''Запуск sub_script_1''' sub_script_1 = 'Folder_1\\sub_script_1.py' start_script1 = [python_path, sub_script_1] subprocess.call(start_script1) '''Запуск sub_script_2''' sub_script_2 = 'Folder_2\\sub_script_2.py' start_script2 = [python_path, sub_script_2] subprocess.call(start_script2) if __name__ == '__main__': main() A: "родительская папка" это директория из которой был запущен интерпретатор. чтобы не зависеть от этого внешнего фактора нужно определить путь к скрипту и получить тем самым директорию где расположен скрипт # sub_script_1.py для примера, sub_script_2.py имеет аналогичный код только вместо '1.1 folder' имеет '1.2 folder' import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) def create_folders(): sub_dir_path = os.path.join(BASE_DIR, '1.1 folder') if not os.path.exists(sub_dir_path): os.makedirs(sub_dir_path) create_folders()
{ "pile_set_name": "StackExchange" }
Q: Failed multimeter I have a cheap handheld multimeter that has stopped working. It basically behaves as if the leads weren't connected: the Vdc readout stays at zero, and the resistance readout stays at "1." I've checked the battery and have tested the leads with a bench meter. Now, before I chuck the meter in the bin (it's long overdue an upgrade anyway), is there anything else relatively obvious that may be worth checking? A: A few more things to check: Broken wires in your test leads Broken test lead terminals (where you plug the leads in), they may have bent and broken Fuse (as Robert suggests) "Fuse": some thin traces on the board that may have acted like a fuse for you. A: I think the leads have a fuse inline to protect the internals. Try opening it up and look for some blown fuses. A: I've had a similar problem years ago. What helped was disassembly and cleaning of the contacts below the rotating switch. You will find little spring contacts assembled in cavities of the rotating plastic part and contacts on the PCB that the little spring contacts brush over. A bit like the wiper of a potentiometer. Ethanol or isopropyl alcohol (or contact spray) will likely help. Seems like even the analog signals are routed along the contacts of the rotating switch, which sometimes gives not only complete open contacts but also resistance measurements that are just a bit too high, especially for the 200 Ohm range.
{ "pile_set_name": "StackExchange" }
Q: How to use XMLTABLE with multiple default namespaces My XML has multiple default name spaces, my below <BusMsg> <AppHdr xmlns="urn:iso:std:iso:20022:tech:xsd:head.001.001.01" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:head.001.001.01 General_head_001_001_01_20160503.xsd"> <CreDt>2017-06-29T05:32:11.147Z</CreDt> <Prty>abc</Prty> </AppHdr> <Document xmlns="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.05" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.05 SCT_pacs_008_001_05_20160503.xsd"> <FIToFICstmrCdtTrf> <GrpHdr> <MsgId>NATAAU33XXX2017062918789018AK12503</MsgId> <CreDtTm>2017-06-29T05:32:11.147Z</CreDtTm> <NbOfTxs>1</NbOfTxs> <SttlmInf> <SttlmMtd>abc</SttlmMtd> <ClrSys> <Cd>abc</Cd> </ClrSys> </SttlmInf> <InstgAgt> <FinInstnId> <BICFI>abcdd</BICFI> </FinInstnId> </InstgAgt> <InstdAgt> <FinInstnId> <BICFI>abcde</BICFI> </FinInstnId> </InstdAgt> </GrpHdr> </FIToFICstmrCdtTrf> </Document> </BusMsg> I tried like below, but didnt work, its giving me null as output SELECT f.PURPOSE FROM tem_table, XMLTABLE( xmlnamespaces(default 'urn:iso:std:iso:20022:tech:xsd:head.001.001.01 urn:iso:std:iso:20022:tech:xsd:pacs.008.001.05'), '/BusMsg/Document' PASSING XMLTYPE(tem_table.SOURCE_MESSAGE_TEXT) COLUMNS PURPOSE VARCHAR2(30) PATH 'FIToFICstmrCdtTrf/GrpHdr/MsgId') f WHERE id = '5bf8356b2e63'; Any one idea having on how to handle this A: Just because your XML document has different default namespaces in various elements, doesn't mean you have to use default namespaces to put them apart. The namespace mappings you declare in the XMLTABLE function are only relevant int he XQuery expressions of this XMLTABLE call. If you want to match the namespace urn:iso:std:iso:20022:tech:xsd:head.001.001.01 you have two options declare it as default namespace and don't prefix the elements/attributes in the XQuery expressions. assign it to a namespace prefix and also use that prefix in the XQuery expressions. XMLTABLE(xmlnamespaces(default 'urn:iso:std:iso:20022:tech:xsd:head.001.001.01' , 'urn:iso:std:iso:20022:tech:xsd:pacs.008.001.05' AS "n") , '/BusMsg/Document' PASSING XMLTYPE(tem_table.SOURCE_MESSAGE_TEXT) COLUMNS PURPOSE VARCHAR2(30) PATH 'n:FIToFICstmrCdtTrf/n:GrpHdr/n:MsgId' ) f I've assigned the NS ending in ".01" as default namespace and did not prefix the elements in the main QPath expression. I've also assigned the alias "n" to the other namespace, and also prefixed the elements from that namespace in the COLUMNS XQuery expression. I might have done some typos and it might be better reversed to have less namespace prefixes.
{ "pile_set_name": "StackExchange" }
Q: using editActionsForRowAtIndexPath to delete a row "UITableView internal bug" I need to create a action in editActionsForRowAtIndexPath to delete a row in a table. Following some research on the internet I came to this code: func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let remove = UITableViewRowAction(style: UITableViewRowActionStyle.Destructive, title: "Remover", handler: { (action: UITableViewRowAction, indexPath: NSIndexPath) -> Void in self.tableData.removeObjectAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) }) return [remove] } but now I get this error UITableView internal bug: unable to generate a new section map with old section count: 1 and new section count: 0 A: When you delete a row from UITableView, you need to take care of two things. First you should call tableView.deleteRowsAtIndexPaths only after you remove the object from the data source already. Because it'll check for the count again and ensure that the resultant data source have one less value. Now the second thing to remember is that the no. of section can't be 0 after you delete the last row. If you are returning 0 to numberOfSectionsInTableView, return 1 at least on empty row count. Another option is to actually delete the index too when you delete the last row.
{ "pile_set_name": "StackExchange" }
Q: Is There any ASTNode Library For IntelliJ? Is there any library I can use on IntelliJ equivalent to org.eclipse.jdt.core.dom? I want to be able to parse a java code to an AST. A: The library is called the PSI. See here for information about using the PSI.
{ "pile_set_name": "StackExchange" }
Q: How to calculate areas for data that covers the whole of Australia I have a polygon shapefile showing mining areas across all of Australia. I want to calculate the area for each of the polygons however they have been provided in a Geographic Coordinate System (GDA_94). Can anyone tell me what projected coordinate system I could use that would enable me to calculate the areas of each polygon? Will I need to transform the data and how might this affect the calculations given the size of Australia (i.e. it covers multiple GDA or UTM zones)? A: There are several projected coordinate systems that are valid for the whole Australia. I suggest that you use Australia Albers equal area because global projection often induce more distortions locally. For a global projection suitable for Australia, Hobo-Dyer (a cylindrical equal area projection) could be good too. As you can see on wikipedia, the Tissot indicatrice is close to a circle in Australia, which means that there little shape distortion (in addition to being equal-area). Remark (if you need accurate values): Before you project, make sure that your polygons are delineated with enough vertices (e.g. using some densify function). Indeed only the vertices are projected when you change the coordinate system. So if you have large polygon this could cause distortions (vertices are connected by straight lines before and after the projection).
{ "pile_set_name": "StackExchange" }
Q: Learning Python: print variable inside a function from another function I want to do the following in python: def func1(): var1 = "something" def func2(): print var1 What is the correct mode to do this ? I've not found in documentation at all PS. If possible, it's not my plan to make that 'var1' a global variable. Thanks. A: I assume you don't want to pass the variable as a parameter between the function calls. The normal way to share state between functions would be to define a class. It may be overkill for your particular problem, but it lets you have shared state and keep it under control: class C: def func1(self): self.var1 = "something" def func2(self): print self.var1 foo = C() foo.func1() foo.func2() A: No, it is not possible to do things like that. This is because of something called "scope". You can either create a module-level variable or place it in an OOP construct.
{ "pile_set_name": "StackExchange" }
Q: Does a connected manifold with vanishing Euler characteristic admit a nowhere-vanishing vector field? A version of the "hairy ball" theorem, due probably to Chern, says that the Euler-characteristic of a closed (i.e. compact without boundary) manifold $M$ can be computed as follows. Choose any vector field $\vec v \in \Gamma(\mathrm T M)$. If $p$ is a zero of $\vec v$, then the matrix of first derivatives at $p$ makes sense as a linear map $\partial\vec v|_p : \mathrm T_p M \to \mathrm T_p M$. By perturbing $\vec v$ slightly, assume that at every zero, $\partial\vec v|_p$ is invertible. Then $\chi(M) = \sum_{\vec v(p)=0} \operatorname{sign}\bigl( \det \bigl(\partial\vec v|_p\bigr)\bigr)$. I am curious about the following potential converse: "If $M$ is closed and connected and $\chi(M) = 0$, then $M$ admits a nowhere-vanishing vector field." Surely the above claim is false, or else I would have learned it by now, but I am not sufficiently creative to find a counterexample. Moreover, I can easily see an outline of a proof in the affirmative, which I will post as an "answer" below, in the hopes that an error can be pointed out. Thus my question: What is an example of a compact, connected, boundary-free manifold with vanishing Euler characterstic that does not admit a nowhere-vanishing vector field? (Or does no such example exist?) A: Yes, if M is closed and connected and χ(M)=0, then M admits a nowhere-vanishing vector field. Start with generic vector field, it has zero of index $\pm 1$. Two zeros of opposite sign can kill each other (maybe it is called Whitney trick?). So you get a field with zeros of the same sign. The result follows since the sum of the indexes is the Euler characteristic. A: That a compact manifold M with vanishing Euler characteristic has a nonvanishing vector field was proved by Heinz Hopf, Vektorfelder in Mannifaltigkeiten, Math. Annalen 95 (1925), 340-367. A pretty convincing "intuitive proof" was outlined by Norman Steenrod in his book Fibre Bundles (Theorem 39.7), using a smooth triangulation and obstruction theory. For a complete proof he refers to page 549 of the 1935 book Topologie by P. Alexandroff and H. Hopf
{ "pile_set_name": "StackExchange" }
Q: Explanations for the complexity values for second preimage attack on GOST? I've been reading the article "A (second) preimage attack on the GOST hash function" by F. Mendel et al (link) and I'm having some difficulty to grasp some of the values of complexities/probabilities in the attack. Specifically: On page 228, how is the probability that two pairs lead to the corresponding values $x_1$, $x_2$, and $x_3$ amount to $2^{-192}$? On page 230, how is $2^{128}$ used in the calculation of the complexity of the compression function? On page 230, why construct $2^{32}$ pseudo-preimages for the last iteration of GOST? On page 231, how was the value for the probability of finding the right $M_{257}$ in the list $L$ obtained? Finally, on another issue, what operation is referred to by the squared $\ominus$ symbol on page 231: $\Sigma^m = \Sigma^t \ominus M_{257}$. [My guess: subtraction modulo $2^{256}$ -- am I right?] Thanks very much. A: Preliminary: Almost the same article is available for free without breaking any law, nor downloading 5GB (formatting is shifted by at most one third of a page). It is also (as well as all other articles of IACR crypto conferences from 2000-2011) in the IACR Online Proceedings, specifically in the FSE 2008 section, but then you need to subtract about 223 from the page numbers quoted in the question to get the page number in the PDF. For this reason it is best to use section (rather than page) numbers to designate a section of an article. I have now answered all the points (and learned along the way), but anyone remains welcome to improve that answer, made community wiki. 1) In section 3, why does the probability that two pairs lead to the corresponding values $x_1$, $x_2$, and $x_3$ amount to $2^{−192}$? By construction, $x_i$, $y_i$, $z_i$, $s_i$ are 64-bit. We assume that the process that uncovered each pair, being independent of the relations $x_i=y_i\oplus z_i\oplus s_i$ for $i\in\{1,2,3\}$ (only concerned with that relation for $i=0$), makes each of these relations for $i\in\{1,2,3\}$ true with odds about $2^{-64}$; hence makes the three true with odds about $2^{-192}$ (again, without proof of independence). That's typical in cryptanalysis: we assume odds that $a=b$ holds with odds $2^{-n}$ when $a$ and $b$ are $n$-bit with at least one of these quantity produced by a process that is engineered for a purpose independent of matching that relation, and that process's output or the other quantity has no clear bias. That probability would follow from assuming either quantities is uniformly distributed. 2) In section 4.1, how is $2^{128}$ used in the calculation of the complexity? In section 4.1 it is considered a multicollision of $t=256$ message blocks, with for each block a pair of values that can be used interchangeably without changing the result in $H_{256}$: For each of $t$ message blocks, the pair is found by the birthday attack on the output of $f$, which has $n=256$ bits, thus with about $2^{n/2}$ evaluations of $f$ using a technique such as Paul C. van Oorschot and Michael J. Wiener's Parallel Collision Search with Cryptanalytic Applications. Here comes the $2^{n/2}=2^{128}$ term! The total cost of finding the multicollision is about $t\cdot2^{n/2}=2^{136}$. Notice that this is already totally impracticable in a foreseeable future: we are discussing a theoretical attack 3) In section 4.2, why construct $2^{32}$ pseudo-preimages for the last iteration of GOST? That's a compromise between the work required in 4.2, which increases proportionally to the number $w$ of pseudo-preimages made; and the work required in 4.3, which decreases proportionally to $w$. The sum of work required for the two steps is thus of the form $a\cdot w+b/w$, and the minimum for that is for $w=\sqrt{b/a}$. Here $a=2^{192}$, and $b=2^{256}$ (not quite in the same unit unless I err, but since this is a purely theoretical attack, that does not matter much), and it comes $w=2^{32}$ for the minimum. In other words: one can change $2^{32}$ a little, the attack will still (theoretically) work. With an increase of that to say $2^{33}$, the expected work in 4.3 will be halved, but that's at the price of twice more work in 4.2, and twice more memory. Thus if we increase too much the work will be raised overall (dominated by 4.2), and if we decrease too much the work will be raised overall (dominated by 4.3). The value $2^{32}$ balances the work in 4.2 and 4.3, and is in the right ballpark for a minimum overall attack effort. 4) In section 4.3, how was the probability of finding the right $M_{257}$ in the list $L$ obtained? The list $L$ contains $w=2^{32}$ pairs $(H,M)$ with $H$ of $n=256$ bits (distinct with high odds since $w\ll2^{n/2}$, under the standard assumption that the $H$ are random-like for reasons discussed in 1). We want to find an $M_{257}$ that makes $H_{258}$ matching the $H$ of some $(H,M)$ in $L$. $H_{258}$ is next to uniformly distributed (no matter how we enumerate distinct $M_{257}$, because that's a design goal for $f$) thus each value tried has odds $2^{-n}$ to match any particular $H$ in the list, thus odds (only very slightly above) $2^{-n}\cdot w=2^{-224}$ to match one $H$ in the list, and that's the probability we wanted. That part of the attack alone is expected to require trying $2^{224}$ values of $M_{257}$, thus $2^{225}$ evaluations of $f$, and that's also the stated cost of the attack: at this degree of impracticality, it is common to consider $u+v\approx u$ whenever $v<u$ and we repeat such approximation only a few times. 5) What operation is referred to by the $\boxminus$ symbol? Indeed, $\boxminus$ (written $\boxminus$ on this website) is used in this article for subtraction modulo $2^{256}$. That is quite clear in the context of use of section 4.3 of the paper, given the definition of $\boxplus$ ($\boxplus$) in section 2 as addition modulo $2^{256}$. Note: to determine how to render a symbol in $\TeX$, I often try a detexifyer, and in that case it worked. 6) In Section 3, why does the system of equations with $5⋅64$ equations in $8⋅64$ variables results in $2^{192}$ solutions? A linear system of $x$ linearly independent equations in $y>x$ variables is under-determined, and $y-x$ variables can be fixed to any value. If these are binary variables, that leads to $2^{y-x}$ solutions. We obtain $2^{192}$ as $2^{8⋅64-5⋅64}$. The same occurs when solving the system of equations with $6⋅64$ equations in $8⋅64$ variables leading to $2^{128}$ solutions: we obtain $2^{128}$ as $2^{8⋅64-6⋅64}$.
{ "pile_set_name": "StackExchange" }
Q: Nginx Third Party Module subs_filter installed but not working returning unknown directive I've installed Nginx previously and recompiled again in order to add two new modules using the usual ./configure and make process. Nginx is running fine but when I call sub_filter in the .conf file I get an error nginx: [emerg] unknown directive "sub_filter" in /usr/local/nginx/conf/sites-available/nobo.conf:46 The version and compile info tells me the module is there (third party module) Do I need to enable it somewhere or have I missed a step in the process nginx version: nginx/1.5.7 built by clang 6.0 (clang-600.0.51) (based on LLVM 3.5svn) TLS SNI support enabled configure arguments: --add-module=rob_nginx_modules/ngx_http_substitutions_filter_module/ --with-http_ssl_module Any Ideas? A: Your error says that the unknown directive is "sub_filter", but the module in your configure arguments is the third party nginx_substitutions_filter. The correct directive for this is subs_filter, with an 's'.
{ "pile_set_name": "StackExchange" }
Q: Prove that $\sum_{X=0}^N u(X) {N \choose X} p^X (1-p)^{N-X}=0 \iff u(X)=0, \space \forall X\in\{ 0,1,...,N \}$ I am trying to prove that $Bin(N,p)$ where $N$ is fixed is a complete distribution. Thus my goal is to show $$E[u(X)]=0 \iff u(X)=0$$ While I was attempting to prove this I have noticed that $$\sum_{X=0}^N u(X) {N \choose X} p^X (1-p)^{N-X}$$ is a degree-$N$ polynomial congruent to $0$ making all coefficients equal to $0$. Here, the coefficients ends up being a nice linear combination which I suspect that it is a form of binomial coefficients. For example, when $N=3$ I get the following $$\begin{align} \sum_{X=0}^3 u(X) {3 \choose X} p^X (1-p)^{3-X}= \\ & \quad p^3*(u(3)-3u(2)+3u(1)-u(0)) \\ &+p^2*3(u(2)-2u(1)+u(0)) \\ &+p*3(u(1)-u(0)) \\ &+1(u(0))\\ \end{align}$$ $$ = p^3\sum_{i=0}^3u(i){3 \choose i}(-1)^i +p^2\sum_{i=0}^2u(i){2 \choose i}(-1)^i +p\sum_{i=0}^1u(i){1 \choose i}(-1)^i + u(0)$$ $$=\sum_{j=0}^3\sum_{i=0}^j u(i){3 \choose j}{j \choose i}(-1)^ip^j$$ The part that I would like have assistance is to show that $$\sum_{X=0}^N u(X) {N \choose X} p^X (1-p)^{N-X}=\sum_{j=0}^N\sum_{i=0}^j u(i){N \choose j}{j \choose i}(-1)^ip^j$$ and that the cascades of $u(i)=0$ occurs, i.e., $$u(0)=0 \implies u(1)=0 \implies ... \implies u(N)=0$$ I appreciate your assistance. A: This is an answer that summarizes the question and the comments. The goal is to show that $$E[u(X)]=0 \iff u(X)=0$$ and the given equation is equivalent to $$\sum_{X=0}^n u(X) {N \choose X} p^X (1-p)^{N-X} = \sum_{j=0}^N \sum_{i=0}^j u(i){N \choose j} {j \choose i}(-1)^ip^j = 0$$ We are assuming that $N$ is fixed and $p \in [0,1]$ The middle column is a Bernstein Polynomial that is a base, thus if it is equal to $0$ then $u(X)=0$. This shows that $Bin(N,p)$ is a complete distribution.
{ "pile_set_name": "StackExchange" }
Q: Is it legal to create a copy of a book for personal use and then gift the original to others, so they could repeat this process indefinitely? There's this comment thread under a post about student textbooks and a few other threads in the same post about the same legal loophole: Commenters are saying that while it is illegal to distribute copies of an original book, it's okay to make a copy for personal use, keep it, and then give away or sell the original book as used, and then others can repeat this until everybody has a personal copy, and there's only one original in the wild. Is this right? A: The commentators are just making stuff up when they say that you can freely infringe on copyright as long as it is for personal use. It is true that "personal infringers" are less likely to suffer the legal consequences of any infringement (partly because it's easier to avoid detection and partly because the hassle to award ratio involved in suing a personal infringer is too high). It's a misunderstanding of "fair use", based on the legally erroneous assumption that anything is okay until you make a business out of it.
{ "pile_set_name": "StackExchange" }
Q: resources in a Spring Boot application are missing from jar file when using Spring Boot Maven Plugin I am using Spring-Boot v1.3.0.M5 with Maven v3.3.3. I used to be able to run my Spring Boot (boot) application from the console with this command. mvn clean package spring-boot:run However, I've had to revise my pom.xml to account for different environment builds. In particular, I am using Maven profiles to modify the properties files of boot application. Now when I run the previously mentioned command, the boot application fails to run and complains with the following exception. Caused by: java.lang.NumberFormatException: For input string: "${MULTIPART.MAXREQUESTSIZE}" I have a properties file located at src/main/resources/config/application.properties. And this properties file has a bunch of key-value pairs which looks like the following. multipart.maxFileSize=${multipart.maxFileSize} multipart.maxRequestSize=${multipart.maxRequestSize} Then in my pom.xml, my build is defined as follows. <build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>**/*.properties</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <filtering>false</filtering> <excludes> <exclude>**/*.properties</exclude> </excludes> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <profiles> <!-- development --> <profile> <id>env-dev</id> <activation> <activeByDefault>true</activeByDefault> <property> <name>env</name> <value>dev</value> </property> </activation> <properties> <multipart.maxFileSize>250MB</multipart.maxFileSize> <multipart.maxRequestSize>250MB</multipart.maxRequestSize> </properties> </profile> <!-- staging --> <profile> <id>env-stg</id> <activation> <activeByDefault>false</activeByDefault> <property> <name>env</name> <value>stg</value> </property> </activation> <properties> <multipart.maxFileSize>500MB</multipart.maxFileSize> <multipart.maxRequestSize>500MB</multipart.maxRequestSize> </properties> </profile> <profiles> I noticed that if I type in mvn clean package and look inside the jar file, the application.properties file is inside the jar. However, if I type in mvn clean package spring-boot:run, then the applications.properties file is not inside the jar. In fact, nothing under src/main/resources makes it into the jar file. This problem is a little annoying for me because if I want to run my boot application from the command line, I have to do two steps now. mvn clean package java -jar ./target/app-0.0.1-SNAPSHOT.jar Any ideas on what I am doing wrong? A: As described in the documentation mvn spring-boot:run adds src/main/resources in front of your classpath to support hot reload by default. You can turn this off easily <build> ... <plugins> ... <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>1.2.7.RELEASE</version> <configuration> <addResources>false</addResources> </configuration> </plugin> ... </plugins> ... </build>
{ "pile_set_name": "StackExchange" }
Q: If $X^\ast $ is separable $\Longrightarrow$ $S_{X^\ast}$ is also separable Let $X$ be a Banach space such that $X$* (Dual space of $X$) is separable How can we prove that $S_{X^\ast}$ (Unit sphere of $X$*) is also separable Any hints would be appreciated. A: Note: here we consider the question for $X^*$, and $S_{X^*}$, equipped with the topology induced by the norm. See this thread for the same question with the weak* topology. This is a consequence of a much more general fact which has nothing to do with duals and Banach spaces. Fact: if $(X,d)$ is a separable metric space, then for any subset $Y\subseteq X$, the subspace $(Y,d)$ is separable. Note: as pointed out by Nate Eldredge, another approach is to observe that a subspace of a second countable space is obviously second countable. So it only remains to use or prove that a metric space is separable if and only it is second countable. Proof: let $S=\{x_n\,;\,n\geq 1\}$ a dense subset of $X$. For every $n\geq 1$, consider the distance $d(x_n,Y)=\inf\{d(x_n,y)\,;\,y\in Y\}$. By definition of an infimum=greatest lower bound, for every $k\geq 1$, $d(x_n,Y)+\frac{1}{k}$ is not a lower bound of $\{d(x_n,y)\,;\,y\in Y\}$. So there exists $y_n^k\in Y$ such that $d(x_n,y_n^k)< d(x_n,Y)+\frac{1}{k}$. Since $T=\{y_n^k\,;\,n\geq 1, k\geq 1\}$ is a countable union of countable sets, it is countable. We will now show that it is dense in $Y$. Take $y\in Y$ and $\epsilon>0$. By density of $S$ in $X$, there exists $n\geq 1$ such that $d(x_n,y)<\frac{\epsilon}{2}$. In particular, $d(x_n,Y)\leq d(x_n,y)<\frac{\epsilon}{2}$. So for $k$ large enough, precisely: $k>\left(\frac{\epsilon}{2}-d(x_n,Y)\right)^{-1}$, we have $d(x_n,Y)+\frac{1}{k}<\frac{\epsilon}{2}$. Then for this $n$ and such a $k$, we get $$ d(y_n^k,y)\leq d(y_n^k,x_n)+d(x_n,y)<d(x_n,Y)+\frac{1}{k}+\frac{\epsilon}{2}<\frac{\epsilon}{2}+\frac{\epsilon}{2}=\epsilon. $$ So there are elements of $T$ arbitrarily close to $y$ for every $y\in Y$. That is $T$ is dense in $Y$. QED. Remark: what really is about Banach spaces $X$ such that $X^*$ is separable is that $X$ is separable. And it follows that the unit sphere of $X$, $S_X$, is separable as well.
{ "pile_set_name": "StackExchange" }
Q: How this statement works `int k = (a++, ++a);` in c or c++ I am unable to understand how the output of the below code is "-3" ? #include <stdio.h> void main() { int a = -5; int k = (a++, ++a); printf("%d\n", k); } What is the concept behind this int k = (a++, ++a); statement in c or c++? A: It works because of the , operator which creates a sequence point. §5.19.1 (Comma operator) The comma operator groups left-to-right. A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded value expression (Clause 5). Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression. The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand, and is a bit-field if its right operand is a glvalue and a bit-field. If the value of the right operand is a temporary (12.2), the result is that temporary. Therefore: a is initialized to -5. Then a++ executes, and modifies a to -4. Then ++a executes, modifies a to -3, and returns -3 to k.
{ "pile_set_name": "StackExchange" }
Q: MySQL syntax error when using question mark placeholders in prepared statement Tried everything I can think of and I've narrowed down to the "?" placeholders. I've tried replacing the "?" placeholders with random text and all works well (except of course it keeps overwriting the same row). The error I get: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE produ' at line 2 Here is my code (I would provide more but it all works well except for this bug, and if I remove the "?" placeholders then all works perfectly except that the values are not dynamic, but please ask if you suspect the issue is elsewhere): // Create MySQL connection to ds_signifyd_api $mysqli = mysqli_connect( $db_server_name, $db_username, $db_password, $db_name ); // Check connection if ($mysqli->connect_error) { exit( $mysqliFailedBody ); } $mainProdQueryStmt = "INSERT INTO products (`product_id`, `title`, `body_html`, `vendor`, `product_type`, `created_at`, `handle`, `updated_at`, `published_at`, `template_suffix`, `published_scope`, `tags`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE product_id = VALUES(product_id), title = VALUES(title), body_html = VALUES(body_html), vendor = VALUES(vendor), product_type = VALUES(product_type), created_at = VALUES(created_at), handle = VALUES(handle), updated_at = VALUES(updated_at), published_at = VALUES(published_at), template_suffix = VALUES(template_suffix), published_scope = VALUES(published_scope), tags = VALUES(tags)"; $product_id = $product_title = $body_html = $vendor = $product_type = $created_at = $handle = $updated_at = $published_at = $template_suffix = $published_scope = $tags = ""; foreach ($dss_product_db_array as $product) { $product_id = $product['id']; //... more variables here... $tags = mysqli_real_escape_string($mysqli, $tags); if (!mysqli_query($mysqli, $mainProdQueryStmt)) { printf("Errormessage: %s\n", mysqli_error($mysqli)); } $mainProdQuery->bind_param("isssssssssss", $product_id, $product_title, $body_html, $vendor, $product_type, $created_at, $handle, $updated_at, $published_at, $template_suffix, $published_scope, $tags); $mainProdQuery->execute(); // $mainProdQuery->close(); } UPDATE Implemented the fixes mentioned here: 1. Stopped using mysqli_real_escape_string 2. Binding variables outside loop 3. Using only the object oriented method, as opposed to mixing them as in the case of mysqli_query($mysqli, $mainProdQueryStmt) VS $mysqli->prepare($mainProdQueryStmt) as it should have been -- this solved the "?" placeholders syntax error being incorrectly reported Now everything works perfectly, no errors. Updated Code: $mainProdQueryStmt = "INSERT INTO dss_products (`product_id`, `title`, `body_html`, `vendor`, `product_type`, `created_at`, `handle`, `updated_at`, `published_at`, `template_suffix`, `published_scope`, `tags`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE product_id = VALUES(product_id), title = VALUES(title), body_html = VALUES(body_html), vendor = VALUES(vendor), product_type = VALUES(product_type), created_at = VALUES(created_at), handle = VALUES(handle), updated_at = VALUES(updated_at), published_at = VALUES(published_at), template_suffix = VALUES(template_suffix), published_scope = VALUES(published_scope), tags = VALUES(tags)"; $mainProdQuery = $mysqli->prepare($mainProdQueryStmt); if ($mainProdQuery === FALSE) { die($mysqli->error); } $product_id = $product_title = $body_html = $vendor = $product_type = $created_at = $handle = $updated_at = $published_at = $template_suffix = $published_scope = $tags = ""; $mainProdQuery->bind_param("isssssssssss", $product_id, $product_title, $body_html, $vendor, $product_type, $created_at, $handle, $updated_at, $published_at, $template_suffix, $published_scope, $tags); if ($mainProdQuery) { foreach ($dss_product_db_array as $product) { $product_id = $product['id']; $product_title = $product['title']; $body_html = $product['body_html']; $vendor = $product['vendor']; $product_type = $product['product_type']; $created_at = $product['created_at']; $handle = $product['handle']; $updated_at = $product['updated_at']; $published_at = $product['published_at']; $template_suffix = $product['template_suffix']; $published_scope = $product['published_scope']; $tags = $product['tags']; if (!$mysqli->prepare($mainProdQueryStmt)) { printf("Errormessage: %s\n", $mysqli->error); } $mainProdQuery->execute(); } } A: When you use placeholders you have to use mysqli_prepare(), you can't use mysqli_query(). It looks like you intended to do that, but somehow that code got lost, since you use a variable $mainProdQuery that you never assigned. You should prepare the query and bind the parameters just once, outside the loop. Then call execute() inside the loop. $mainProdQueryStmt = "INSERT INTO products (`product_id`, `title`, `body_html`, `vendor`, `product_type`, `created_at`, `handle`, `updated_at`, `published_at`, `template_suffix`, `published_scope`, `tags`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE product_id = VALUES(product_id), title = VALUES(title), body_html = VALUES(body_html), vendor = VALUES(vendor), product_type = VALUES(product_type), created_at = VALUES(created_at), handle = VALUES(handle), updated_at = VALUES(updated_at), published_at = VALUES(published_at), template_suffix = VALUES(template_suffix), published_scope = VALUES(published_scope), tags = VALUES(tags)"; $mainProdQuery = $mysqli->prepare($mainProdQueryStmt); $mainProdQuery->bind_param("isssssssssss", $product_id, $product_title, $body_html, $vendor, $product_type, $created_at, $handle, $updated_at, $published_at, $template_suffix, $published_scope, $tags); foreach ($dss_product_db_array as $product) { $product_id = $product['id']; //... more variables here... $mainProdQuery->execute(); }
{ "pile_set_name": "StackExchange" }
Q: Asking for an idiom according to literal translation I translated a sentence into English: When the details are ignored, the whole problem will be ignored unintentionally Seems like a logical sentence that says when you don't consider all details while solving a problem, it'll affect the result and the whole problem. I'd like to know if there's an idiomatic expression meaning the same. A: The best saying I can think of is The devil's in the details Which mean that the smallest parts of a problem are the most challenging. The opposite of what you want, I think, is Look after the pennies and the pounds will look after themselves Meaning, if you take care of the little things the big things will fall into place. A: It's not clear to me exactly what OP wants to convey. If she's trying to point out that solving some particular problem is actually much harder than might be thought by others who don't understand exactly what will be involved, @Matt's "The devil's in the detail" is probably appropriate (it's often pluralised now, but I've always known it in the singular). If on the other hand, OP is trying to convey that failure to conscientiously attend to all details will result in an inadequate solution, I suggest the proverb If a job's worth doing, it's worth doing well.
{ "pile_set_name": "StackExchange" }
Q: How to set formula by using google spreadsheets app script? Actually, question is - how to recreate type of formulas: ArrayFormula(replace(replace(regexreplace(K1:K&"","[-/,. ()]",""),4,0,"-"),8,0,"-")) into code. Unfortunately, i didn't find it by myself, so I'm asking for help. Upd. Let me clarify just a little. Part of code which was used by me into script: value = value.replace(/^ /, '').replace(/[. )]/g, 'a').replace(/[+]/g, '').replace(/(aa)/g, '-').replace(/(a)/g, '-').replace(/[(]/g, '-'); value = value.replace(/^-/, ''); value = value.replace(/-$/, ''); range2.setValue(value); This is example of a result: "(22)road.CA" - "22-road-CA"; "22roadCA" - is not(eror). If we working into google spreadsheets we could use formula's which I'm typed before, and in this case, results will be the: "(22)road.CA" - "22-road-CA"; "22roadCA" - "22-road-CA". So, how to create right code for it? Mb I should delete all signs, use looping method for check sign by sign, and insert my variant after some count of cell array? A: Simple example : var formulaTargetCell = SpreadsheetApp .getActiveSpreadsheet() .getActiveSheet() .getRange(1, 1, 1, 1); formulaTargetCell.setFormula('=ArrayFormula(replace(replace(regexreplace(K1:K&"""",""[-/,. ()]"",""""),4,0,""-""),8,0,""-""))'); //or var formulaTargetCell = SpreadsheetApp .getActiveSpreadsheet() .getActiveSheet() .getRange('B2'); formulaTargetCell.setFormulaR1C1('=ArrayFormula(replace(replace(regexreplace(K1:K&"""",""[-/,. ()]"",""""),4,0,""-""),8,0,""-""))'); There are still some kind of way to set formula in app script that documented in available API of Range
{ "pile_set_name": "StackExchange" }
Q: Is this the correct expression for a combination problem? I feel that I have the correct expression for this problem, but I have this nagging feeling that something is incorrect. May I ask that you all verify this? Question: "In a game of chance, three of the same color wins. Suppose there are thirty colored coins of the same size in a bag. The bag contains an equal amount of red, blue, green, yellow and white colored coins. If a player is allowed only one draw of three coins, how many possible winning draws are there? How many ways can the player lose?" My Answer: C(30, 3) C(30, 27) A: There are $6$ of every colored coin. To win, you can choose exactly $3$ red coins. There are $\text C(6, 3)$ ways to do that. But you can win with any of the other $4$ colors, so there are $5\cdot \text C(6, 3)$ ways to win. Any other draw you make will result in a loss, so the remaining $\text C(30, 3)-5\cdot\text C(6, 3)$ draws are ways to lose.
{ "pile_set_name": "StackExchange" }
Q: Hibernate: ManytoMany mapping: "Two-way" I have two class: Order.java: @Entity @Table(name = "orders", catalog = "ownDB") public class Order { private int orderNO; private String oderName; private Set<Room> rooms = new HashSet<Room>(0); public Order(int orderNo, String orderName, Set<Room> rooms) { this.oderNo = orderNo; this.orderName = orderName; this.rooms = rooms; } @Id @Column(name = "orderNO", unique = true, nullable = false, length = 6) public int getOrderNO() { return this.orderNO; } public void setOrderNo(int OrderNO) { this.orderNO = orderNO; } @Column(name = "orderName", nullable = false, length = 100) public String getOrderName() { return this.orderName; } public void setOrderName(String orderName) { this.orderName = orderName; } @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "rooms_orders", joinColumns = { @JoinColumn(name = "orderNO") }, inverseJoinColumns = { @JoinColumn(name = "roomNO") }) public Set<Room> getRoom() { return this.rooms; } public void setRoom(Set<Room> rooms) { this.rooms = rooms; } } And this is the room.java: @Entity @Table(name = "rooms", catalog = "ownDB") public class { private int roomNO; private String name; private Set<Order> orders = new HashSet<Order>(0); public Room(int roomNO, String name, Set<Order> orders) { this.roomNO = roomNO; this.name = name; this.orders = orders; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "roomNO", unique = true, nullable = false, length = 6) public int getRoomNO() { return this.roomNO; } public void setRoomNO(int roomNO) { this.roomNO = roomNO; } @Column(name = "name", nullable = false, length = 100) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "rooms_orders", joinColumns = { @JoinColumn(name = "roomNO") }, inverseJoinColumns = { @JoinColumn(name = "orderNO") }) public Set<Order> getOrders() { return this.orders; } public void setOrders(Set<Order> orders) { this.orders = orders; } } SQL: CREATE TABLE rooms ( roomNO int(6) NOT NULL , name VARCHAR(100) NOT NULL , PRIMARY KEY (roomNO)); CREATE TABLE orders ( orderNO int(6) NOT NULL AUTO_INCREMENT, orderName VARCHAR(100) NOT NULL, PRIMARY KEY (orderNO)); CREATE TABLE rooms_orders ( roomNO int(6) NOT NULL, orderNO int (6) NOT NULL, PRIMARY KEY (roomNO, orderNO)); What is the problem with the two mapping? It is works for me. But I don't want to use, if it isn't the right way. If I am change the second mapping to "@ManyToMany(mappedBy="room")" (without the joinTable annotation) in the Order class. I can't list all rooms (with their orders), because I got this error message: "Failed to lazily initialize a collection of role: com.room.model.Room.orders, could not initialize proxy - no Session" What is the right way to can list all orders with their rooms and all rooms with their orders. So I need "two-way" join. A: There are many errors in the code you posted. First of all, your join table is not correctly defined. It shouldn't have a seperate column for the ID: noone will ever populate this column. It should be defined as CREATE TABLE rooms_orders ( roomNO int(6) NOT NULL, orderNO int (6) NOT NULL, PRIMARY KEY (rommNO, orderNO)); Second, your mapping is wrong. A bidirectional association always has an owner side, which defines how the association is mapped, and an inverse side, which uses the mappedBy attribute to tell JPA that this is the inverse side, and where to find the owner side. So, in Room, the association should be mapped with @ManyToMany(mappedBy = "rooms") public Set<Order> getOrders() { return this.orders; } And finally, your mapping for the association doesn't match with the column names in your table: @JoinTable(name = "rooms_orders", joinColumns = { @JoinColumn(name = "orderNO") }, inverseJoinColumns = { @JoinColumn(name = "roomNumber") }) There is no column "roomNumber" in the table. The column is named "roomNO".
{ "pile_set_name": "StackExchange" }
Q: Failing to use String.Format to display Version String in WPF I am a C++ developer and recently shifted to C#. I am working on a wpf app where I need to work on String.Format. In My C++ application, I had used sprintf to obtain the result but when it comes to C#, string.format helped me achieve it. Now I have come across a tricky situation where I need to achieve the similar thing but with different values. Here Is the C++ code: char t_str[4] = {}; for(int i = 0; i < 4; i++) { sprintf(t_str, "%02X", buffer[i]); m_apiResponse[i]->setText(String(t_str)); } where buffer[0] = 20; buffer[1] = 30; buffer[2] = 40; buffer[3] = 50; and m_apiResponse is a textbox. Even though string.format was also helpful, I rather choose the easiset way of doing it. I had done this in my C# as follows: Response1Box = buffer[0].ToString("X2"); Response2Box = buffer[1].ToString("X2"); Response3Box = buffer[2].ToString("X2"); Response4Box = buffer[3].ToString("X2"); It worked well and gave me the answer i wanted. But now I have come across a twisted version of it in my c++ app..... Here is the code: unsigned char buffer[8] = {}; char verString[64] = {}; m_msp430->WriteInternalCommand(cmd, 1, buffer); m_msp430->ReadInternalCommand(cmd, 4, buffer); sprintf(verString, "FPGA 0x42 Version (dd/mm/yyyy ID): %02d/%02d/20%02d %02d", ((buffer[3] & 0xF8) >> 3), (buffer[2] & 0x0F), ((buffer[2] & 0xF0) >> 4), (buffer[3] & 0x07)); m_versionString->setText(String(verString), false); Here m_versionString is a label and once this statement is executed, it prints e.g. FPGA 0x42 Version (dd/mm/yyyy ID): 00/00/2012 23. I tried it in C# as follows: // Description of VersionString label which displays private string _VersionString; public string VersionString { get { return _VersionString; } set { _VersionString = value; OnPropertyChanged("VersionString"); } } public void GetVersion() { int cmd = 0x0A42; Byte[] buffer = new Byte[8]; Byte[] verString = new Byte[64]; mComm.WriteInternalCommand(cmd, 1, ref buffer); mComm.ReadInternalCommand(cmd, 4, ref buffer); // Failing to figure out how to achieve it VersionString = Convert.ToString(verString); } How can i perform these operations and display it on my VersionString?? :) Please help :) A: Your C++ code is not equivalent to your C# code. You are masking and bit shifting each byte before your sprintf. There's no way that C# would know how to mask off the individual bytes to make your string. Not much time right now.. but basically something like this.. verString = String.Format("FPGA 0x42 Version (dd/mm/yyyy ID): {0}/{1}/20{2} {3}", ((buffer[3] & 0xF8) >> 3), (buffer[2] & 0x0F), ((buffer[2] & 0xF0) >> 4), (buffer[3] & 0x07)); or you can do it byte by byte without String.Format before calling convert
{ "pile_set_name": "StackExchange" }
Q: onClick in each list of recyclerView I've set 2 recyclerView in a layout and pass data in that recyclerView using arraylist. I am trying to set clickListener in each array list of different recyclerview. this is adapter public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder>{ Context context; int LayoutId; List<ItemModel> data; private OnNoteClickListener mOnNoteClickListener; public RecyclerAdapter(Context context, int layoutId, List<ItemModel> data, OnNoteClickListener onNoteClickListener) { this.context = context; LayoutId = layoutId; this.data = data; this.mOnNoteClickListener = onNoteClickListener; } public RecyclerAdapter(MainActivity mainActivity, int item_layout_vertical, List<ItemModel> topRecycleData) { } @NonNull @Override public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View myView = inflater.inflate(LayoutId,null); return new RecyclerViewHolder(myView, mOnNoteClickListener); } @Override public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) { final ItemModel singleItem = data.get(position); holder.imgTitle.setText(singleItem.getImgTitle()); holder.img.setImageDrawable(context.getResources().getDrawable(singleItem.getImgId())); } @Override public int getItemCount() { return data.size(); } public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ OnNoteClickListener onNoteClickListener; TextView imgTitle; ImageView img; public RecyclerViewHolder(@NonNull View itemView, OnNoteClickListener onNoteClickListener) { super(itemView); imgTitle = itemView.findViewById(R.id.imgTitle); img = itemView.findViewById(R.id.img); this.onNoteClickListener = onNoteClickListener; itemView.setOnClickListener(this); } @Override public void onClick(View view) { onNoteClickListener.onNoteClick(getAdapterPosition()); } } public interface OnNoteClickListener{ void onNoteClick(int positon); } } this is activity where recyclerview is shown: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Fetching View From XMl topRecyclerView = findViewById(R.id.topRecyclerView); bottomRecyclerView = findViewById(R.id.bottomRecyclerView); // Data For Top Recycler Views List<ItemModel> topRecycleData = new ArrayList<ItemModel>(); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 1")); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 2")); // Data For Bottom Recycler Views List<ItemModel> bottomRecycleData = new ArrayList<ItemModel>(); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 1")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 2")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 3")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 4")); // Setting Layouts To Recycler Views topRecyclerView.setLayoutManager(new GridLayoutManager(this,2)); bottomRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL,false)); // Creating Adapters RecyclerAdapter topAdapter = new RecyclerAdapter(MainActivity.this,R.layout.item_layout_vertical,topRecycleData); RecyclerAdapter bottomAdapter = new RecyclerAdapter(MainActivity.this,R.layout.item_layout_horizontal,bottomRecycleData); // Setting Adapters To Layouts topRecyclerView.setAdapter(topAdapter); bottomRecyclerView.setAdapter(bottomAdapter); } } If there was a single recyclerview then i hope i could do that but this time there are 2 recyclerview with 2 different arrylist in a home. so i am very confused how to call listener for two different arraylist of recyclerview. I want to make toast message when clicked in "for example" postion 2 on 1st recycler view and toast message when clicked in position 1 of 2nd recycler view. A: Here is the complete code with all the changes. I have tested your code and it runs fine. MainActivity Java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity{ RecyclerView topRecyclerView, bottomRecyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_main); // Fetching View From XMl topRecyclerView = findViewById(R.id.topRecyclerView); bottomRecyclerView = findViewById(R.id.bottomRecyclerView); // Data For Top Recycler Views List<ItemModel> topRecycleData = new ArrayList<ItemModel>(); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 1")); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 2")); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 3")); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 4")); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 5")); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 6")); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 7")); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 8")); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 9")); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 10")); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 11")); topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 12")); // Data For Bottom Recycler Views List<ItemModel> bottomRecycleData = new ArrayList<ItemModel>(); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 1")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 2")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 3")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 4")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 5")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 6")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 7")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 8")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 9")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 10")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 11")); bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 12")); // Setting Layouts To Recycler Views topRecyclerView.setLayoutManager(new GridLayoutManager(this,2)); bottomRecyclerView.setLayoutManager(new LinearLayoutManager(this)); // Creating Adapters (No need to send onNote) RecyclerAdapter topAdapter = new RecyclerAdapter (this,R.layout.item_layout_vertical,topRecycleData); RecyclerAdapter bottomAdapter = new RecyclerAdapter (this,R.layout.item_layout_horizontal,bottomRecycleData); // Setting Adapters To Layouts topRecyclerView.setAdapter(topAdapter); bottomRecyclerView.setAdapter(bottomAdapter); } } MainActivity XML Using a Scoll View and Linear Layout with weights on inner linear layouts to scale them equally on screen height. In your code, the top layout was getting hidden by bottom layout. A scroll view must contain a single child, that's why an extra Linear Layout is added as child of Scroll View. <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_alignParentBottom="true" android:layout_alignParentStart="true" android:layout_alignParentEnd="true" android:layout_alignParentTop="true" android:scrollbars="none" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:weightSum="2"> <LinearLayout android:layout_margin="5dp" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#4CE9D9" android:text="Header No 1" android:textSize="18sp" android:textColor="#000" android:padding="5dp"/> <android.support.v7.widget.RecyclerView android:id="@+id/topRecyclerView" android:layout_marginTop="5dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:id="@+id/bottomRecyclerViewLayout" android:layout_margin="5dp" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#4CE9D9" android:text="Header No 2" android:textSize="18sp" android:textColor="#000" android:padding="5dp"/> <android.support.v7.widget.RecyclerView android:id="@+id/bottomRecyclerView" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout> </ScrollView> item_layout_vertical xml Add an id to the top layout, this will be used to set the onclick listener later. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:id="@+id/verticalContainer" android:padding="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:id="@+id/img" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher"/> <TextView android:id="@+id/imgTitle" android:layout_marginTop="5dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:textColor="#000" android:textStyle="bold" android:text="Hello Dear Dibas"/> </LinearLayout> item_layout_horizontal xml Add an id to the top layout, this will be used to set the onclick listener later. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/horizontalContainer" android:orientation="vertical" android:padding="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:id="@+id/img" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher"/> <TextView android:id="@+id/imgTitle" android:layout_marginTop="5dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:textColor="#000" android:textStyle="bold" android:text="Hello Dear Dibas"/> </LinearLayout> RecyclerAdapter Java import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder>{ Context context; int LayoutId; List<ItemModel> data; public RecyclerAdapter(Context context, int layoutId, List<ItemModel> data) { this.context = context; LayoutId = layoutId; this.data = data; } @NonNull @Override public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View myView = inflater.inflate(LayoutId,null); return new RecyclerViewHolder(myView); } @Override public void onBindViewHolder(@NonNull RecyclerViewHolder holder, final int position) { final ItemModel singleItem = data.get(position); holder.imgTitle.setText(singleItem.getImgTitle()); holder.img.setImageDrawable(context.getResources() .getDrawable(singleItem.getImgId())); //checking which layout is in layoutId and adding onclick listener if (LayoutId == R.layout.item_layout_horizontal) { holder.horizontalLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //check which item is clicked here and proceed if(position==0) { //do something } else if(position==1) { //do something } else if(position==2) { //do something } //and so on to the list end } }); } else { holder.verticalLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //check which item is clicked here and proceed if(position==0) { //do something } else if(position==1) { //do something } else if(position==2) { //do something } //and so on to the list end } }); } } @Override public int getItemCount() { return data.size(); } public class RecyclerViewHolder extends RecyclerView.ViewHolder{ TextView imgTitle; ImageView img; LinearLayout horizontalLayout,verticalLayout; public RecyclerViewHolder(@NonNull View itemView) { super(itemView); imgTitle = itemView.findViewById(R.id.imgTitle); img = itemView.findViewById(R.id.img); //fetching the container views that are to be attached to the //recycler view and for adding onclick listeners //(because of multiple layouts for the same adapter) if(LayoutId==R.layout.item_layout_horizontal) horizontalLayout=itemView.findViewById(R.id.horizontalContainer); else verticalLayout=itemView.findViewById(R.id.verticalContainer); } } } Hope this helps. It is running fine. Add a toast in the click listener conditions to verify if they are working for the exact position. And important to note that position index starts from 0(first item) to so on.
{ "pile_set_name": "StackExchange" }
Q: Easy way to add a closing quote in an ellipsized over-flowed text I have a div with a text inside. If the text overflows it's div, It is shortened with an ellipsis at the end. What I want to do is to add a double-quote after it's ellipse so that it will look like this: "The quick bro..." Here's my code: <html><body> <div style="width: 100px;background: #CCCCCC;"> <div style="overflow:hidden; white-space: nowrap; text-overflow: ellipsis;">"The quick brown fox" </div></div> </body></html> Is there an easy way/technique to do this or do you need to create your own custom ellipsis instead? Thanks all! A: CSS text-overflow can be configured with custom characters, for example: .customEllipsis { overflow:hidden; white-space: nowrap; text-overflow: '…"'; } However, support is experimental and the above example will currently only work in Firefox. For cross-browser support you will have to modify the output in PHP (since the question is tagged with PHP) on the server or with JavaScript on the client. Update 2015-07-29 text-overflow is now fully supported by all modern browsers. Update 2016-07-01 It is possible that moving to the Blink web engine broke this as I would have tested it on Chrome - see this Blink defect. Also it doesn't look like it works in Edge. So there is currently no cross-browser solution using text-overflow: <string>. It gets worse because the <string> functionality is marked "at risk" so it could be dropped if "interoperable implementations are not found".
{ "pile_set_name": "StackExchange" }
Q: Почему [0] != "" и [] != "0" и [[]] != "0"? Просто было бы логично если бы [0] == "" т.к. обе части приводятся к нулю. Или ещё вопрос, почему [] != "0" и [[]] != "0" ведь тут так же обе части приводятся к нулю. http://dorey.github.io/JavaScript-Equality-Table/ console.log(Number([0])); console.log(Number("")); console.log(Number([])); console.log(Number([[]])); console.log(Number("0")); A: обе части приводятся к нулю Не приводятся. Массив приводится к строке, получаем две строки и сравниваются строки. А они, очевидно, разные. А вот если бы в правой части было число, то в сравнении строки и числа строка бы привелась к числу, из-за чего равенство бы выполнилось: console.log([] == "") console.log([] == 0) console.log([] == "0") console.log([0] == "") console.log([0] == 0) console.log([0] == "0")
{ "pile_set_name": "StackExchange" }
Q: Another beautiful integral (Part 2) One of the ways of calculating the integral in closed form is to think of crafitly using the geometric series, but even so it seems evil enough. $$\int_0^1\int_0^1\int_0^1\int_0^1\frac{1}{(1+x) (1+y) (1+z)(1+w) (1+ x y z w)} \ dx \ dy \ dz \ dw$$ Maybe you can guide me, bless me with another precious hints, clues. Thanks MSE users! Supplementary question: How about the generalization? $$\int_0^1\int_0^1\cdots\int_0^1\frac{1}{(1+x_1) (1+x_2)\cdots (1+x_n)(1+ x_1 x_2 \cdots x_n)} \ dx_1 \ dx_2 \cdots \ dx_n$$ A: This response will only address the $n=4$ case, $$I_{4}:=\int_{[0,1]^{4}}\frac{\mathrm{d}x\,\mathrm{d}y\,\mathrm{d}z\,\mathrm{d}w}{\left(1+x\right)\left(1+y\right)\left(1+z\right)\left(1+w\right)\left(1+xyzw\right)}.\tag{1}$$ According to WolframAlpha, the multiple integral $(1)$ above has the approximate numerical value $I_{4}\approx0.223076.$ Starting with the substitution $w=\frac{1-t}{1+xyzt}$, we can whittle the multiple integral down to the following double integral: $$\begin{align} I_{4} &=\small{\int_{0}^{1}\mathrm{d}x\int_{0}^{1}\mathrm{d}y\int_{0}^{1}\mathrm{d}z\int_{0}^{1}\frac{\mathrm{d}w}{\left(1+x\right)\left(1+y\right)\left(1+z\right)\left(1+w\right)\left(1+xyzw\right)}}\\ &=\small{\int_{0}^{1}\mathrm{d}x\int_{0}^{1}\mathrm{d}y\int_{0}^{1}\mathrm{d}z\int_{0}^{1}\frac{\mathrm{d}t}{\left(1+x\right)\left(1+y\right)\left(1+z\right)\left(2-t+xyzt\right)}}\\ &=\int_{0}^{1}\mathrm{d}x\int_{0}^{1}\mathrm{d}y\int_{0}^{1}\mathrm{d}z\,\frac{\ln{(2)}-\ln{\left(1+xyz\right)}}{\left(1+x\right)\left(1+y\right)\left(1+z\right)\left(1-xyz\right)}\\ &=\int_{0}^{1}\mathrm{d}x\int_{0}^{1}\mathrm{d}y\int_{0}^{xy}\mathrm{d}v\,\frac{\ln{\left(\frac{2}{1+v}\right)}}{\left(1+x\right)\left(1+y\right)\left(xy+v\right)\left(1-v\right)};~~~\small{\left[xyz=v\right]}\\ &=\int_{0}^{1}\mathrm{d}x\int_{0}^{x}\mathrm{d}u\int_{0}^{u}\mathrm{d}v\,\frac{\ln{\left(\frac{2}{1+v}\right)}}{\left(1+x\right)\left(x+u\right)\left(u+v\right)\left(1-v\right)};~~~\small{\left[xy=u\right]}\\ &=\int_{0}^{1}\mathrm{d}x\int_{0}^{x}\mathrm{d}v\int_{v}^{x}\mathrm{d}u\,\frac{\ln{\left(\frac{2}{1+v}\right)}}{\left(1+x\right)\left(x+u\right)\left(u+v\right)\left(1-v\right)}\\ &=\int_{0}^{1}\mathrm{d}v\int_{v}^{1}\mathrm{d}x\int_{v}^{x}\mathrm{d}u\,\frac{\ln{\left(\frac{2}{1+v}\right)}}{\left(1+x\right)\left(x+u\right)\left(u+v\right)\left(1-v\right)}\\ &=\int_{0}^{1}\mathrm{d}v\int_{v}^{1}\mathrm{d}u\int_{u}^{1}\mathrm{d}x\,\frac{\ln{\left(\frac{2}{1+v}\right)}}{\left(1+x\right)\left(x+u\right)\left(u+v\right)\left(1-v\right)}\\ &=\int_{0}^{1}\mathrm{d}v\int_{v}^{1}\mathrm{d}u\,\frac{\ln{\left(\frac{(1+u)^2}{4u}\right)}\ln{\left(\frac{2}{1+v}\right)}}{\left(1-u\right)\left(u+v\right)\left(1-v\right)}\\ &=\int_{0}^{1}\mathrm{d}u\int_{0}^{u}\mathrm{d}v\,\frac{\ln{\left(\frac{(1+u)^2}{4u}\right)}\ln{\left(\frac{2}{1+v}\right)}}{\left(1-u\right)\left(u+v\right)\left(1-v\right)}.\tag{2}\\ \end{align}$$ WolframAlpha's numerical approximation of the iterated integral obtained in the last line of $(2)$ is consistent with the original approximation stated above, so I am reasonably confident that I haven't made any errors so far. Continuing, transforming variables and changing the order of integration yields the following equivalent double integral representation of $I_{4}$: $$\begin{align} I_{4} &=\int_{0}^{1}\mathrm{d}u\int_{0}^{u}\mathrm{d}v\,\frac{\ln{\left(\frac{(1+u)^2}{4u}\right)}\ln{\left(\frac{2}{1+v}\right)}}{\left(1-u\right)\left(u+v\right)\left(1-v\right)}\\ &=\int_{0}^{1}\mathrm{d}u\int_{\frac{1-u}{1+u}}^{1}\mathrm{d}y\,\frac{\ln{\left(\frac{(1+u)^2}{4u}\right)}\ln{\left(1+y\right)}}{\left(1-u\right)\left(u+\frac{1-y}{1+y}\right)y\left(1+y\right)};~~~\small{\left[\frac{1-v}{1+v}=y\right]}\\ &=-\frac12\int_{0}^{1}\mathrm{d}x\int_{x}^{1}\mathrm{d}y\,\frac{\ln{\left(1-x^2\right)}\ln{\left(1+y\right)}}{xy\left(1-xy\right)};~~~\small{\left[\frac{1-u}{1+u}=x\right]}\\ &=-\frac12\int_{0}^{1}\mathrm{d}y\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1-x^2\right)}\ln{\left(1+y\right)}}{xy\left(1-xy\right)}.\tag{3}\\ \end{align}$$ Now, the dilogarithm function $\operatorname{Li}_{2}{\left(z\right)}$ for complex argument is traditionally defined via the integral representation $$\operatorname{Li}_{2}{\left(z\right)}:=-\int_{0}^{z}\frac{\ln{\left(1-t\right)}}{t}\,\mathrm{d}t;~~~\small{z\in\mathbb{C}\setminus(1,\infty)}.\tag{4}$$ The following indefinite integral may then be confirmed by differentiated both sides of the equation: $$\small{\int\frac{\ln{\left(c+dx\right)}}{a+bx}\,\mathrm{d}x=\frac{\operatorname{Li}_{2}{\left(\frac{b\left(c+dx\right)}{bc-ad}\right)}+\ln{\left(c+dx\right)}\ln{\left(\frac{d\left(a+bx\right)}{ad-bc}\right)}}{b}+\color{grey}{constant}.}\tag{5}$$ Next, splitting up the logarithm function of $x$ in the numerator and applying partial fraction decomposition to the rational part, we find $$\begin{align} I_{4} &=-\frac12\int_{0}^{1}\mathrm{d}y\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1-x^2\right)}\ln{\left(1+y\right)}}{xy\left(1-xy\right)}\\ &=-\frac12\int_{0}^{1}\mathrm{d}y\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1+x\right)}\ln{\left(1+y\right)}}{xy\left(1-xy\right)}\\ &~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1-x\right)}\ln{\left(1+y\right)}}{xy\left(1-xy\right)}\\ &=-\frac12\int_{0}^{1}\mathrm{d}y\,\ln{\left(1+y\right)}\int_{0}^{y}\mathrm{d}x\,\left[\frac{1}{1-xy}+\frac{1}{xy}\right]\ln{\left(1+x\right)}\\ &~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\,\ln{\left(1+y\right)}\int_{0}^{y}\mathrm{d}x\,\left[\frac{1}{1-xy}+\frac{1}{xy}\right]\ln{\left(1-x\right)}\\ &=-\frac12\int_{0}^{1}\mathrm{d}y\,\ln{\left(1+y\right)}\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1+x\right)}}{1-xy}\\ &~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1+x\right)}}{x}\\ &~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\,\ln{\left(1+y\right)}\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1-x\right)}}{1-xy}\\ &~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1-x\right)}}{x}\\ &=\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[-\int_{0}^{y}\mathrm{d}x\,\frac{y\ln{\left(1+x\right)}}{1-xy}\right]\\ &~~~~~+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}\\ &~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\,\ln{\left(1+y\right)}\int_{1-y}^{1}\mathrm{d}t\,\frac{\ln{\left(t\right)}}{1-y\left(1-t\right)};~~~\small{\left[1-x=t\right]}\\ &~~~~~+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\ &=\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[\operatorname{Li}_{2}{\left(y\right)}+\ln{\left(1-y\right)}\ln{\left(1+y\right)}-\operatorname{Li}_{2}{\left(\frac{y}{1+y}\right)}\right]\\ &~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\int_{1-y}^{1}\mathrm{d}t\,\frac{\left(\frac{y}{1-y}\right)\ln{\left(t\right)}}{1+\left(\frac{y}{1-y}\right)t}\\ &~~~~~+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\ &=\small{\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[\operatorname{Li}_{2}{\left(y\right)}+\ln{\left(1-y\right)}\ln{\left(1+y\right)}+\operatorname{Li}_{2}{\left(-y\right)}+\frac12\ln^{2}{\left(1+y\right)}\right]}\\ &~~~~~\small{-\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[\operatorname{Li}_{2}{\left(\frac{y}{y-1}\right)}-\operatorname{Li}_{2}{\left(-y\right)}-\ln{\left(1-y\right)}\ln{\left(1+y\right)}\right]}\\ &~~~~~+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\ &=\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[\operatorname{Li}_{2}{\left(y\right)}+\operatorname{Li}_{2}{\left(-y\right)}+\ln{\left(1-y\right)}\ln{\left(1+y\right)}\right]\\ &~~~~~+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}\\ &~~~~~\small{+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[\operatorname{Li}_{2}{\left(y\right)}+\frac12\ln^{2}{\left(1-y\right)}+\operatorname{Li}_{2}{\left(-y\right)}+\ln{\left(1-y\right)}\ln{\left(1+y\right)}\right]}\\ &~~~~~+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\ &=\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[\operatorname{Li}_{2}{\left(y\right)}+\operatorname{Li}_{2}{\left(-y\right)}+\ln{\left(1-y\right)}\ln{\left(1+y\right)}\right]\\ &~~~~~+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{2}{\left(1-y\right)}\ln{\left(1+y\right)}}{y}\\ &~~~~~+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\ &=\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}\\ &~~~~~+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{2}{\left(1-y\right)}\ln{\left(1+y\right)}}{y}\\ &~~~~~+\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}\ln^{2}{\left(1+y\right)}}{y}.\tag{6}\\ \end{align}$$ And so we have reduced our multiple integral to a sum of five single-variable polylogarithmic integrals. Instead of attempting to evaluate each of these in turn, we'll save much energy if we make a few rearrangements first. $$\begin{align} I_{4} &=\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}\\ &~~~~~+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{2}{\left(1-y\right)}\ln{\left(1+y\right)}}{y}\\ &~~~~~+\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}\ln^{2}{\left(1+y\right)}}{y}\\ &=\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\ &~~~~~+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{2}{\left(1-y\right)}\ln{\left(1+y\right)}}{y}\\ &~~~~~\small{+\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y^2\right)}-\ln^{3}{\left(1-y\right)}-\ln^{3}{\left(1+y\right)}-3\ln^{2}{\left(1-y\right)}\ln{\left(1+y\right)}}{3y}}\\ &=-\frac34\int_{0}^{1}\mathrm{d}y\,\frac{(-2)\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\ &~~~~~-\frac13\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y\right)}}{y}-\frac{1}{12}\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}\\ &~~~~~+\frac13\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y^2\right)}}{y}-\frac34\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{2}{\left(1-y\right)}\ln{\left(1+y\right)}}{y}\\ &=-\frac34\left[\operatorname{Li}_{2}{\left(-y\right)}^{2}\right]_{0}^{1}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\ &~~~~~\small{-\frac13\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y\right)}}{y}-\frac{1}{12}\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}+\frac13\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y^2\right)}}{y}}\\ &~~~~~-\frac18\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y^2\right)}-\ln^{3}{\left(\frac{1-y}{1+y}\right)}-2\ln^{3}{\left(1+y\right)}}{y}\\ &=-\frac34\left[\operatorname{Li}_{2}{\left(-1\right)}\right]^{2}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\ &~~~~~-\frac13\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y\right)}}{y}+\frac16\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}\\ &~~~~~+\frac{5}{24}\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y^2\right)}}{y}+\frac18\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(\frac{1-y}{1+y}\right)}}{y}\\ &=-\frac34\left[\operatorname{Li}_{2}{\left(-1\right)}\right]^{2}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\ &~~~~~-\frac13\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y\right)}}{y}+\frac16\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}\\ &~~~~~+\frac{5}{48}\int_{0}^{1}\mathrm{d}z\,\frac{\ln^{3}{\left(1-z\right)}}{z};~~~\small{\left[y=\sqrt{z}\right]}\\ &~~~~~-\int_{0}^{1}\mathrm{d}y\,\frac{\left[\frac12\ln{\left(\frac{1+y}{1-y}\right)}\right]^{3}}{y}\\ &=-\frac34\left[\operatorname{Li}_{2}{\left(-1\right)}\right]^{2}-\frac32\operatorname{Li}_{2}{\left(1\right)}\operatorname{Li}_{2}{\left(-1\right)}-\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}\\ &~~~~~-\frac{11}{48}\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y\right)}}{y}+\frac16\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}-\int_{0}^{1}\mathrm{d}y\,\frac{\left[\operatorname{arctanh}{\left(y\right)}\right]^{3}}{y}.\tag{7}\\ \end{align}$$ The first two logarithmic integrals can immediately be written as Nielsen generalized polylogarithms. It's also not difficult to reduce the third logarithmic integral to Nielsen polylogarithms: $$\begin{align} \int_{0}^{1}\mathrm{d}y\,\frac{\left[\operatorname{arctanh}{\left(y\right)}\right]^{3}}{y} &=\int_{0}^{1}\mathrm{d}y\,\frac{\left[\frac12\ln{\left(\frac{1+y}{1-y}\right)}\right]^{3}}{y}\\ &=-\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(\frac{1-y}{1+y}\right)}}{8y}\\ &=-\frac14\int_{0}^{1}\mathrm{d}x\,\frac{\ln^{3}{\left(x\right)}}{1-x^2};~~~\small{\left[\frac{1-y}{1+y}=x\right]}\\ &=-\frac18\int_{0}^{1}\mathrm{d}x\,\frac{\ln^{3}{\left(x\right)}}{1-x}-\frac18\int_{0}^{1}\mathrm{d}x\,\frac{\ln^{3}{\left(x\right)}}{1+x}\\ &=-\frac38\int_{0}^{1}\mathrm{d}x\,\frac{\ln^{2}{\left(x\right)}\ln{\left(1-x\right)}}{x}+\frac38\int_{0}^{1}\mathrm{d}x\,\frac{\ln^{2}{\left(x\right)}\ln{\left(1+x\right)}}{x}\\ &=\frac34\,S_{3,1}{\left(1\right)}-\frac34\,S_{3,1}{\left(-1\right)}.\tag{8}\\ \end{align}$$ This just leaves the dilogarithmic integral to evaluate. $$\begin{align} \int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y} &=-\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}}{y}\int_{0}^{1}\mathrm{d}x\,\frac{\ln{\left(1+yx\right)}}{x}\\ &=-\int_{0}^{1}\mathrm{d}x\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}\ln{\left(1+xy\right)}}{xy}\\ &=:-\int_{0}^{1}\mathrm{d}x\,\frac{J{\left(-x\right)}}{x}\\ &=-\int_{0}^{1}\mathrm{d}x\,\frac{S_{1,2}{\left(-x\right)}}{x}-\int_{0}^{1}\mathrm{d}x\,\frac{\operatorname{Li}_{3}{\left(-x\right)}}{x}\\ &=-S_{2,2}{\left(-1\right)}-\operatorname{Li}_{4}{\left(-1\right)}.\tag{9}\\ \end{align}$$ (See Appendix 2 for definition and evaluation of the auxiliary function $J{(a)}$ used above.) Putting everything together, we arrive at $$\begin{align} I_{4} &=-\frac34\left[\operatorname{Li}_{2}{\left(-1\right)}\right]^{2}-\frac32\operatorname{Li}_{2}{\left(1\right)}\operatorname{Li}_{2}{\left(-1\right)}\\ &~~~~~-\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}\\ &~~~~~-\frac{11}{48}\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y\right)}}{y}+\frac16\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}\\ &~~~~~-\int_{0}^{1}\mathrm{d}y\,\frac{\left[\operatorname{arctanh}{\left(y\right)}\right]^{3}}{y}\\ &=-\frac34\left[\operatorname{Li}_{2}{\left(-1\right)}\right]^{2}-\frac32\operatorname{Li}_{2}{\left(1\right)}\operatorname{Li}_{2}{\left(-1\right)}\\ &~~~~~+\frac32\,S_{2,2}{\left(-1\right)}+\frac32\operatorname{Li}_{4}{\left(-1\right)}\\ &~~~~~+\frac{11}{8}\,S_{1,3}{\left(1\right)}-S_{1,3}{\left(-1\right)}\\ &~~~~~-\frac34\,S_{3,1}{\left(1\right)}+\frac34\,S_{3,1}{\left(-1\right)}\\ &=\frac32\,S_{2,2}{\left(-1\right)}+\frac{11}{8}\,S_{1,3}{\left(1\right)}-S_{1,3}{\left(-1\right)}-\frac{7\pi^4}{480}.\\ \end{align}$$ Appendix 1. The Nielsen generalized polylogarithm may be defined for positive integer indices via the integral representation $$S_{n,p}{\left(z\right)}:=\frac{\left(-1\right)^{n+p-1}n}{n!\,p!}\int_{0}^{1}\frac{\ln^{n-1}{\left(t\right)}\ln^{p}{\left(1-zt\right)}}{t}\,\mathrm{d}t;~~~\small{n,p\in\mathbb{N}^{+}}.$$ Setting $n=1$, $$S_{1,p}{\left(z\right)}:=\frac{\left(-1\right)^{p}}{p!}\int_{0}^{1}\frac{\ln^{p}{\left(1-zt\right)}}{t}\,\mathrm{d}t;~~~\small{p\in\mathbb{N}^{+}}.$$ Setting $p=1$, $$S_{n,1}{\left(z\right)}=\frac{\left(-1\right)^{n}n}{n!}\int_{0}^{1}\frac{\ln^{n-1}{\left(t\right)}\ln{\left(1-zt\right)}}{t}\,\mathrm{d}t;~~~\small{n\in\mathbb{N}^{+}}.$$ Appendix 2. Define the real function $J:(-\infty,1]\to\mathbb{R}$ via the integral representation $$J{\left(a\right)}:=\int_{0}^{1}\frac{\ln{\left(1-y\right)}\ln{\left(1-ay\right)}}{y}\,\mathrm{d}y;~~~\small{a\le1}.$$ Then, for $a\le1$ we have $$\begin{align} J{\left(a\right)} &=\int_{0}^{1}\frac{\ln{\left(1-y\right)}\ln{\left(1-ay\right)}}{y}\,\mathrm{d}y\\ &=\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}}{y}\int_{0}^{1}\mathrm{d}x\,\frac{ay}{ayx-1}\\ &=-a\int_{0}^{1}\mathrm{d}y\int_{0}^{1}\mathrm{d}x\,\frac{\ln{\left(1-y\right)}}{1-ayx}\\ &=-\int_{0}^{1}\mathrm{d}x\int_{0}^{1}\mathrm{d}y\,\frac{a\ln{\left(1-y\right)}}{1-axy}\\ &=-\int_{0}^{1}\mathrm{d}x\,\frac{\operatorname{Li}_{2}{\left(\frac{ax}{ax-1}\right)}}{x}\\ &=\int_{0}^{1}\mathrm{d}x\,\frac{\frac12\ln^{2}{\left(1-ax\right)}+\operatorname{Li}_{2}{\left(ax\right)}}{x}\\ &=\frac12\int_{0}^{1}\mathrm{d}x\,\frac{\ln^{2}{\left(1-ax\right)}}{x}+\int_{0}^{1}\mathrm{d}x\,\frac{\operatorname{Li}_{2}{\left(ax\right)}}{x}\\ &=S_{1,2}{\left(a\right)}+\operatorname{Li}_{3}{\left(a\right)}.\\ \end{align}$$ A: From this paper page $105$ we have $$\overline{H}_n-\ln2=(-1)^{n-1}\int_0^1\frac{x^n}{1+x}dx$$ $$\Longrightarrow (\overline{H}_n-\ln2)^4=\int_{[0,1]^4}\frac{(xyzw)^n}{(1+x)(1+y)(1+z)(1+w)}\ dx\ dy\ dz\ dw$$ now multiply both sides by $(-1)^n$ then $\sum_{n=0}^\infty$ we get $$I=\int_{[0,1]^4}\frac{\ dx\ dy\ dz\ dw}{(1+x)(1+y)(1+z)(1+w)(1+xyzw)}=\sum_{n=0}^\infty(-1)^n(\overline{H}_n-\ln2)^4=S$$ Lets calculate $S$ $$S=\sum_{n=0}^\infty(-1)^n(\overline{H}_n-\ln2)^2\color{blue}{(\overline{H}_n-\ln2)^2}$$ $$=\sum_{n=0}^\infty(-1)^n(\overline{H}_n-\ln2)^2\left(\color{blue}{\int_0^1\int_0^1\frac{(xy)^n}{(1+x)(1+y)}dx\ dy}\right)$$ $$=\int_0^1\int_0^1\frac{dx\ dy}{(1+x)(1+y)}\left(\sum_{n=0}^\infty(\overline{H}_n-\ln2)^2(-xy)^n\right)$$ In the same paper, page $97$ Eq$(13)$ we have $$\sum_{n=0}^\infty(\overline{H}_n-\ln2)^2t^n=\frac{1}{1-t}\left(\operatorname{Li}_2(t)-2\operatorname{Li}_2\left(\frac{1+t}{2}\right)+\operatorname{Li}_2\left(\frac{1}{2}\right)+\ln^22\right)$$ Therefore, $$S=\int_0^1\int_0^1\frac{\operatorname{Li}_2(-xy)-2\operatorname{Li}_2\left(\frac{1-xy}{2}\right)+\operatorname{Li}_2\left(\frac{1}{2}\right)+\ln^22}{(1+x)(1+y)(1+xy)}\ dx\ dy,\qquad xy=u$$ $$=\int_0^1\int_0^x\frac{\operatorname{Li}_2(-u)-2\operatorname{Li}_2\left(\frac{1-u}{2}\right)+\operatorname{Li}_2\left(\frac{1}{2}\right)+\ln^22}{(1+x)(x+u)(1+u)}\ dx\ du$$ $$=\int_0^1\color{blue}{\int_u^1\frac{1}{(1+x)(x+u)}}\frac{\operatorname{Li}_2(-u)-2\operatorname{Li}_2\left(\frac{1-u}{2}\right)+\operatorname{Li}_2\left(\frac{1}{2}\right)+\ln^22}{1+u}\ dx\ du$$ $$=\int_0^1\color{blue}{\frac{\ln\left(\frac{(1+u)^2}{4u}\right)}{1-u}}\frac{\operatorname{Li}_2(-u)-2\operatorname{Li}_2\left(\frac{1-u}{2}\right)+\operatorname{Li}_2\left(\frac{1}{2}\right)+\ln^22}{1+u}\ du$$ now set $u=\frac{1-x}{1+x}$ $$\Longrightarrow S=-\frac12\int_0^1\frac{\ln(1-x^2)}{x}\left[\operatorname{Li}_2\left(-\frac{1-x}{1+x}\right)-2\operatorname{Li}_2\left(\frac{x}{1+x}\right)+2\operatorname{Li}_2\left(\frac{1}{2}\right)+\ln^22\right]\ dx$$ apply integration by parts $$\Longrightarrow S=\frac14\ln^22\zeta(2)+\frac12\int_0^1\frac{\operatorname{Li}_2(x^2)}{1-x^2}\left(\frac{\ln(1+x)}{x}-\ln2\right)\ dx$$ The latter integral was nicely calculated by Cornel here $$\int_0^1\frac{\operatorname{Li}_2(x^2)}{1-x^2}\left(\frac{\ln(1+x)}{x}-\ln2\right)\ dx$$ $$=\frac{1}{6}\ln ^42-\frac{7 }{2}\zeta (4)+\frac{7}{2}\ln2\zeta (3)-\frac{3}{2}\ln ^22\zeta (2)+4 \operatorname{Li}_4\left(\frac{1}{2}\right)$$ $$\Longrightarrow S=\frac{1}{12}\ln ^42-\frac{7 }{4}\zeta (4)+\frac{7}{4}\ln2\zeta (3)-\frac{1}{2}\ln ^22\zeta (2)+2 \operatorname{Li}_4\left(\frac{1}{2}\right)=I$$ A: A table for reference. For explanation, see here. Let $$I(n)=\int_{(0,1)^n} \frac{ \prod_1^n dx_i}{(1+\prod_1^n x_i)\prod_1^n (1+x_i)}$$ denote generalized integral OP mentioned, then: $$\small I(1)=\frac{1}{2},\ I(2)=\frac{\pi ^2}{24},\ I(3)=\frac{3 \log ^2(2)}{2}-\frac{\pi ^2}{24}$$ $$\small I(4)=2 \text{Li}_4\left(\frac{1}{2}\right)+\frac{7}{4} \zeta (3) \log (2)-\frac{7 \pi ^4}{360}+\frac{\log ^4(2)}{12}-\frac{1}{12} \pi ^2 \log ^2(2)$$ $$\small I(5)=-20 \text{Li}_4\left(\frac{1}{2}\right)-\frac{45}{4} \zeta (3) \log (2)+\frac{259 \pi ^4}{1440}+\frac{5 \log ^4(2)}{3}+\frac{5}{12} \pi ^2 \log ^2(2)$$ $$\small I(6)=-33\zeta(\bar5,1)+60 \text{Li}_6\left(\frac{1}{2}\right)+30 \text{Li}_4\left(\frac{1}{2}\right) \log ^2(2)+60 \text{Li}_5\left(\frac{1}{2}\right) \log (2)\\\small+\frac{771 \zeta (3)^2}{64}+\frac{35}{4} \zeta (3) \log ^3(2)-\frac{29 \pi ^6}{360}+\frac{5 \log ^6(2)}{6}-\frac{5}{8} \pi ^2 \log ^4(2)$$ $$\small I(7)=1729\zeta(\bar5,1)+\frac{35}{3} \pi ^2 \text{Li}_4\left(\frac{1}{2}\right)-3360 \text{Li}_6\left(\frac{1}{2}\right)-420 \text{Li}_4\left(\frac{1}{2}\right) \log ^2(2)-1680 \text{Li}_5\left(\frac{1}{2}\right) \log (2)-\frac{5397 \zeta (3)^2}{8}-\frac{315}{4} \zeta (3) \log ^3(2)+7 \pi ^2 \zeta (3) \log (2)-\frac{50813}{32} \zeta (5) \log (2)+\frac{1589281 \pi ^6}{362880}-\frac{1}{3} 14 \log ^6(2)+\frac{175}{36} \pi ^2 \log ^4(2)+\frac{4739 \pi ^4 \log ^2(2)}{1440}$$
{ "pile_set_name": "StackExchange" }
Q: Shift of discrete unit step function I have $x[n]$ which is discrete unit step function where for $n < 0$, $x[n] = 0$. For $n \geq 0 $, $x[n] = 1$. Now, if I have $x[n-4]$, the $x[n]$ is shifted to the right by $4$. Now, if I have $x[-n]$, then $x[n]$ is flipped. So then, when I have $x[4-n]$, then shouldn't it be the following: $n \leq -4, x[n] = 1\text{; } n > -4, x[n] = 0$? But the graph shows the following: What am I missing? Why is what I thought wrong? A: For the unit step function $x[n] = 1$ if $n\ge0$ and $x[n] = 0$ if $n<0$. Now, $x[4-n]=1$ if $4-n\ge 0$. So, $x[4-n]=1$ if $4 \ge n$. Thus for $n \le 4$, the function has value $1$ and $0$ otherwise, as shown in the graph.
{ "pile_set_name": "StackExchange" }
Q: Why am I getting RecursionError: maximum recursion depth exceeded? This is the code: def isEven (n): #function checks if the number is even or odd if (int(n)%2) == 0: True else: False def Edit(b,x,y): #function loops through the number m = str(b) for i in range(1, len(m)+1): if isEven(m[-i]): continue elif int(m[-i+(len(m))]) > 5: b = b + 1 else: b = b - 1 y = y + 1 x = x + 1 Edit(b,x,y) number = input() Number = int(number) caseNum = 0 moves = 0 Edit(Number,caseNum,moves) print('Case #' + str(caseNum) + ' : ' + str(moves)) I want to create a code that checks if there is an odd digit in a number and increments or decrements the number until there are no odd digits in the number. A: I'm not really clear on what output you're expecting, so assuming that you want no odd digits in a number(4567 -> 4468) You simply can do that by: n = [int(i) for i in input("Enter a number: ")] caseNum = 0 for i, x in enumerate(n): if x % 2 != 0: if x > 5: n[i] += 1 else: n[i] -= 1 caseNum += 1 print("".join(str(x) for x in n), "CaseNum: ", caseNum) You don't really need an Even function if you're having if-else in main program already. As of your code, if you're using the Even function, you need to return a the value True or False. def isEven (n): #function checks if the number is even or odd if int(n) % 2 == 0: return True else: return False You're getting the RecursionError as you're calling same function(looping it) without any stopping condition. Edit(b,x,y) This statement in your function is creating the issue and after a limit, python stops executing and gives you the error. If you can elaborate the use of caseNum and moves, I'd be able to add them in program.
{ "pile_set_name": "StackExchange" }
Q: DeMorgans Law Application I'm Trying to prove that ¬(p ↔ q) is equivalent to ¬p ↔ q. I have done the work for ¬p ↔ q and simplified it to (p ∨ q) ∧ ¬(p ∧ q) .....My trouble is on the other proposition how do i distribute that not(¬)? A: De Morgan's Law: $\neg(p\wedge q) \equiv \neg p\vee\neg q$ and $\neg(p\vee q)\equiv \neg p\wedge \neg q)$ So $\neg(p\leftrightarrow q)~{\equiv \neg((p\to q)\wedge(q\to p))\\\equiv\neg (p\to q)\vee\neg(q\to p)}$ Now, if you do not know how to negate a conditional, first use the equivalence $p\to q\equiv \neg p\vee q$. $~\\~\\~$ PS: Calling DeMorgan's Law "distributing the not" will only confuse you.
{ "pile_set_name": "StackExchange" }
Q: Preparing iPhone App for Distribution in Xcode 4.2 The iOS provision portal references are for a previous version of Xcode. It doesn't look like they've updated it for version 4.2. Does anyone know of a good step-by-step guide that is updated with the A: Open a project: Click menu Product > Archive Open Window > Organizer > Archives Select an archive Click Validate ... Click Distribute ...
{ "pile_set_name": "StackExchange" }
Q: Could Quirinus Quirrell have killed Harry using Avada Kedavra while hosting Voldemort? Because Voldemort had not been given a new body in which Harry's blood flowed (as would happen later in GoF), Quirinus Quirrel (Voldemort's temporary host in PS) could not touch Harry because of Lily Potter's protection. Does this mean that he would not have been able to use Avada Kedavra on him either? Since Lily's protection would cause any Killing Curse cast on Harry by Voldemort to rebound... A: I can't think of a canon answer (and no JKR info) BUT, it is plausible that Lily's protection is aimed at Voldemort's soul, independently of the body it is in (since Quirrell indeed couldn't touch Harry). Also, I don't know if it's accurate to say that Lily's protection would cause the curse to rebound vs. other outcomes.
{ "pile_set_name": "StackExchange" }
Q: Testing order of lines of text on web page - Rspec & Capybara in rails Maybe I am missing the obvious... I can easily test for the presence or absence of text on a web page. Is there a straightforward way to test for the order of items listed in a div or on a web page, say from top to bottom? So, if I am expecting This That The other thing And one more item ... to be displayed in that order. Is there a matcher or test method that can be invoked to check the web page content? It should fail if something like this were displayed: This The other thing That And one more item A: You could do it with CSS or XPath selectors: expect(page.find('li:nth-child(1)')).to have_content 'This' http://www.w3schools.com/cssref/sel_nth-child.asp Also see: http://makandracards.com/makandra/9465-do-not-use-find-on-capybara-nodes-from-an-array A: You could do something like this using RSpec Matchers/Index def items_in_order page.body.index('This').should < page.body.index('That') && page.body.index('That').should < page.body.index('The other thing') && page.body.index('The other thing').should < page.body.index('And one more item') end
{ "pile_set_name": "StackExchange" }
Q: span with onclick event inside a tag Sample code <a href="page" style="text-decoration:none;display:block;"> <span onclick="hide()">Hide me</span> </a> Since the a tag is over the span is not possible to click it. I try z-index but that didnt work A: <a href="http://the.url.com/page.html"> <span onclick="hide(); return false">Hide me</span> </a> This is the easiest solution. A: When you click on hide me, both a and span clicks are triggering. Since the page is redirecting to another, you cannot see the working of hide() You can see this for more clarification http://jsfiddle.net/jzn82/ A: Fnd the answer. I have use some styles inorder to achive this. <span class="pseudolink" onclick="location='https://jsfiddle.net/'"> Go TO URL </span> .pseudolink { color:blue; text-decoration:underline; cursor:pointer; } https://jsfiddle.net/mafais/bys46d5w/
{ "pile_set_name": "StackExchange" }
Q: Does an unbounded operator $T$ with non-empty spectrum have an unbounded spectrum? It's well known that the spectrum of a bounded operator on a Banach space is a closed bounded set (and non-empty)on the complex plane. And it's also not hard to find unbounded operators which their spectrum are empty or the whole complex plane. Conversely, suppose $T$ is an unbounded operator on a Banach space $E$,and has non-empty spectrum, does this imply that the $\sigma(T)$ is unbounded on $\mathbb{C}$ ? As far as I known, if $\sigma(T)$ is bounded,then it implied that $\infty$ is the essential singular point of the resolvent $(\lambda-T)^{-1}$, but I don't know how to form a contradiction. A: If the spectrum is bounded, then by means of holomorphic functional calculus we can extract a projection: $\displaystyle P = \frac{1}{2\pi i} \intop_\gamma (\lambda - T)^{-1} d\lambda$, where $\gamma$ encloses the spectrum. Intuitively, this should be thought of as separating the "bounded part" $TP$ (which is indeed bounded, since $T\left(\lambda-T\right)^{-1}=\lambda\left(\lambda-T\right)^{-1}-1$) and the part $T-TP$, which has empty spectrum on $\mathbb{C}$ when restricted to $\ker P$, but should be thought of as having a point at infinity, since indeed its inverse is a bounded operator with spectrum $\{0\}$. A: Weidmann gives a proposition to check for boundedness by investigating the numerical range (see proposition 2.51 in german version of Weidmann's 'Lineare Operatoren in Hilberträumen'). This makes sense since the numerical range is the natural object when studying boundedness rather than the spectrum... It states that for either (a) arbitrary operators on complex Hilbert spaces or (b) not necessarily densely defined symmetric operator operators on arbitrary Hilbert spaces we have: -->The operator is bounded iff its numerical range is bounded! For not necessarily bounded normal densely defined operators we have: (Relaxing to closed ones fails in general as seen in numerical range vs spectrum.) -->The spectrum is contained in the closure of the numerical range! So the scheme is as follows: $$A\text{ bounded}\iff\mathcal{W}(A)\text{ bounded}$$ $$N^*N=NN^*:\quad\sigma(N)\subseteq\overline{\mathcal{W}(N)}$$ But apart from that there's (unfortunately) nothing much to say I guess. By the way if you're more concerned about little subtlties like denseness etc. Weidmann is a good book for. He tries to keep these aspects always (annoyingly or luckily) in discussion.
{ "pile_set_name": "StackExchange" }
Q: Prohibit separating different fields into new lines in beamer I am using this template (https://www.latextemplates.com/template/jacobs-landscape-poster) which is based on beamerposter to create a conference poster. The bibliography list generated automatically separates different fields (author, title, journal etc.) into new lines which wastes a lot of space. I have tried several different bibliographystyle but the problem remains. Guess the origin is in the .sty files coming with the template but could not locate the spot to modify. Is there a way to disable such separation? Thanks. Please see comment for MWEB A: You could not find the linebreaks in the .sty file of your template, because they origin from beamer itself. For example the default definition for the title is \defbeamertemplate*{bibliography entry title}{default}{\par} which will start the title in a new paragraph. This can be changed with \setbeamertemplate{bibliography entry title}{} \documentclass[final]{beamer} \usepackage[scale=1.24]{beamerposter} % Use the beamerposter package for laying out the poster \usetheme{confposter} % Use the confposter theme supplied with this template \newlength{\sepwid} \newlength{\onecolwid} \newlength{\twocolwid} \newlength{\threecolwid} \setlength{\sepwid}{0.024\paperwidth} % Separation width (white space) between columns \setlength{\onecolwid}{0.22\paperwidth} % Width of one column \title{Unnecessarily Complicated Research Title} % Poster title \author{John Smith, James Smith and Jane Smith} % Author(s) \institute{Department and University Name} % Institution(s) \setbeamertemplate{bibliography entry article}{} \setbeamertemplate{bibliography entry title}{} \setbeamertemplate{bibliography entry location}{} \setbeamertemplate{bibliography entry note}{} \begin{document} \begin{frame}[t] \begin{columns}[t] \begin{column}{\onecolwid} Blabla \cite{Smith:2012qr} Blabla \cite{Smith:2013jd} \begin{block}{References} \bibliographystyle{plain} \bibliography{sample.bib} \end{block} \end{column} % End of the third column \end{columns} % End of all the columns in the poster \end{frame} % End of the enclosing frame \end{document}
{ "pile_set_name": "StackExchange" }
Q: Does event loop changes again after async function finishes all asynchronous calls? Let's consider this code: async function testFunction() { // event loop 1 - before any "await", we are still in original event loop, right? const result = await Promise.resolve('abc'); // event loop 2 - we have a new event loop return result; } // event loop 1 testFunction().then(result => { // event loop 2? Or new event loop? }) Does event loop changes again after async function done all asynchronous operations? Is the event loop right before return statement the same as in the then statement? And is there an easy way to check it? I'm working with some synchronous API that needs to be executed in the same event loop and I want to be sure it will work. EDIT: To make it more clear, this is the real life example: async function dbTransaction(tableName, transactionMode) { const db = await _dbPromise; return db.transaction([tableName], transactionMode).objectStore(tableName); } Can I use the transaction returned by this asynchronous function? Some related MDN info: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB#Adding_data_to_the_database And important quote: Now that you have a transaction you need to understand its lifetime. Transactions are tied very closely to the event loop. If you make a transaction and return to the event loop without using it then the transaction will become inactive. EDIT 2: One more thing - the answer is yes - the transaction is usable after const objectStore = await dbTransaction(DB_IMAGE, DB_OP_READWRITE). Only if I await something else I get TRANSACTION_INACTIVE_ERR error - which makes sense. So is it by design? Does it mean it is indeed in the same event loop iteration? A: A transaction is only valid on a given stack. When some asynchronous work is done, i.e. the browser gets a handler to indexedDB here: const db = await _dbPromise; a new stack is created and it continues till the end of that function. But apart from the main stack, there's also a microtask stack and on that stack go all callbacks from promises and observers. If a promise is marked as resolved while executing instructions from a given stack, it is immediately called after the main stack empties and a transaction is still available there. (You can think of stack + microtasks as one 'tick' of a loop after which javascript passes control back to the event loop that decides what to do next). So in your example: async function testFunction() { // tick 1 synchronous const result = await Promise.resolve('abc'); // tick 1 microtask 1 (up resolved through the execution of the stack) return result; } // tick 1 testFunction().then(result => { // tick 1 microtask 2 (resolved through the execution of microtask 1) }) You can get some info by checking performance panel: This video might clear what an event loop is and how it works: https://vimeo.com/254947206
{ "pile_set_name": "StackExchange" }
Q: Integral Calculus, Infinitesimal To integrate $y=f(x)$ from $a$ to $b$ we break the function into small rectangles of width $dx$. So the $n$-th rectangle will be at a distance of $n\,dx$ from $a$ on the $x$-axis. Let there be $t$ rectangles between $a$ and $b$. Therefore $b=a+t\,dx$. But $t\,dx$ will be very small for any positive Integer $t$ due to the properties of Infinitesimals. So how will it ever reach $b$? Do I have any misconceptions regarding calculus and infinitesimals? A: In his book Infinite Powers, Steven Strogatz mentions this exact issue which you are describing. He considers the difference between 'completed infinity' and 'potential infinity'. I will get to your particular issue soon, but first, I will describe a similar problem that helps pinpoint what is going on. As you know, division by zero is not allowed in mathematics. However, many people share in the false belief that $$ 1/0 = \infty $$ Why is this? A trained mathematician might revile at the above statement, but actually, it is very plausible; wrong, but plausible. Take a look at this: \begin{align} 1/0.1&=10 \\ 1/0.01&=100 \\ 1/0.001&=1000 \\ 1/0.0001&=10000 \\ 1/0.00001&=100000 \\ &\,\,\,\vdots \end{align} As $x$ approaches $0$, $1/x$ approaches infinity. Therefore, $1/0=\infty$. But wait, that's not what we have shown. What we shown is that as $x$ gets closer and closer to $0$, $1/x$ gets larger and larger. There is a crucial distinction between these two statements that is often glossed over in introductory calculus courses. Once you get to the case $1/0$, all kinds of paradoxes emerge, and so it is with good reason that $1/0$ is undefined. However, considering what $1/0$ may or may not be is not an entirely unfruitful exercise. To the contrary, it might reveal to us one of the most important tools in calculus: the limit. Let's take a look at the graph of $y=1/x$: As you can see, $1/x$ shoots off into the distance as $x$ gets closer and closer to $0$. We can't say what $1/0$ is; what we can say is that as $x$ gets closer and closer to $0$, $1/x$ gets larger and larger. This is formally written as $$ \lim_{x \to 0}\frac{1}{x}=\infty $$ But wait, that's not quite right either! $1/x$ only approaches infinity* when $x$ approaches $0$ from the positive end. What if $x$ is a negative number that is getting closer and closer to $0$? Then, $1/x$ approaches $-$infinity. Perhaps we could write that $$ \lim_{x \to 0}\frac{1}{x}=\pm\infty $$ but mathematicians like it if limits have a single, definite value. Therefore, both of the above statements are incorrect, and what we should be writing is this: $$ \lim_{x \to 0^+}\frac{1}{x}=\infty \text{ and } \lim_{x \to 0^-}\frac{1}{x}=-\infty $$ (The little '$+$' right next to the $0$ indicates that we are considering the case where $x$ is a positive number that is approaching $0$. Likewise, the '$-$' means $x$ is a negative number that is approaching $0$.) Don't worry if all of the little details don't make complete sense to you. Just try to remember these two key facts: In calculus, mathematicians work with limits. When trying to compute limits such as $1/x$ as $x$ approaches $0$, the fact that $1/0$ is undefined is neither here nor there. We are not trying to work out what happens when we 'get to zero'. Rather, we are looking at what happens as we move closer and closer to $0$, both from the positive and negative direction.** Now let's compare what we have learnt about limits with what we think we know about infinitesimals. The biggest problem with the concept of an infinitesimal in my mind is that they suggest that there is a 'smallest possible number'. Actually, when we are working with the standard real numbers, there is no such thing. This should be intuitively obvious: however low you go, you can always go lower. You might also be sympathetic to the idea that $$ 1/\text{infinitesimal}=\infty $$ Again, this is problematic, not least because it treats infinity as if it were a number. Therefore, we should be extremely cautious when someone mentions the words 'infinitesimal', or 'infinitely small'. Often when they do, they are using these terms as a mere shorthand for the limits we worked with earlier. For instance, if I write 'as $x$ becomes infinitely small, $1/x$ becomes infinitely large', then this would be rather sloppy, but it would also be generally understood by those well versed in the fundamentals of calculus. (I would warn against using such language though.) Other times when people mention infinitesimals they are talking about nonstandard analysis, in which the idea of an infinitesimal is formalised. But let's not get sidetracked. As far as I am concerned, 'infinitesimals' do not exist. This should be your view too. While infinitesimals may be intuitively appealing, we should always confirm that our intuitions are in line with reality. Otherwise, we are asking for trouble. Finally, we get to your question. If I understand correctly, you are asking about $$ \int_a^b f(x) \, dx $$ As you have already correctly pointed out, integrals are based upon splitting up a curve into many small rectangles, each with a certain width. Let's call this width $\Delta x$. We can approximate the area under the graph as $$ \sum_{a+\Delta x}^b f(x) \, \Delta x $$ Do not despair if the above expression looks unfamiliar to you. All it means is that each rectangle has a fixed width $\Delta x$. The length of each rectangle is dependent on the height of the curve at each point—hence why the length is $f(x)$, where $x$ is a variable that goes from $a$ to $b$. And of course, the approximation comes from summing the areas of the rectangles. To visualise this, here is an animation taken from Wikipedia: As the animation rightly suggests, the approximations become better as $\Delta x$ approaches $0$. This is where $dx$ steps in. You can imagine that if the rectangles have an infinitely small width, then the rectangles get the area exactly right. Historically, $dx$ was indeed used in this way to represent an infinitesimal change in $x$. However, modern standards of rigour have rendered this interpretation of $dx$ largely obsolete. Because of all the paradoxes they can create, infinitesimals are best avoided in formal mathematics, at least within the context of 'standard' calculus. Instead, $dx$ should be seen as part of a shorthand for a limit expression. For example, if $y=f(x)$, then $dy/dx$ is a shorthand for $$ \lim_{\Delta x \to 0}\frac{\Delta y}{\Delta x}=\lim_{\Delta x \to 0}\frac{f(x+\Delta x)-f(x)}{\Delta x} $$ In this case of integrals, we can imagine that $$ \int_a^b f(x) \, dx $$ represents the sum of infinitely many infinitely small rectangles of width $dx$. But even just writing this makes me cringe. The fact that the number of rectangles gets bigger and bigger does not mean that there are infinitely many rectangles (hence the difference between 'potential infinity' and 'actual infinity'). And judging by the sentiments you expressed in your question, infinitesimals may be not the right approach for you either. You are absolutely right about the apparent paradox created if we interpret the width of each rectangle as truly 'infinitesimal'. The formal definition of an integral sidesteps this issue entirely by defining $\int_a^b f(x) \, dx$ as the limit of the sum of the areas of the rectangles as $\Delta x$ approaches $0$: $$ \lim_{\Delta x \to 0}\sum_{a+\Delta x}^b f(x) \, \Delta x $$ A pattern seems to have emerged. Every time you catch yourself thinking about infinitesimals, think abouts limits! You don't need to throw your intuition out of the window—if you find infinitesimals useful for building up your mental picture of calculus, then it would be unwise for you to do away with them. Equally though, never forget what it is really going on. *Be careful with the phrase 'approaches infinity'. This has a very different meaning to 'approaching $5$', say. If I say $x$ is approaching infinity, then all I mean is that $x$ is getting bigger and bigger. That's it. **In this particular case, the limit 'does not exist', as we get end up with two different answers: $+\infty$ and $-\infty$, depending on whether we approach $0$ from 'above' or 'below'. Therefore, we have to restrict ourselves to considering the case where $x$ approaches $0$ solely from the positive end, or solely from the negative end.
{ "pile_set_name": "StackExchange" }
Q: UserControl inside ContentControl is it possible to insert some UserControl into ContentControl? but I need to dynamically decide which UserControl I need to insert (like with DataTemplateSelector). A: It is possible. You need to have a ContentControl let's say like this one: <ContentControl Name="ContentMain" Width="Auto" Opacity="1" Background="Transparent" ></ContentControl> And then you need to have your different UserControl like these two: <UserControl x:Class="MyNamespace.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" > <Grid Margin="5,5,5,10" > <Label Name="labelContentOne" VerticalAlignment="Top" FontStretch="Expanded" /> </Grid> <UserControl x:Class="MyNamespace.UserControl2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" > <Grid Margin="5,5,5,10" > <Label Name="labelContentTwo" VerticalAlignment="Top" FontStretch="Expanded" /> </Grid> If you want to change them dinamically you only need to change the Content of the ContentMain ContentControl programatically: // Initialize the content UserControl1 u1 = new UserControl1(); ContentMain.Content = u1; // Let's say it changes on a button click (for example) private void ButtonChangeContent_Click(object sender, RoutedEventArgs e) { UserControl2 u2 = new UserControl2(); ContentMain.Content = u2; } More or less that's the idea... ;) A: Yes, you can place any object in ContentControl.Content, however depending on what determines what UserControl you want, there are multiple ways of accomplishing this. My personal favorite is to go with a DataTrigger that determines the ContentControl.ContentTemplate based on some condition Here's an example that bases the ContentControl.Content on a ComboBox's selected value: <DataTemplate DataType="{x:Type DefaultTemplate}"> <TextBlock Text="Nothing Selected" /> </DataTemplate> <DataTemplate DataType="{x:Type TemplateA}"> <localControls:UserControlA /> </DataTemplate> <DataTemplate DataType="{x:Type TemplateB}"> <localControls:UserControlB /> </DataTemplate> <Style TargetType="{x:Type ContentControl}" x:Key="MyContentControlStyle"> <Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" /> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=MyComboBox, Path=SelectedValue}" Value="A"> <Setter Property="ContentTemplate" Value="{StaticResource TemplateA}" /> </DataTrigger> <DataTrigger Binding="{Binding ElementName=MyComboBox, Path=SelectedValue}" Value="B"> <Setter Property="ContentTemplate" Value="{StaticResource TemplateB}" /> </DataTrigger> </Style.Triggers> </Style>
{ "pile_set_name": "StackExchange" }
Q: How to test if an img tag points to an existing image? I'm using Cucumber and Capybara for BDD on a RoR application. I have the following feature Feature: List profiles In order to know that the people behind the profiles are real people As a lurker I want to be able to find who is registed and see their profile picture Background: Profiles have been added to the database, some with picture attached Given some profiles exist And I am on the home page Scenario: Search by city, avatars should be there When I search for a city with profiles Then I should see some result profiles with avatar The underlying Capybara steps file contains: Then /^I should see some result profiles with avatar$/ do page.should have_css("#profile_search_results .profile img.avatar", :count => some_profiles) end This step checks that the page contains <div id="#profile_search_results> <img class="avatar" src="" /> BUT... I also want to check if the image exists (it is not a broken image). How can I do this in my Capybara steps? A: The way to check, without having to use Selenium or any other drivers, was to extract the src attribute from the img element (Thanks MrDanA), and check the status code after visiting that URL: page.should have_css("#profile_search_results .profile img.avatar", :count => some_profiles) img = page.first(:css, "#profile_search_results .profile img.avatar") visit img[:src] page.status_code.should be 200
{ "pile_set_name": "StackExchange" }
Q: if Outlook conditional statement Is there a conditional statement for all Outlook versions? I found this for version 9: <!–[if gte mso 9]> <![endif]–> A: I'm on Linux at the moment and can't test, but perhaps something like [if mso]?
{ "pile_set_name": "StackExchange" }
Q: typedef struct in header and dereference pointer to incomplete type I'm quite rusty in C, but I think I'm having issues understanding the proper usage of using typedefs in headers, defining the actual struct's structure in the implementation file, and then using the struct in a third file. I wrote a queue data-structure that has a type defined as such: typedef struct queue { int count; qnode_t *head; qnode_t *tail; } queue_t; Where qnode_t is a struct that's only used within the queue's implementation file. Within my header I have this: typedef struct queue queue_t; When using this queue_t type within another file I'm attempting to get the queue's length like this: queue_t *work_queue; ... int length = work_queue->count; However, on that line where I'm looking up count I get the compiler error: dereferencing pointer to incomplete type I've been doing a lot of research about how to properly define types in C, but I think I just keep confusing myself more and more instead of getting clarity since many examples are either conflicting with other resources or are too simplified for me to put to practical use. Would I be getting this error because the 'count' variable within the struct isn't defined there? If this is the case, then can I define the struct in BOTH the implementation and header? If so, can the header only have the count variable defined since the head & tail should be hidden/private? (I miss OOP) Should I just be making another function that takes a queue_t* and returns its length as size_t? A: you can only dereference defined types, not declared types. Type declarations are useful to type-check opaque pointers, but object fields are not visible, cannot be accessed. You need to move the typedef into the header to access fields of your queue object. Edit: from the questions/answers below: Yes, two identical struct definitions are seen as the same typedef. You could omit fields if you never had both definitions in the same source file, but don't do it, that leads to bugs and maintenance confusion. Better to use a naming convention eg names starting with underscores are internal. The convention is to define the struct in the header then include the same header in the implementation file. This keeps the published layout in sync with the implementation
{ "pile_set_name": "StackExchange" }
Q: Bootstrap navbar styling issue This is a rather minor issue, but enough to drive me up a wall. Sometimes I swear I have OCD, though not diagnosed. What's going on is that I'm working on a company Web site (starting my own company). I am using the navbar-default, and customizing it to suit the color scheme I want. One issue, though (see linked pic below): screenshot of issue This is the right-most point on my navbar. You can clearly see that there's about a 15px space at the end there that is not the same color as the rest of the navbar. It is a light grey (from the default Bootstrap styling) rather than the white (my customizations). I'm currently using an inline CSS style to try and figure out which class is causing this, but can't seem to do so. Please help? Code of navbar: <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#s2s-navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/"><img src="img/s2s-logo-brand.png" /></a> </div> <div class="collapse navbar-collapse" id="s2s-navigation"> <ul class="nav navbar-nav navbar-right"> <li class="active"><a id="home" href="pages/home">Home <span class="sr-only">(current)</span></a></li> <li><a id="about" href="pages/about">About</a></li> <li><a id="programs" href="pages/programs">Programs</a></li> <li><a id="contact" href="pages/contact">Contact</a></li> <li><a id="help" href="pages/help">Help</a></li> <li><a id="legal" href="pages/legal">Legal</a></li> </ul> </div> CSS (as appropriate to the situation): #s2s-navigation { background: #FFFFFF; } a#home, a#about, a#programs, a#contact, a#help, a#legal { color: #3BBEFF; } (Yes, I realize I could have wrote that a bit better.) A: .container-fluid Has a default padding of 15px This is wrapped around your styled navigation. Style a higher level container such as `.navbar-default'
{ "pile_set_name": "StackExchange" }
Q: On OSX and JVM 7, FileChannel.open seems to be broken On OSX with JVM 7, I am seeing that FileChannel.open with CREATE_NEW doesn't seem to comply with the docs. The code below, I would expect to create a new file, and only fail if it can't (permissions, disk issue) or that the file already exists. scala> FileChannel.open(new File("/tmp/doesnotexist").toPath, StandardOpenOption.CREATE_NEW) java.nio.file.NoSuchFileException: /tmp/doesnotexist at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86) at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102) at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107) at sun.nio.fs.UnixFileSystemProvider.newFileChannel(UnixFileSystemProvider.java:177) at java.nio.channels.FileChannel.open(FileChannel.java:287) at java.nio.channels.FileChannel.open(FileChannel.java:334) ... 32 elided scala> val path = new File("/tmp/doesnotexist") path: java.io.File = /tmp/doesnotexist scala> path.createNewFile() res9: Boolean = true scala> FileChannel.open(path.toPath, StandardOpenOption.CREATE_NEW) res10: java.nio.channels.FileChannel = sun.nio.ch.FileChannelImpl@19fed8d0 scala> FileChannel.open(path.toPath, StandardOpenOption.CREATE_NEW) res11: java.nio.channels.FileChannel = sun.nio.ch.FileChannelImpl@5c6ff75 scala> FileChannel.open(path.toPath, StandardOpenOption.CREATE_NEW) res12: java.nio.channels.FileChannel = sun.nio.ch.FileChannelImpl@1fa547d1 Here is the Java that I am using $ java -version java version "1.7.0_55" Java(TM) SE Runtime Environment (build 1.7.0_55-b13) Java HotSpot(TM) 64-Bit Server VM (build 24.55-b03, mixed mode) Is this a doc (or interpretation of doc) issue, or a bug on OSX (maybe even linux? Not tested yet)? A: You must specify WRITE along with CREATE_NEW. I just tested this on my OS X for you, and it works as expected: FileChannel.open(Paths.get("/tmp/doesnotexist"), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
{ "pile_set_name": "StackExchange" }
Q: Why should I choose a 401(k) or IRA over a standard brokerage account? 401(k)'s and other retirement accounts have limits on restrictions on when your money can be withdrawn. But let's say I score a job making a huge sum, can save a lot, and want to retire decades early. I'm aware that there are yearly contribution limits for 401(k)s and IRAs, and I am also aware a reason for contributing to a 401(k) would be a company match. Disregarding those facts, why wouldn't I want to open a standard brokerage account and invest as much of my money as I want as I see fit? The expense ratios would likely be lower, and while there would likely be trading fees, I plan to invest, rather than actively trade. A: It is not an either/or decision. If you "want to retire decades early", then you will need to have a taxable account anyway, as you won't be able to stuff enough money into the tax-advantaged accounts to meet that goal. And if you are "making a huge sum", then you will be in a high tax bracket and so the tax advantages of saving into a 401K or IRA will be substantial. So, max out your 401K/IRA, and then save the rest into the taxable brokerage account. When you retire at 39, live off your taxable account until you are old enough to tap the other ones without penalty. Unless you plan to die decades early, as well as retire decades early. In that case, you can bypass the 401K/IRA.
{ "pile_set_name": "StackExchange" }
Q: Transition loading message in jquery mobile I have a problem: This is my script, and it is called on a click $("#next").live("click", function() { $.mobile.loading( 'show', { text: 'loading', textVisible: true, theme: 'b', html: "" }); $('.giocatore').remove(); var pagina = parseInt($('#home').attr('pagina')); $('#home').attr('pagina',pagina+1); $('#back').append('<a id="prev" data-role="button" data-theme="a" href="" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">Prec</a>').trigger('create'); caricalista(); }); It does something to my webpage. I want that during the time it does something, the page shows me a loading message or some transition like the "pop" when i pass from page to page in jquery mobile. Now with my code the page display me the loading message but it remain also after the script is executed Can anyone help me? A: You can use a custom event. after you done with your work just trigger an announcement that it is done. Add this line to very last of your existing function: $(document).trigger('customEvent'); now outside of the function make a subscription to that announcement: $(document).on('customEvent', function () { // hide your loading message }); hope this help
{ "pile_set_name": "StackExchange" }
Q: Is the swap algorithm in this book correct? I am reading the book on Algorithms: Design and Analysis, by Harsh Bhasin, and I doubt if I understand section "5.3.2 Reversing the Order of Elements of a Given Array", where it is written: "In order to reverse the order of elements of an array, the following procedure is employed.", but to me it does not seem that the given "procedure" ever changes anything, possibly what am I missing please? This is the mentioned "procedure": //temp is a temporary variable //i is the counter for(i=0; i<n; i++) { temp = a[i]; a [i] = a [n-i-1]; a [n-i-1] = temp; } I came up with my own in JS as following, please tell me if I am correct: let a = [1,2,3,4,5]; let limit = Math.ceil(a.length/2); let a_length = a.length; let temp; for(let i=0;i<limit;i++){ temp = a[i]; a[i] = a[a_length-i-1]; a[a_length-i-1] = temp; } A: You are right, it should be i < n / 2 for the first loop, i.e. you should only perform the swaps on the first half of the array in order to reverse the array. By the way, you can just use Math.floor rather than Math.ceil for the JS code, i.e. the index i just needs to be less than the floor of $n/2$. Using your ceiling version is still correct, but just does an unnecessary swap of the middle element with itself when $n$ is odd (e.g. if $n=3$ and the array is $[2,4,6]$, then using ceiling will swap the $4$ with itself, which is redundant).
{ "pile_set_name": "StackExchange" }
Q: why the regression doesnt work? (MATLAB) I have a accelerometer signal as below: and I have a walking signal as below: I tried to regress these two signal using regression. Here is the code: regMat=zeros(size(walkVec,1),size(walkVec,2)); for i=1:size(data,1) b=regress(walkAcc', walkVec(i,:)'); regMat(i,:)=walkVec(i,:)-repmat(b,1,length(walkAcc)); regData(i,:)=[data(i,1:(ipt(1)-1)),regMat(i,:), data(i, (ipt(2)+1):size(data,2) ) ]; end figure(1),hold on, plot(data(1,:),'r'), plot(regData(1,:)), title ('regressed (b) and raw(r) ') legend('raw','regressed') xlabel('samples') ylabel('Intensity') and here is the reslts: as you can see the regression doesnt really work. Do you have any idea why and how I can fix it? Thanks a lot and kind Regards A: Check if regData has any data in the first column. This can also happen if one data is several magnitudes higher or lower. It becomes negligible in the same chart. I tried your code with dummy data and it works.
{ "pile_set_name": "StackExchange" }
Q: Nuances of JavaScript Prototyping In Chrome when i'm doing this: var A = function(){}; A.prototype = { a:1,b:2 }; var aInst = new A; aInst.a = 11; console.log(aInst); I see this in console: I didn't see Objects with two properties with the same name ("a") before, something wrong with my Chrome? Here: http://jsfiddle.net/4Zws3/1/ A: One a is an instance property, the other is a value of the prototype object. I'm actually seeing this in Chrome:
{ "pile_set_name": "StackExchange" }
Q: Get Previous 12 months name/id from current month Can any one help me in getting the last 12 months names from the current date (month). I want this query in slq server. A: You can use common table expression for your solution: ;WITH DateRange AS( SELECT GETDATE() Months UNION ALL SELECT DATEADD(mm, -1, Months) FROM DateRange WHERE Months > DATEADD(mm, -11, GETDATE()) ) SELECT DateName(m, Months) AS Months, Month(Months) AS ID FROM DateRange shows previous months in the order: Months ID ------------------------------ ----------- January 1 December 12 November 11 October 10 September 9 August 8 July 7 June 6 May 5 April 4 March 3 February 2 A: Requires sql-server 2008 select datename(m,dateadd(m,-a,current_timestamp)) monthname, datepart(m,dateadd(m,-a,current_timestamp)) id from (values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)) x(a) Result: monthname id December 12 November 11 October 10 September 9 August 8 July 7 June 6 May 5 April 4 March 3 February 2 January 1
{ "pile_set_name": "StackExchange" }
Q: Android : How to get just two digit after the point in decimal value ? dont want to trunc the value How to get the double value that is only two digit after decimal point. For example if the a = 190253.80846153846 then the result value should be like a = 190253.80 Try: I have try with this: public static DecimalFormat twoDForm = new DecimalFormat("#0.00"); in code a = Double.parseDouble(twoDForm.format(((a)))); But i got the value like 190253.81 instead of that i want 190253.80 So what should i have to change for it ?? A: Because Math.round() Returns the closest int to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type int. Use Math.floor() Example public static double roundMyData(double Rval, int numberOfDigitsAfterDecimal) { double p = (float)Math.pow(10,numberOfDigitsAfterDecimal); Rval = Rval * p; double tmp = Math.floor(Rval); System.out.println("~~~~~~tmp~~~~~"+tmp); return (double)tmp/p; } Complete Source code class ZiggyTest2{ public static void main(String[] args) { double num = 190253.80846153846; double round = roundMyData(num,2); System.out.println("Rounded data: " + round); } public static double roundMyData(double Rval, int numberOfDigitsAfterDecimal) { double p = (float)Math.pow(10,numberOfDigitsAfterDecimal); Rval = Rval * p; double tmp = Math.floor(Rval); System.out.println("~~~~~~tmp~~~~~"+tmp); return (double)tmp/p; } } A: Try this, make a object of BigDecimal double a = 190253.80846153846; BigDecimal bd = new BigDecimal(a); BigDecimal res = bd.setScale(2, RoundingMode.DOWN); System.out.println("" + res.toPlainString()); A: With no libraries: a = (float) (((int)(a * 100)) / 100.0f); or, for double: a = (double) (((int)(a * 100)) / 100.0);
{ "pile_set_name": "StackExchange" }
Q: Is it possible to seed the release revision for a release plan? We're migrating over from another build tool where relied on the CI to maintain a release version that increments based on a given pattern. In VSTS, the release revision id autoincrements from 1, but we deploy to targets that require a newer version number than the current one. I'd really rather not create hundreds of fake releases to push the version number up or have to manage the version number myself. Is there a way to seed the release version with a starting number? Or, alternatively, is it possible for a release to modify a release plan's variable (so that the changed value is available to future releases)? A: You can define custom variables, that enable you to do this. To view, edit, and add new release definition variables, open the Variables tab of a release definition.
{ "pile_set_name": "StackExchange" }
Q: Setting a global variable to do a function I am trying to set a global variable of 'help' to display a function that I have in my code. The goal is anytime the user types in the word 'help' I can display my table I have created. The function is called table() that I want to display. My code is as follows: def table(): header=(" Operation Command-line Format") underline=("_________ ___________________") meat=("Union set1&set2 \n Intersection set1|set2 \n Difference set1-set2 \n Symmetric difference set1 ^ set2 \n Cartesian product set1 X set2 \n Subset set1<=set2 \n Proper subset set1<set2 \n Super set set1=>set2 \n Proper super set set1>set2 \n Cardinality card set1 \n Membership-in xE set1 where x is single element\n Membership-not-in x!Eset1 where x is single element\n Power set power set1\n Display this table help") print(header, "\n",underline,"\n",meat) def intro(): firstChoice=input("Would you like to get the sets from a file or input your own? \n Press 1 for from file \n Press 2 to input your own") if input is 'help': table() if firstChoice== '1': fileChoice=input("Please enter the fle you would like to open") with open(fileChoice, 'r+') as f: z=f.readlines() length=len(z) try: if z != len(z): fileSet1=z[length-length] if length-length != " ": fileSet1=fileSet1.strip('\n') fileSet1=str(fileSet1) fileSet1.split(',') fileSet1=set([fileSet1]) fileSet2=z[length-length+1] if length-length+1 != " ": fileSet2=fileSet2.strip('\n') fileSet2=str(fileSet2) fileSet2.split(',') fileSet2=set([fileSet2]) fileSet3=z[length-length+2] if length-length+2 != " ": fileSet3=fileSet3.strip('\n') fileSet3=str(fileSet3) fileSet3.split(',') fileSet3=set([fileSet3]) fileSet4=z[length-length+3] if length-length +3 != " ": fileSet4=fileSet4.strip('\n') fileSet4=str(fileSet4) fileSet4.split(',') fileSet4=set([fileSet4]) print ("This is fileSet1 \n",fileSet1) print ("This is fileSet2 \n",fileSet2) print ("This is fileSet3 \n",fileSet3) print ("This is fileSet4 \n",fileSet4) except: try: print ("This is fileSet1 \n",fileSet1,"\nThis is fileSet2 \n",fileSet2,"\nThis is fileSet3 \n",fileSet3) except: print ("This is fileSet1 \n",fileSet1,"\nThis is fileSet2 \n",fileSet2) f.close() elif firstChoice== '2': keep_going= 'yes' userSet=input("Please enter the set you would like to use. " ) userSet1=userSet.split(',') userset1=set(userSet1) print("User set 1 ", userset1) keep_going=input("would you like to go again? Please respond with yes or no") while keep_going == 'yes': userSet=input('what other set would you like to use? ') userSet2=userSet.split(',') userset2=set(userSet2) print ("user set 2 ", userset2) keep_going=input ("Would you like to use another set too? ") if keep_going== 'yes': userSet=input("Th other set you would like to use?") userSet3=userSet.split(',') userset3=set([userSet3]) print("user set 3 ", userset3) keep_going=input("would you like to keep going? ") if keep_going== 'yes': userSet=input("Th other set you would like to use?") userSet4=userSet.split(',') userset4=set([userSet4]) print("user set 4 ", userset4) keep_going==input("Another one?") if keep_going == 'yes': print ("i don't think we need another set") keep_going='no' firstSet=input("which set would you like to use for operations \nplease type in userset1,userset2, userset3, userset4 or \n fileSet1,fileSet2,fileSet3 or fileSet4 ") if firstSet == "userset1": set1=userset1 print ("this is set1",set1) elif firstSet =="userset2": set1=userset2 print ("this is set1",(set1)) elif firstSet =="userset3": set1=userset3 print ("this is set1",(set1)) elif firstSet =="userset4": set1=userset4 print ("this is set1",(set1)) elif firstSet =="fileSet1": set1=fileSet1 print ("this is set1",(set1)) elif firstSet =="fileSet2": set1=fileSet2 print ("this is set1",(set1)) elif firstSet =="fileSet3": set1=fileSet3 print ("this is set1",(set1)) elif firstSet =="fileSet4": set1=fileSet4 print ("this is set1",(set1)) else: print ('your bad') secondSet=input("What other set would you like to use for operations \n please type in userset1,userset2, userset3, userset4, setFile ") if secondSet == "userset1": set2=userset1 print ("this is set2",set2) elif secondSet =="userset2": set2=userset2 print ("this is set2",(set2)) elif secondSet =="userset3": set2=userset3 print ("this is set2",(set2)) elif secondSet =="userset4": set2=userset4 print ("this is set2",(set2)) elif secondSet =="fileSet1": set2=fileSet1 print ("this is set1",(set1)) elif secondSet =="fileSet2": set2=fileSet2 print ("this is set1",(set1)) elif secondSet =="fileSet3": set2=fileSet3 print ("this is set1",(set1)) elif secondSet =="fileSet4": set2=fileSet4 print ("this is set1",(set1)) else: print ('your bad') table() commandinput=input("please select the operation you would like to do") commandinput=commandinput.split() if '&' in commandinput: union=set1.union(set2) print(union) elif '|' in commandinput: intersetction=set1.intersection(set2) print(intersection) elif '-' in commandinput: difference=set1/difference(set2) print(difference) elif '^' in commandinput: symmetric=set1.symmetric_difference(set2) print(symmetric) elif 'X' in commandinput: print ("HIGH") elif '<=' in commandinput: subset=set2.issubset(set1) print(subset) elif '<' in commandinput: print ("HIGH") elif '=>' in commandinput: subset=set2.issuperset(set1) print(subset) elif '>' in comandinput: print ("HIGH") elif 'card' in commandinput: length=len(set1) print(length) elif 'E' in commandinput: x=input("what would you like to search for") if x in set1: print ( "It is in here!!") else: print("It isn't in here") elif '!E' in commandinput: x=input("what would you like to search for ") if x in set1: print ("It is in here") else: print ("Not here!") elif "power" in commandinput: print ("HIGH") elif 'help' in commandinput: print(table()) intro() A: You should use ==, not is. is tests if the strings are the exact same object in memory, which they probably aren't. if firstChoice == 'help':
{ "pile_set_name": "StackExchange" }
Q: javascript to enlarge img I've got some problems while trying to change the size of an image when 'mouseover' occurs. I know it can be done by css, but I need to realize it by js. JS Codes: // id is passed to this function. ... var content = document.getElementById("content"); var li; // generate lists of img from db. li = document.createElement("li"); li.innerHTML = '<img src="' + id + '" />'; content.appendChild(li); addDomListener(li, 'mouseover', function(){ li.style.height = '600px'; li.style.width = '800px'; }); HTML codes: <div> <ul id="content"> </ul> </div> seems right, but it doesn't work. I suspect the problem is 'li.style.height'. Could anyone tell me the correct way to realize it? Thx! A: You were changing the height and width of li element itself, instead of the img element, for that replace your following code: li.style.height = '600px'; li.style.width = '800px'; for this one: li.firstChild.style.height = '600px'; li.firstChild.style.width = '800px';
{ "pile_set_name": "StackExchange" }
Q: Is taking an injured person to a hospital without their consent kidnapping? I found this definition of "kidnapping" on Google: kidnap, verb. Take (someone) away illegally by force, typically to obtain a ransom. Synonyms: abduct, carry off, capture, seize, snatch, take hostage. "they attempted to kidnap the president's child" But if I am lying on ground bleeding and too weak to move much less fight, and a person I do not know/trust finds me and takes me when I don't want to go with them to his car and drives me off somewhere, even if it's to a hospital, then are they kidnapping me by law of the United States? Especially if they don't call my parents/husband? A: Your question is about "Would it be kidnapping if I was injured and someone took me to a hospital without my consent", so I don't understand these other answers which say "it depends on the situation". The key point is what you mean by "without my consent". Good Samaritan laws are also relevant, which offer defenses to people who do things that would otherwise be unlawful when they are doing it with good intentions to help someone who they believe is injured or would become injured without their intervention. The main things to consider are the degree of injury, which is a spectrum ranging from no injury at all to being dead, and whether the injured person is conscious. Are you so injured that you are unconscious? In most jurisdictions, being unconscious is considered as you consenting to any actions which are done with the intent of giving you medical assistance, which is on a spectrum of saying "hey are you ok?" or shaking you in order to wake you up, all the way up to treatment including major surgery. So by being unconscious it is usually automatically consent, but if you are awake and are refusing help or treatment, even if you could die if you didn't receive treatment, it would be easy to argue that you were not consenting and that any treatment/assistance etc was unlawful. This situation sometimes happens, and EMTs are often trained to wait until the person goes unconscious to then give them medical assistance/transport etc, but assisting someone before they go unconscious could still be argued as permissible, if the injured person was so distressed that they were unable to give/refuse consent, or at least if the assistor believed that to be the case. This is why if someone has a major medical problem and is unconscious, hospitals can resuscitate them and even perform surgery without them signing a consent form. By being unconscious, it is considered that they are consenting to any necessary surgery to help them, even including amputation or other negative consequences. Conversely, if someone has a valid Advance healthcare directive on file which forbids measures such as resuscitation, they will be considered not to consent, and will usually be left alone without life-saving assistance. Resuscitating/performing surgery on someone in this case can be cause for damages to the injured person, because it would have been clear that they did not consent to such assistance.
{ "pile_set_name": "StackExchange" }
Q: First time using @media screen It did not go so well ... The right sidebar disappears if screen is small alright but the top sidebar is staying there and I do not understand why ... after fiddling for hours I decided to ask for help. Website http://www.notloli.com.br <html><head> <style type="text/css"> body{ width:100%; height:100%; margin:0px; background-color:#aaa; font-family:trebuchet ms, tahoma; } @media screen and (max-width:899px){ div.sidebar{visibility:hidden}; div.sidebartop{visibility:visible}; div.mainbox{width:100%;top:calc(100% - 210px);min-height:calc(100% - 210px);} } @media screen and (min-width:900px){ body{font-weight:bold}; div.sidebar{visibility:visible}; div.sidebartop{visibility:hidden}; div.mainbox{width: calc(100% - 310px);top:0px;min-height:100%;} } div.sidebar{ position:fixed; right:0px; height:100%; z-index:2; background-color:#9374a4; width:300px; color:#fff; margin:0px; padding:15px; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; border-left:1px solid pink; } div.sidebartop{ top:0px; position:fixed; z-index:2; width:100%; margin:0px; padding:15px; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; height:200px; background-color:#abab63; } </style></head><body> <div class="sidebartop"></div><div class="sidebar"></div> </body></html> Please assist me ... thank you A: So if the screen is "big" you have side bar and no top bar, if the screen is small you have topbar and no sidebar, right? I think you confused visibility:visible with display:none and display:inline-block and also create a parent for the main and side div. Try this: <html><head> <style type="text/css"> body{ width:100%; height:100%; margin:0px; background-color:#aaa; font-family:trebuchet ms, tahoma; } @media screen and (min-width:900px){.sidebartop{display:none}} @media screen and (min-width:900px){body{font-weight:bold}} .mainbox{display:inline-block;width:70%;min-width:600px} .sidebar{ position:fixed; right:0px; height:100%; z-index:2; background-color:#9374a4; width:300px; color:#fff; margin:0px; display:inline-block; padding:15px; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; border-left:1px solid pink; } @media screen and (max-width:899px){.sidebar{display:none}} .sidebartop{ top:0px; position:fixed; z-index:2; width:100%; margin:0px; padding:15px; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; height:200px; background-color:#abab63; } </style></head><body> <div class="sidebartop"></div> <div> <div class="mainbox"></div><div class="sidebar"></div> </body></html> I did not try all the compatibly it is just a tutorial example
{ "pile_set_name": "StackExchange" }
Q: Parse the items in an multidimentional array php I am creating an e-commerce website where I have to give the categories that a shop has in a particular array . Currently the data getting retrieved from a mysql table contains the same category id's in different array items if the array has different subcategory , I have to gather the same category id's in the same array and for subcategories create a nested array . The code is on laravel 4.2 . Here is the format of data coming right now , "data": [ { "id": 1, "name": "Fruits", "sub_category_names": [ "Dairy Whiteners" ], "total_items": 69 }, { "id": 1, "name": "Fruits", "sub_category_names": [ "Tea & Coffee" ], "total_items": 69 }, { "id": 1, "name": "Fruits", "sub_category_names": [ "Concentrates - Tang etc" ], "total_items": 69 }, { "id": 2, "name": "Beverages", "sub_category_names": [ "Tea & Coffee" ], "total_items": 28 }, { "id": 2, "name": "Beverages", "sub_category_names": [ "Concentrates - Tang etc" ], "total_items": 28 } ] Here is what I need , "data": [ { "id": 1, "name": "Fruits", "sub_category_names": [ "Dairy Whiteners" , "Concentrates - Tang etc" , "Tea & Coffee" ], "total_items": 69 } , { "id": 2, "name": "Beverages", "sub_category_names": [ "Tea & Coffee" , "Concentrates - Tang etc" ], "total_items": 28 } ] The code I wrote for the above , // For the current categories create a common array for subcategories for same categories $filteringSelectedCategories = []; $subCategoriesNamesLocal = []; $innerIndex = 0; for ($i = 0; $i < count($selectedCategories); $i++) { // to prevent undefined offset error if (!isset($selectedCategories[$i + 1])) { continue ; // if 6 don't exist then deal with 5 } // if the id of two items is same then push that sub category name in the same array if ($selectedCategories[$i]['id'] === $selectedCategories[$i + 1]['id']) { array_push($subCategoriesNamesLocal, $selectedCategories[$i]['sub_category_names']); } // if the id is different then push the array values with the sub category name in an array else { $filteringSelectedCategories[$innerIndex]['id'] = $selectedCategories[$i]['id']; $filteringSelectedCategories[$innerIndex]['name'] = $selectedCategories[$i]['name']; $filteringSelectedCategories[$innerIndex]['sub_category_names'] = $subCategoriesNamesLocal; $filteringSelectedCategories[$innerIndex]['total_items'] = $selectedCategories[$i]['total_items']; // nullify the array after assigning the value $subCategoriesNamesLocal = []; // increment the new array index $innerIndex = $innerIndex + 1; } } Here is the output I get from the above , "data": [ { "id": 1, "name": "Fruits", "sub_category_names": [ [ "Dairy Whiteners" ], [ "Tea & Coffee" ] ], "total_items": 69 } ] A: I'm not entirely sure I see what offset error could occur but I believe you could easily get away with; foreach ($selectedCategories as $key => $data) { $newKey = $data['id']; $filteringSelectedCategories[$newKey]['id'] = $data['id']; $filteringSelectedCategories[$newKey]['name'] = $data['name']; $filteringSelectedCategories[$newKey]['sub_category_names'][] = $data['sub_category_names']; $filteringSelectedCategories[$newKey]['total_items'] = $data['total_items']; }
{ "pile_set_name": "StackExchange" }
Q: splash hace que se cierre la app hice un splash screen y le puse una imagen de fondo, y carga bien en mi samsung s8, sin embrago en el j5 hace que se cierre, ya revisé el min sdk y debería cargar en un j5, luego quite la imagen del splah y carga bien...al parecer es el hecho de que ponga una imagen, lo mismo me pasa en cualquier layout que use una imagen de fondo. no se que pasa ojala me puedan ayudar. les dejo el xml, java y el build gradle gradle apply plugin: 'com.android.application' android { lintOptions { checkReleaseBuilds false } compileSdkVersion 28 defaultConfig { applicationId "com.app.birkonapp" minSdkVersion 16 targetSdkVersion 28 versionCode 2 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.codesgood:justifiedtextview:1.1.0' //Justificar texto implementation 'com.google.android.gms:play-services-ads:17.2.0' } java public class splash extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent=new Intent(splash.this,MainActivity.class); startActivity(intent); finish(); } },3000); } } A: ya lo resolví, lo que sucede es que habia ubicado las imagenes que usa la app en la carpeta equivocada, las tenia en la carpeta drawable v-24 y las puse en la carpeta drawable y corrió perfectamente. de todas formas gracias por su ayuda
{ "pile_set_name": "StackExchange" }
Q: Ruby Project Euler 35-Circular Primes Wrong Answer I tried Project Euler question 35 in Ruby (I am quite new to it) and got the wrong answer. The problem: The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? My code: require 'prime' def primes(n) nums = [nil, nil, *2..n] (2..Math.sqrt(n)).each do |i| (i**2..n).step(i) { |m| nums[m] = nil } if nums[i] end nums.compact end prime = primes(1000000) circularPrimes = 0 prime.each do |j| puts "\n" puts j flag = false j = j.to_s() for k in (0..j.length) temp = j[k..-1] + j[0..k] temp = temp.to_i() a = Prime.prime?(temp) if a == false then flag = true break end end if flag == false then circularPrimes += 1 end end puts"\n\n\n\n\n" puts circularPrimes I can't figure out the problem in the code (which I think is fine). A: You are re-inventing two things: generating primes upto n (use Prime.each(n)) rotating the digits (use Array#rotate!) Probably the problem is somewhere in there. I would do it this way: require 'prime' def rotations(x) digits = x.to_s.chars digits.map do digits.rotate!.join.to_i end end circular_primes = Prime.each(1_000_000).select do |p| rotations(p).all?{|r| Prime.prime?(r) } end puts circular_primes.count
{ "pile_set_name": "StackExchange" }
Q: retail flotation When it comes to using the environment to sell, the Body Shop is a pioneer. The Body Shop shot to fame in the 1980s. It stood for environmental awareness and an ethical approach to business. But its success was as much to do with what it sold as what it stood for. It sold natural cosmetics, Raspberry Ripple Bathing Bubbles and Chamomile Shampoo, products that were immensely popular with consumers. Its stock exchange listing in 1984 was one of the most successful retail flotations in history. What do you think retail flotation is? A: A flotation is a method companies can use to generate money. Instead of being privately owned, they sell portions (shares) of the company to the public. The public then plays a part in the everyday running of the company, typically by being able to vote to influence decisions. In return, as the value of the company fluctuates, the value of the shares goes up or down. Retail is any business involving direct contact with the public. From Wikipedia: Retail is the process of selling consumer goods and/or services to customers through multiple channels of distribution to earn a profit. The Body Shop is a (primarily) retail business, and it floated on the stock market in 1984, and this retail flotation was one of the more successful flotations ever. So Retail Flotation is the flotation of a retail company.
{ "pile_set_name": "StackExchange" }
Q: How to store Model loaded by ColladaLoader in Three.js? Since the Three.js migration (r68 -> r69) the ColladaLoader returns a Scene instead of an Object3D. How can I get the loaded Object3D now? I want store the loaded Object in a var to use it everytime. var newpos = Cube.position; var oLoader = new THREE.ColladaLoader(); oLoader.load('models/logo.dae', function(collada) { var object = collada.scene; var skin = collada.skins[0]; object.rotation.x = -Math.PI / 2; object.rotation.z = Math.PI / 2; object.position.x = newpos.x; object.position.y = newpos.y+1.85; object.position.z = newpos.z; object.scale.set(0.75, 0.75, 0.75); object.updateMatrix(); scene.add(object); }, function ( xhr ) { // console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); } ); A: The ColladaLoader returns a scene because the loaded Model is'nt created as a 3DObject. The ColladaLoader creates a new scene added to your scene including the loaded .dae-Model. (Now it returns a group) That's because not every Model is just one Object. Check the childs of the dae.scene that you loaded, it helps a lot.
{ "pile_set_name": "StackExchange" }
Q: Xcode 7.2 can't find c++ std::pair First of all, I use Xcode 7.2 on OSX 10.11.2. In my main.cpp file, the std library is working fine. But, whenever I try to use it in any other c++ file, I get unexpected unqualified-id. I have the following files : main.cpp (std is working in it) algo.hpp (std is not working in it) algo.cpp (std is not working in it) Why is the deployment target OSX 10.11 not finding the standard c++ library in all my files ? Here is for exemple my header file algo.hpp #ifndef algo_hpp #define algo_hpp std::pair<unsigned int, unsigned int> pgcdFB(const int m,const int n); std::pair<unsigned int, unsigned int> euclide(const int m, const int n); unsigned int fibonacci(const unsigned int i); #endif /* algo_hpp */ On each line where I use std I get undeclared identifier 'std A: You'll have to include the proper headers, you simply forgot #include <utility> since you're using std::pair. (and there seems to be no reason to include stdio.h here)
{ "pile_set_name": "StackExchange" }
Q: Newton's Third Law Sorry if this question's been asked. I looked through some of the questions but didn't find a similar enough question. My question on Newton's Third Law: It's my understanding that if you were in outer space and you threw a tennis ball then both you and the tennis ball would move but in opposite directions. Because you exert a force on the ball and it exerts an equal force on you. So how come when you push a wall on earth you get pushed back but not when you throw a ball. Can't you throw a ball with the same force you pushed the wall- if that's the case how come you don't move back? It's putting a force on you equal to the wall's force, right? I do appreciate all the answers I've got but I guess I'm still confused. I understand that the ground pushes me in opposition to the wall's direction of force when the wall pushes my body, therefore my feet, on the ground away from the wall. But how come your arm and consequently your torso moves back when pushing a wall but not when throwing a ball. A: When you throw a ball, you push it and it pushes you back. It just weighs slightly less than a wall (or the entire earth) so you don't need to push as much to move it. You push a ball with enough force to move by acceleration $a$. This force is $F= m a$. This force is also exerted by the ground as a reaction to keep you in place. If you try to throw a ball on ice you will notice you will slide backwards or fall down. Now if you try to "throw a wall" you need a force $F = m a$ that exceeds both the traction on your feet and what you can physically provide so nothing happens, or you slip and fall down.
{ "pile_set_name": "StackExchange" }
Q: Getting error about redefinition even with guard I have a basic file I'm attempting to use. #ifndef POINT_GUARD #define POINT_GUARD //------------------------------------------------------------------------------ struct Point { int x, y; Point(int xx, int yy) : x(xx), y(yy) { } Point() :x(0), y(0) { } }; //------------------------------------------------------------------------------ inline bool operator==(Point a, Point b) { return a.x==b.x && a.y==b.y; } //------------------------------------------------------------------------------ inline bool operator!=(Point a, Point b) { return !(a==b); } //------------------------------------------------------------------------------ #endif // POINT_GUARD Notice that it's wrapped in a guard. Now this is imported into two different files. I'm getting an error, though. It complains as soon as it hits struct Point that it's a "Redefinition of Point". Any ideas what could be happening here? A: I can't reproduce the error with the input given. I placed your code in test.h, and wrote this for test.cpp: #include "test.h" #include "test.h" Running g++ -Wall -c test.cpp produces no errors or warnings, and running it through the pre-processor shows that struct Point is declared only once, so the guard is working. I'd guess there's a declaration with the same name somewhere else, outside of the code you quoted?
{ "pile_set_name": "StackExchange" }
Q: How to prevent rsync from chown'ing remote users files I'm doing rsync /local/path/to/src user1@remote:/path/to/dest. dest belongs to user2@remote. How do I keep rsync from chown'ing dest to user1 after syncing? Please note that I have already tried googling but the switches suggested have not helped and reading the man page has not given me any ideas too. So I'll appreciate your understanding. A: --no-owner may or may not do what you want, depending on whether dest exists or needs to be updated. This is the negated version of --owner, which is described by the man page as: This option causes rsync to set the owner of the destination file to be the same as the source file, but only if the receiving rsync is being run as the super-user (see also the --super and --fake-super options). Without this option, the owner of new and/or transferred files are set to the invoking user on the receiving side. I'm not sure if a directory counts as "transferred" if anything within it changes. As far as I can tell there is no way to tell rsync to not chown updated files at all.
{ "pile_set_name": "StackExchange" }