text:
Q: How to print to pdf separated excel pages in one file? I made this simples code, but this create 4 pdfs files, not only one, can you help me?
Sub PrintToPageX()
Worksheets("Anexo Financeiro").Select
Application.ActivePrinter = "Microsoft Print to PDF on Ne02:"
ActiveWindow.SelectedSheets.PrintOut from:=1, to:=4
If Worksheets("Anexo Financeiro").Range("p205") = 1 Then ThisWorkbook.PrintOut from:=5, to:=5
If Worksheets("Anexo Financeiro").Range("n272") = 1 Then ThisWorkbook.PrintOut from:=6, to:=6
ActiveWindow.SelectedSheets.PrintOut from:=7, to:=7
End Sub

A: Assuming that Worksheets("Anexo Financeiro") is the same as ActiveWindow.SelectedSheets which is the same as ThisWorkbook.ActiveSheet:
I created an If Statement that checks if the document can be printed all together or if it needs to be separated.
Sub PrintToPageX()
    Application.ActivePrinter = "Microsoft Print To PDF on Ne02:"
    With Worksheets("Anexo Financeiro")
        If .Range("p205") = 1 And .Range("n272") = 1 Then
            .PrintOut From:=1, To:=7
        Else
            .PrintOut From:=1, To:=4
            If .Range("p205") = 1 Then .PrintOut From:=5, To:=5
            If .Range("n272") = 1 Then .PrintOut From:=6, To:=6
            .PrintOut From:=7, To:=7
        End If
    End With
End Sub


text:
Q: How do I get the path of where my file is? domain.com/hello/world/
How do I only get the /hello/world/ part?
Update: How could I get domain.com/hello/world?

A: $_SERVER['PHP_SELF'];

A: $_SERVER['REQUEST_URI'] is the actual uri in the browser.

redpajama_set_name: RedPajamaStackExchange


text:
Q: \leftmargin length not working in enumerate environment I need to write down arguments that are made up of numbered claims and where the conclusion is marked by a conclusion symbol. I have no problem modifying the way enumerate labels are displayed to have that result.
Unfortunately, these labels quickly get so wide that they hang over into the left margin. I'd like to indent the enumerate environment on the left so that the labels and the text are further to the right. Looking at a list of lengths in list environments (e.g., in this answer), I figured \leftmargin would be the right length for me to manipulate. Unfortunately, it doesn't have the expected effect of indenting the text associated with an item. I can use \itemindent to indent the label, but that only indents the first line, not the main body.
A couple of constraints on answers.

*

*I'm aware of the enumerate package and for various reasons do not want to use it.

*I only want some, but not all, enumerate environments to be indented in this way. So a global change, e.g., by including \AtBeginDocument{\addtolength{\leftmargini}{3em}} won't work for me.

Here's an MWE I'm working with, and a screenshot of the result. I'm using lipsum as an easy way to generate multiline text, and I'm calling amssymb to get me the "conclusion" symbol of the three dots.
\documentclass{article}

\usepackage{lipsum}
\usepackage{amssymb}
\begin{document}

\lipsum[1]

\begin{enumerate}
  \renewcommand{\theenumi}{\roman{enumi}}%
  \renewcommand{\labelenumi}{(\theenumi)}%
  \addtolength{\leftmargin}{5em}
  \addtolength{\itemindent}{3em}
\item \lipsum[4]
\item \lipsum[4]%
  \renewcommand{\labelenumi}{$\therefore$(\theenumi)}%
\item \lipsum[4]
\end{enumerate}
\end{document}

A: You do not need to set \addtolength{\leftmargini}{3em} in the preamble it is a local declaration so can be set at any point before the special list. You can reset the value after the list either by using a tex group or simply subtracting the value after the list finishes.
It needs to be before \begin{enumerate} not after as the value is used within the begin code to set up the list parameters.

A: With enumitem is simple:
\documentclass{article}
\usepackage{lipsum}

\usepackage{amssymb}
\usepackage{enumitem}
\setlist[enumerate]{label=(\roman*),
                    itemindent=3em,
                    leftmargin=2em, % leftmargin=* if you like to have left margin as in main text
                    }

\begin{document}
\lipsum[11]

\begin{enumerate}
\item   \lipsum[4]
\item   \lipsum[4]%
\stepcounter{enumi}          % <---
\item[$\therefore$\theenumi] % <---
        \lipsum[4]
\end{enumerate}
\end{document}

A: Is it what you want? I set the label width with enumitem, and asked to calculate the left margin in accordance:
\documentclass{article}
\usepackage{showframe}
\renewcommand{\ShowFrameLinethickness}{0.4pt}
\usepackage{enumitem}
\usepackage{lipsum}
\usepackage{amssymb}

\begin{document}

\lipsum[1]

\begin{enumerate}[labelwidth=2.5em, leftmargin=!]
\item \lipsum[4]
\item \lipsum[4]%
\item[$\therefore$ \stepcounter{enumi}(\theenumi)] \lipsum[4]
\end{enumerate}

\end{document}


text:
Q: create tensor in specific indexes without loops I have a tensor t1 (with shape (2*n, 2*n), and I need to create tensor t2 (with shape (2*n)) with the values of t1 at [i,(i+n) mod 2n] for each row i.
For example, given:
t1 = torch.tensor([[1, 2, 3, 4],
                   [5, 6, 7, 8],
                   [9 ,10,11,12],
                   [13,14,15,16]])

Here n=2.
t2 has to be [3,8,9,14].
I have this code:
t2 = torch.tensor([t1[i,(i+n)%(2*n)] for i in range(2*n)])

but Im searching a way without loops.

A: You could create the list of indices beforehand with a loop then pick the values from t1 with torch.gather without having to loop over them yourself:
>>> index = torch.tensor([[(i+n)%(2*n)] for i in range(2*n)])

>>> torch.gather(t1, 1, index).flatten()
tensor([ 3,  8,  9, 14])

Alternatively, you can use torch.roll to shift by n an (2*n, 2*n) identity matrix, multiply by t1 to get a mask and apply that to t1 with torch.masked_select:
>>> mask = torch.eye(2*n).roll(n, 1).bool()
tensor([[False, False,  True, False],
        [False, False, False,  True],
        [ True, False, False, False],
        [False,  True, False, False]])

>>> torch.masked_select(t1, mask)
tensor([ 3,  8,  9, 14])


text:
Q: Which Unreal Engine 4 version runs best on Ubuntu 20.04? Intel® Core™ i5-7500 CPU @ 3.40GHz × 4
NVIDIA Corporation GP107 [GeForce GTX 1050 Ti] / GeForce GTX 1050 Ti/PCIe/SSE2
15,5 GiB
Ubuntu 20.04.2 LTS
I would like to install UE4 4.25 on my PC. I have followed all the steps correctly from https://docs.unrealengine.com/en-US/SharingAndReleasing/Linux/BeginnerLinuxDeveloper/SettingUpAnUnrealWorkflow/index.html. The installation itself was really slow and the application stucks while loading the program. Is there any version of this application that runs stable on Ubuntu 20.04?


text:
Q: Book recommendations for Combinatorial Designs I am well-acquainted to basic topics of experimental designs such as anova, ancova, crd, rbd, lsd, factorial design, robust design etc (as per the book of Dr. D. C. Montgomery). Now as per my recent ongoing research curriculum, I need to learn more mathematically oriented combinatorial design. The topics I need to learn are finite geometry, steiner systems, t-designs, resolvable designs, pairwise balanced design, directed design, pbd, tuscan squares, vector space design, packing, partial geometry, sequences with zero autocorrelation, D-optimal design etc and some other topics based on abstract and linear algebra. I have started with the book by W. D. Wallis but not all topics (such as equidistant permutation array, skolem sequences and many other topics aforementioned) are covered in this book. Also Wikipedia gives a list of references but I am not sure which one to pick beside the book I am using.
Would you kindly like to recommend books on combinatorial design that cover these topics? All suggestions and recommendations are valuable and appreciated.

A: Disclaimer: These are some of the materials that I came across, some of which I used profusely. While the resources don't cover all the things OP mentioned, these are worth to study.

Analysis and Design of Experiments, H. B. Mann, Dover, 1949

Author does an exceptional job in keeping the chapters short but detailed enough to not create any void in derivations. The book is not voluminous; though sometimes beating the bush to go to the main results but this is definitely not quaint: a sharp exposition. The highlights are the chapters on latin squares, Galois fields and Orthogonal Latin squares. More or less self-contained.
Mathematics of Design and Analysis of Experiments, M. C. Chakrabarti, Asia Publishing House, 1962
These are collection of lectures by the author. Not recommended for first reading. The materials are terse. I liked his treatment of confounded arrangements in split-plot designs, application of Galois fields and finite geometry in constructing the confounded designs, hypercubes of strength $d.$ But again, I reiterate it is not for first reading.
Constructions and Combinatorial Problems in Design of Experiments, Damaraju Raghavarao, Wiley, 1971
The author indeed has largely been successful in consolidating some of the important topics: construction of orthogonal arrays, products of orthogonal arrays, embeddings, MacNeish-Mann Theorem, duals of incomplete block designs, partial geometries. Essentially a formal treatment of the field: a good read.
Optimal Design: An Introduction to the Theory for Parameter Estimation, S.D. SILVEY, CHAPMAN AND HALL, 1980
My personal favorite. Silvey did an amazing job in writing such a beautiful treatise. If one knows nothing and wants to have an intuitive idea about information matrices, design criteria, $\mathcal D$ optimality, design algorithms, then without an iota of doubt, do read this classic.
Optimal Design of Experiments, Friedrich Pukelsheim, SIAM, 2006
This is a magnum opus in true sense for it delves deep, I mean way deep, in covering optimality theory. It thoroughly discusses information matrices, optimality criteria, the equivalence theorems, $\cal D,~A, ~E, ~T$ optimality, Bayes designs, invariant designs, Loewner and Kiefer optimality, rotatibility.
Design and Analysis of Experiments, M.K.Sharma, B. V. S. Sisodia, PHI Learning Pvt. Ltd., 2012
A beginner's book with a copious writing style and a tolerable pace develops the finite field theory, finite geometries, difference sets and their applications in constructing the requisite designs. Exercises are easy to moderate.
Robust Response Surfaces, Regression, and Positive Data Analyses, R. N. Das, CRC Press, 2014
The monograph provides a conspicuous elucidation of weak rotatibility, slope rotatibility, weak slope rotatibility, $\mathcal D$ optimal slope rotatibility, and also brief discussion of correlated structures. Although the main attention and emphasis are on robust response surfaces. It is replete with good applications.

A: There is a book on the topic which actually have its own page on wikipedia!.  Start with that one.  amazon link
Also Introduction to Combinatorial Designs (Discrete Mathematics and Its Applications) 2nd Edición  by W.D. Wallis, with empasis on the maths, but ending with statistical applications.


text:
Q: Laravel route model binding and fallback I am working on an api with laravel. For this, I wanna return a json response for all 404 errors. I created this fallback route and placed it at the end of the api.php:
Route::fallback(function(){
    return response()->json(['message' => 'Not Found.'], 404);
})->name('api.fallback.404');

When I now enter an invalid url like /xyz I get the json response as expected.
But when I use route model binding:
Route::get('/projects/{project}', function (\App\Models\Project $project) {
    return $project->toArray();
});

and try to get a non existing project (for example /projects/9999), then I get the standard laravel 404 HTML response and not my json one.
How to fix this?


text:
Q: Connection between isomorphisms of algebraic topology and class field theory I am considering the following two isomorphisms:
First, if $X$ is a reasonably nice topological space, then $X$ has a normal covering space which is maximal with respect to the property of having an abelian group of deck transformations.  The group of deck transformations of this covering space is isomorphic to the abelianizatin of the fundamental group of $X$, which can be identified with the singular homology group $H_1(X,\mathbb{Z})$.
Second, if $K$ is a number field, class field theory gives an isomorphism between the Galois group of the maximal abelian unramified extension of $K$ (the Hilbert class field) and the ideal class group of $K$.  The ideal class group can be identified with the sheaf cohomology group $H^1(\mathrm{Spec}(\mathcal{O}_K),\mathbf{G}_m)$.
Given the apparent similarity between these two theorems, is there some more general theorem which implies both of these results as special cases?

A: As BCnrd says, the theorem you want is geometric class field theory. One version says that the abelianization of the fundamental group of a curve over an algebraically closed field is the fundamental group of its Jacobian. One can use this to derive class field theory for curves over finite fields. Over the complex numbers, this is a topological statement, since the Jacobian of a Riemann surface can be constructed by topological methods, such as $J(C)=H_1(C;\mathbb R/\mathbb Z)$. Also, consider Weil's construction of the Jacobian by using Riemann-Roch to recognize a high symmetric power of a curve as a $\mathbb C\mathbb P^n$ bundle over the Jacobian. The projective space bundle is probably not a topological invariant, but the symmetric power is and it already has the right fundamental group. That has an extensive topological generalization, the Dold-Thom theorem, that the homology of a reasonable space is the homotopy groups of its infinite symmetric power.
The key unifying ingredient is, as BCnrd says, the Jacobian, even though it is missing from both of your statements.


text:
Q: Adding views programmatically, then referencing those views. I'm a novice in the java world, so thanks in advance for the help.
What I am trying to do is this:
I have two EditText fields and a Button. When I hit the button, I want to take the contents of the two fields, combine them and display them below button. The fields are cleared. Then if they are filled again and the button is pushed, combine the fields and display them below previously generated textview.
Example:
Before Button Click:
eT1___ eT2____ |Button|
After Button click
eT1___ eT2____ |Button|
               eT1-eT2
After 2nd Button click
eT1___ eT2____ |Button|
               eT1-eT2
               eT1-eT2
And so on however many times the button is clicked. What I need help with is the new views that are being added. Currently I am using a Relative Layout. What I am trying to figure out is how to reference the new textView's that I am creating within the code so that when new views are added, they can reference the previously added view.
This is what I've been attempting at the moment:

private TextView createNewTextView(String desc, Double cost){
        RelativeLayout.LayoutParams lparams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);;
        TextView newTextView = new TextView(this);
        if (i==1) {
            lparams.addRule(RelativeLayout.BELOW, mButton.getId());
        }
        else {
            lparams.addRule(RelativeLayout.BELOW, mLayout.getId());
        }
        lparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        newTextView.setLayoutParams(lparams);
        newTextView.setText(desc + " - $" + cost);
        newTextView.setTag(i);
        i++;
        return newTextView;
    }

I was trying to use "i" as an incrementing variable that I could use to reference the previous view by except on the first pass when it the new view references based on the button.
Any help would be greatly appreciated. Thanks in advance and for everything I've lurked already!

A: Just add your textviews to a global list and find them based on the tag from there.

A: Create a member variable of ArrayList of TextView :
ArrayList<TextView> textviews = new ArrayList<>();

and then in your createNewTextView() method, store the reference of TextView you are adding:
textviews.add(newTextView);

So the TextView you've added at the first will be at index 0 and so on. Then you can easily reference your TextViews.
Suppose you want to get the second TextView,
TextView secondTv = textviews.get(1);


text:
Q: web api controller action methods I am trying to get a web api call to work:  I want to submit an email address and then on the server, the method will validate and return null or a message.
This is what I tried:
    [Post]
    public string validate(string email) {
        return this._contextProvider.ValidateEmail(email);
    }

However, I get this message returned to the client: No HTTP resource was found that matches the request URI 'https://localhost:44300/breeze/data/validate
The payload looks like this: {email: "Greg@gmail.com"}

A: The problem, it turns out, was the parameter binding.
In the Web API, binding is handling differently than MVC. By default, simple types are extracted from the URI, not the body.  Complex types are extracted from the body of the message.
I then added the [FromBody] Attribute to the Action Method, and it then found the action method.  But alas, the email parameter was null.
public string validate([FromBody]string email) {
        return this._contextProvider.ValidateEmail(email);
    }

Turns out when using this trick, the body must NOT be json, but constructed like a querystring - email=greg@gmail.com.  I didn't want do do that, so ended up creating a class to accept the parameter, and that worked as expected.
public class ParameterizedAction {
    public string Parameter { get; set; }
}

 public string validate(ParameterizedAction arg) {
        return this._contextProvider.ValidateEmail(arg.Parameter);
 }

This article has more info:   http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection
as well as this one:   http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/


text:
Q: Toggling between 2 graphs in HTML/Javascript Hello I was wondering if there is a way I could toggle between 2 graphs(pyGal graphs) which I'm creating in python and passing through flask to the jinja template. I have a graph for weekly information and monthly information and I want (Not a button) but some sort of thing I could click to show only 1 at a time. I'd appreciate any input.

A: It depends a lot on how your webpage is designed. You have to think if the user will understand if you don't put a button or something that relates in an obvious way to that change.
Sometimes we design something that we think that is obvious but if the end user doesn't understand it, it's of no use.
If in your page you have more data showing information about week or month, maybe it's better to put a button that filters it by Month/Week. Just one tiny one :)
If you send a picture with the template I can try to give you some ideas.


text:
Q: How to make facebook app use full screen? I am developing a facebook app and I want my app to use full screen in facebook iframe without any right sidebar which contains info about other apps. Is there any setting/code to remove it or is it default for all the apps?

A: Facebook take consideration about this once.
https://developers.facebook.com/bugs/436162913102704?browse=search_5046c9a1032a58d19137888


text:
Q: padding when a floated object element is inside i have the below html:

        <object width="550" height="200" id="banner">
            <param name="movie" value="banner.swf" />
            <embed src="banner.swf" width="550" height="200"
                    wmode="transparent"
                    type="application/x-shockwave-flash">
            </embed>
        </object>

          <object width="600" height="20">
             <param name="movie" value="menu.swf" />
             <embed src="menu.swf" width="600" height="20"
                    wmode="transparent"
                    type="application/x-shockwave-flash">
              </embed>
         </object>

and the css is:
#wrapper{
 /*background: url(header_bg.jpg) repeat-x;*/
 background: url(container_bg2.png) repeat-y;
 margin: 0 auto;
 margin-top: 20px;
 width: 900px;
}

#header{
 width: 900px;
 padding: 0 10px;
}

#banner{
 float: right;
}

#menu{
 clear: right;
 padding-left: 13px;
}

For some reason the right padding applied to the #header is not working; Any ideas?

A: The width of the wrapper is 900px.
The width of the header is 900px + 10px Left Padding + 10px Right Padding
= 920px.
You are trying to fit a 920px div inside a 900px div. Either make the wrapper wider to 920px or the header shorter to 880px.


text:
Q: Running docker command within python script I have a docker image which is using a text search model that I want to call each time I click a button on my streamlit app.
My code
import streamlit as st
import pandas as pd
import numpy as np
from python_on_whales import docker

def main():
    search = st.text_input('Enter search words:')
    if st.button('Search'):
        st.write('Results:')
        #Run docker
        docker.run("search_app_image")
        # Read csv and create pandas df
        df = pd.read_csv("results.csv")
        st.table(df)

I am trying to run the image the same way as I do in the console via
docker run -v "C:\Users\s.woo\Documents\search_app\docker\search-engine:/home" search_app_image

to mount it as a volume.
When I run it this way from my python script it doesn't write the data to disk, which I need. Any help appreciated!


text:
Q: Somatório query Estou tendo um tipo de problema com esta Query, mas o que eu quero que aconteça é para todos os valores como: Goals Scored, Assists Made,Key passes etc, para fazer somatório para cada ID do Jogador tornando-os aparecer apenas uma vez.
SELECT s.[Statistics ID], s.[Player ID],  s.[Game ID],  s.[Season ID],  s.[Goals Scored], s.[Assists Made],  s.[Key Passes], s.[Successful Tackles],  s.[Successful Interceptions], s.[Goals Conceded], p.[Player Name], p.[Player ID]
FROM Statistics$ s, Players$ p
WHERE s.[Player ID]=p.[Player ID]

Isto é o que aparece na visualização:

A: Para somar utiliza o SUM(campo) e para fazer com que o jogador seja exibido apenas uma vez utiliza DISTINCT campo ou pode agrupar usando GROUP BY campo:
SELECT
  DITINCT p.[Player ID],
  SUM(s.[Goals Scored]) AS gols_jogador,
  SUM(s.[Assists Made]) as assists,
  SUM(s.[Key Passes]) as passes
FROM Players$ p
INNER JOIN Statistics$ s ON s.[Player ID]=p.[Player ID]

Espero que de certo :)


text:
Q: Intuition behind the difference between absolute continuity and $\mu(A) = 0 \implies \mathcal H^{d-1}(A)<+\infty$ In the book Optimal Transport for Applied Mathematicians, the author states that the condition that a measure $\mu \in \mathcal P(\mathbb R^d)$ is absolutely continuous relative to the Lebesgue measure is a stronger than "$\mu(A) = 0$ for any $A \subset \mathbb R^d$ such that $\mathcal H^{d-1}(A)<+\infty$".
Now, I can intuitively understand what absolutely continuity of a measure implies, for example, but I do not have any intuition when it comes to the "$\mu(A) = 0$ for any $A \subset \mathbb R^d$ such that $\mathcal H^{d-1}(A)<+\infty$".
What would be the intuition behind such condition? Can anyone provide examples where $\mu$ is not absolutely continuous, but satisfies this second condition?

A: Yes, in this context you can think about the Lebesgue measure as a sort of characterization of the (let me use this word a bit informally) dimension of the sets. All the Borel sets $A\subset\mathbb{R}^d$ of dimension $d$ verify $\mathcal{L}^d(A)>0$, while if $\mathcal{L}^d(A)=0$ then dimension of $A$ is strictly smaller than $d$. Thus, for $\mu$ to be absolutely continuous w.r.t. $\mathcal{L}^d$ it should vanish also in sets of dimension strictly smaller than $d$. On the other hand, the condition $\mu(A)=0$ for any $A\subset\mathbb{R}^d$ such that $\mathcal{H}^{d-1}(A)<+\infty$ leaves room to define $\mu$ so that it does not vanish for Borel sets $A$ of dimension $d-1$ but such that $\mathcal{H}^{d-1}(A)=+\infty$.
Example: A line in $\mathbb{R}^2$. Consider $d=2$ and $B=\{(x,y)\in\mathbb{R}^2:y=x\}$, hence $\mathcal{L}^2(B)=0$ but $\mathcal{H}^{1}(B)=+\infty$. Then you can define $\mu$ so that $\mu(A)=0$ for any $A\subset\mathbb{R}^d$ such that $\mathcal{H}^{d-1}(A)<+\infty$ but $\mu(B)>0$. Therefore it is not absolutely continuous w.r.t. $\mathcal{L}^2$.


text:
Q: How do I know when the limit of a function at a certain point doesn't exist? $$\lim_{x \to 8} \frac{\sqrt{7+\sqrt[3]{x}}-3}{x-8}$$
I have this limit. I can't use L'Hopital. After rationalizing the numerator I get:
$$\lim_{x \to 8} \frac{\sqrt[3]{x}-2}{(x-8)(\sqrt{7+\sqrt[3]{x}}+3)}$$
Isn't there anything left to do after that? How to know if the limit just doesn't exist?
EDIT: I typed the limit wrong.

A: The numerator (of the original limit) approaches 6, while the denominator approaches 0.  Further, the denominator is positive as $x\to 8+$, and negative as $x\to 8-$.  Hence the limit is $+\infty$ from the right and $-\infty$ from the left.  Thus it doesn't exist.

A: \begin{align}
\lim_{x \to 8} \frac{\sqrt{7+\sqrt[3]{x}}-3}{x-8}
&=\lim_{x \to 8} \frac{\sqrt{7+\sqrt[3]{x}}-3}{x-8} \cdot \frac{\sqrt{7+\sqrt[3]{x}}+3}{\sqrt{7+\sqrt[3]{x}}+3}\tag{1}\\
&=\lim_{x \to 8} \frac{(7+\sqrt[3]{x})-9}{(x-8)(7+\sqrt[3]{x}+3)}\tag{2}\\
&=\lim_{x \to 8} \frac{\sqrt[3]{x}-2}{(x-8)(7+\sqrt[3]{x}+3)}\tag{3}\\
&=\lim_{x \to 8} \frac{\sqrt[3]{x}-2}{(\sqrt[3]{x}^3-2^3)(7+\sqrt[3]{x}+3)}\tag{4}\\
&=\lim_{x \to 8} \frac{\sqrt[3]{x}-2}{(\sqrt[3]{x}-2)(\sqrt[3]{x}^2+2\sqrt[3]{x}+4)(7+\sqrt[3]{x}+3)}\tag{5}\\
&=\lim_{x \to 8} \frac{1}{(\sqrt[3]{x}^2+2\sqrt[3]{x}+4)(7+\sqrt[3]{x}+3)}\tag{6}\\[6pt]
&=\frac{1}{(4+4+4)(7+4+3)}=\frac{1}{168}\tag{7}
\end{align}
Explanation:
$(2)$: I used $(x-y)(x+y)=(x^2-y^2)$
$(5)$: I used $(x^3-y^3)=(x-y)(x^2+xy+y^2)$


text:
Q: Remove Old Angular CLI version I'm trying to upgrade to 10 on a mac
How do I find and delete an old version?
I tried these two steps, but version 8.00 is still there
Step 1 :
sudo npm uninstall -g @angular/cli

Step 2 :
sudo npm cache clean --force

Here I got
preferred-user:~ puser$ sudo npm uninstall -g @angular/cli
Password:
up to date in 0.058s
preferred-user:~ puser$ sudo npm cache clean --force
npm WARN using --force I sure hope you know what you are doing.
preferred-user:~ puser$ ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 8.0.0
Node: 12.9.1
OS: darwin x64
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.800.0
@angular-devkit/core         8.0.0
@angular-devkit/schematics   8.0.0
@schematics/angular          8.0.0
@schematics/update           0.800.0
rxjs                         6.4.0

A: you can install nvm (node version manager), through this you can install multiple nodejs versions and can install latest version of angular-cli.
Link to guide how to install nvm

A: Uninstalled homebrew and reinstalled node the CLI install is working as expected
Homebrew had the old version of Angular in it's /cellar folder


text:
Q: How to hide a section of fields using a checkbox? How to hide a section of fields using a checkbox in visualforce pages?

A: Assuming the Salesforce approach (keeping the page weight down etc.), you could do something like the following:
<apex:inputCheckbox value="{!theBool}">
    <apex:actionSupport event="onChange" action="{!myAction}" rerender="theFieldsPanel"/>
</apex>

<apex:outputPanel id="theFieldsPanel">
    <apex:variable var="v" value="" rendered="{!theBool}">
        <apex:inputField value="{!someField"} rendered/>
        <!-- more fields etc. -->
    </apex:variable>
</apex:outputPanel>

Note that I don't use the rendered attribute on the output panel itself, this is because if it's not rendered then it doesn't exist in the page, and as such, doesn't make for a good  rerender target! Now you just require a simple action on the controller (you could do any other logic in here if need be):
public Pagereference myAction()
{
    // any logic etc. goes here
    return null;
}

The benefit of doing things this way, as opposed to with javascript is that you can ensure that if the fields are hidden then values won't be sent back to the controller for the variables they're bound to. Simply hiding things with javascript would not have the same effect, so say the user typed something in one of the fields and then hid them, whatever he/she typed would still end up in the related controller variables.


text:
Q: open multi image pages to different Bitmap objects in .net I am developing an image editor and the structure needs a different Bitmap object for each page. But in .net i couldnt find a fine way.
When i use Bitmap.Clone() it gives the same bitmap (not only one page)
The code below works fine but its dirty and slow.
So what would be the best way of opening a multi-image to separate Bitmap objects?
                    for (int i = 0; i < frameCount; i++)
                    {
                        bmp.SelectActiveFrame(FrameDimension.Page, i);
                        MemoryStream ms = new MemoryStream();
                        bmp.Save(ms, ImageFormat.Bmp);

                        Bitmap outImg = new Bitmap(ms);
                        outImg.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);

                        AddFrame(name, outImg, mimeType);//This creates a class inluding a bitmap object
                        Application.DoEvents();
                    }


text:
Q: TextAngular is not functioning as expected? I just shifted from summernote to angularText. With summernote as my html editor everything was working as expected.
With angularText my editor shows fine, and the html previously entered (under summernote) looks fine. But there is a MAJOR issue!
If I type a single key into the editor, all the html tags VANISH.
One might imagine that I am missing something in the setup, but the initial display looks fine. It is only after I enter a key that things radically change.  In order to keep things simple I have in my scope:
$scope.html = "
Hello There
";

and the relevant markup is:

<textarea ng-model="html" style="width: 100%"></textarea>

Before the key stroke I see:

After the key stroke all the html tags are GONE!

You help is greatly appreciated!
PS: 'Dumb is really powerful!' and I am probably missing something obvious!

A: It turns out that I had a directive: contenteditable that was causing havoc with textAngular.  I renamed my directive and the issue was immediately solved.
As it turns out I really need this contenteditable directive in other places!  The final solution as quite reasonable.  In my contenteditable directive, I simply tested for the class names for those contenteditible elements, and stopped the directive from modifying the html otherwise.  Hence I added within my contenteditable directive:
link: function (scope, element, attrs, ngModel) {

    ...
    ...

    if (!element.hasClass('task_name')) {
      // don't affect any elements which don't have 'task_name' class
      // so don't bind or $render
    }
    else
    {
      ngModel.$render = function () {
        element.html(ngModel.$viewValue || "");
      };

      element.bind("blur keyup change", function () {
        // read is my magic needed for the task_name elements
        scope.$apply(read);
      });
    }

}


text:
Q: AppCompat v7:21 Split Action Bar Broken? I am currently developing an application in which I use a heavily modified Split Action Bar. Here is a link to the app's current state:

You'll notice a transparent action bar up top, with a custom view inflated into it, with a hacked together split action bar on bottom. The bottom view is actually a single action item with a custom view inflated into it and showAlways=true.
Currently I only support SDK v15+ and I don't really plan on changing that, but with the Lollipop AppCompat library that just released, I decided to implement it, so I could get some of that awesomeness in my app.
I've changed my theme to Theme.AppCompat.Light, and my MainActivity now extends ActionBarActivity instead of Activity.
All references to getActionBar have now been switched to getSupportActionBar, and with only those changes, this is what my activity now looks like:

You'll notice I got a UI dump from the Device Monitor, and it's shoving the bottom action bar into a weird space and calling that the action bar, and getting rid of my top custom view.
Here is my code for setting up my action bar:
public void initializeActionBar(){
    View customNav = LayoutInflater.from(this).inflate(R.layout.action_bar_top, null);

    actionBar = getSupportActionBar();
    actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.transparent_fifty_percent));

    final PopupWindow window = addPopupWindow();

    actionBarOptions = (ImageView)customNav.findViewById(R.id.options);
    actionBarOptions.setVisibility(View.GONE);
    actionBarOptions.setImageDrawable(app.svgToBitmapDrawable(getResources(), R.raw.vertical_ellipsis, app.scaleByDensity(48)));
    actionBarOptions.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            window.showAsDropDown(actionBarOptions, 0, 0);
        }
    });
    TextView title = (TextView) customNav.findViewById(R.id.screen_title);
    Typeface font1 = Typeface.createFromAsset(getAssets(), "Merriweather-Italic.ttf");

    title.setText("Parsley");
    title.setTypeface(font1);

    actionBar.setCustomView(customNav);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayShowHomeEnabled(false);
    actionBar.setDisplayUseLogoEnabled(false);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    new MenuInflater(this).inflate(R.menu.test, menu);

    LinearLayout fullMenu = (LinearLayout) menu.findItem(R.id.full_menu).getActionView();

    ViewGroup.LayoutParams params;

    icon1 = (ImageView) fullMenu.findViewById(R.id.action_item1);
    params = icon1.getLayoutParams();
    params.width = getResources().getDisplayMetrics().widthPixels / 4;
    params.height = (int) (48 * getResources().getDisplayMetrics().density);

    icon1.setImageDrawable(app.svgToBitmapDrawable(getResources(), R.raw.shopping_list_icon, app.scaleByDensity(32)));
    icon2 = (ImageView) fullMenu.findViewById(R.id.action_item2);
    icon3 = (ImageView) fullMenu.findViewById(R.id.action_item3);
    icon4 = (ImageView) fullMenu.findViewById(R.id.action_item4);
    icon2.setImageDrawable(app.svgToBitmapDrawable(getResources(), R.raw.recipe_box_icon, app.scaleByDensity(32)));
    icon3.setImageDrawable(app.svgToBitmapDrawable(getResources(), R.raw.icon_search, app.scaleByDensity(32)));
    icon4.setImageDrawable(app.svgToBitmapDrawable(getResources(), R.raw.icon_add, app.scaleByDensity(32)));
    params = icon2.getLayoutParams();
    params.width = getResources().getDisplayMetrics().widthPixels / 4;
    params.height = (int) (48 * getResources().getDisplayMetrics().density);
    params = icon3.getLayoutParams();
    params.width = getResources().getDisplayMetrics().widthPixels / 4;
    params.height = (int) (48 * getResources().getDisplayMetrics().density);
    params = icon4.getLayoutParams();
    params.width = getResources().getDisplayMetrics().widthPixels / 4;
    params.height = (int) (48 * getResources().getDisplayMetrics().density);
    if (!firstLoad) {
        setBottomActionBarActive();
        setActiveTab(0);
    }

    optionsLoaded = true;

    return true;
}

initializeActionBar() is called from onCreate in my activity. Any ideas what I'm doing wrong?

A: Toolbar should be used. In your case it's one toolbar at the top, and one at the bottom. Check android team blog, they have nice integration guide.

A: If you just want your bottom action bar back, you can simply change back to appcompat v7:20 ,and it works for me. The problem is split action bar is no longer being supported in appcomat v7:21.

A: While user482277's solution may work for instances with a more traditional split action bar, utilizing action items, navigation drawer, etc, it didn't quite work for me. What I ended up doing was building a pair of custom (compound really) views to emulate both the top and bottom action bar. I found this situation to work much better, especially with backwards compatibility. I don't have to worry about earlier versions supporting action bar, because at the end of the day, it's just a pair of classes that extend LinearLayout. In addition, I don't have to worry about different screen sizes (particularly tablets) not supporting the split version.


text:
Q: Is this a selenium issue or website issue? I have made a list of all links present on the given webpage. It is including spaces and considering them links (when I print its length). I cannot seem to figure out what's happening. Is this selenium issue, webpage issue or am I doing it wrong?
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome(executable_path="D:\D-Downloads\chromedriver_win32\chromedriver.exe")

driver.get("https://www.youtube.com/")

links = driver.find_elements(By.TAG_NAME,"a")
print(len(links))

for link in links:
    print(link.text)

The output of the length part is:
171
The link.text output displays the links but with a lot of spaces. I checked and the len(links) is also considering these spaces.


text:
Q: Conflict in routing between Laravel Nova and Dingo API I have a Laravel API server which only has one web route (test page), everything else is controlled via dingo/api package and all is working correctly.
In config/api.php I've set 'prefix' => env('API_PREFIX', '/') as it's only an API server.
I've since installed Laravel Nova and kept getting JSON errors message on the /nova route: No hint path defined for [nova].
I eventually figured out I need to change the prefix to 'prefix' => env('API_PREFIX', '/api'). Now Nova works correctly, but my API routes are broken.
In Postman when I do GET /test (prefix /) works, but Nova doesn't, and when I do /api/test/ (prefix /api), Nova does work but I get an error on the API return:
{
    "message": "",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
    "file": "/home/vagrant/Code/guest-api/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php",
    "line": 179,
    "trace": [
        {
            "file": "/home/vagrant/Code/guest-api/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
            "line": 633,
            "function": "match",
            "class": "Illuminate\\Routing\\RouteCollection",
            "type": "->"
        },
        {
            "file": "/home/vagrant/Code/guest-api/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
            "line": 622,
            "function": "findRoute",
            "class": "Illuminate\\Routing\\Router",
            "type": "->"
        },
        ...
    ]
}

Without an error message, I can't see what is wrong? Also, when I do php artisan api:routes I get the correct route back:
+------+----------+-----------------+------+-----------------------------------------------+-----------+------------+----------+------------+
| Host | Method   | URI             | Name | Action                                        | Protected | Version(s) | Scope(s) | Rate Limit |
+------+----------+-----------------+------+-----------------------------------------------+-----------+------------+----------+------------+
|      | GET|HEAD | /something/test |      | App\Http\Controllers\Auth\AuthController@test | No        | v1         |          |            |
+------+----------+-----------------+------+-----------------------------------------------+-----------+------------+----------+------------+

A: Instead of adding the /api as a fallback parameter, you should add the prefix to your .env file like: API_PREFIX=api as described here


text:
Q: how to set status as "Declined" "Completed" in docusign through API i am trying to set a document status as "Declined" / "Completed" through API call however i a mgetting back an error mentioning only "sent" created or voided or the valid status
Can someone help me if i am making any error in the request
https://demo.docusign.net/restapi/v2/accounts//envelopes/
{"status":"completed"}
OR
{"status":"declined","voidedReason":"test"}
But getting the follwoing response back from DOCUSIGN
{
errorCode: "INVALID_REQUEST_PARAMETER"
message: "The request contained at least one invalid parameter. Value for 'status' must be 'created', 'sent' or 'voided'."
}

A: Only the recipient's action can trigger an Envelope status of "declined" or "completed".  i.e., you can't decline an envelope via the API -- and you can't complete an envelope via the API -- the recipient's action of either declining or completing the Envelope is the only thing that will result in an Envelope with status of declined or completed.
As the error message indicates, the only Envelope statuses you can set via the API are 'created', 'sent', and 'void'.  If you're simply trying to make it so that no further action can be conducted upon an in-progress envelope, then "void" is the status that you'd want to set via the API.


text:
Q: Multi database y Multi sitios Django Intento hacer una Aplicación API Rest en Django y lo que intento hacer que varios dominios(example1.com, example2.com, example3.com) al momento de hacer peticiones sean dirigidos con la base de datos de cada cual.
Cada dominio tiene su base de datos en postgresql.
Django permite utilizar Multi Databases y para poder utilizar esa estrategia hay 2 maneras:
1.- Al momento de hacer una consulta en el ORM
 Articulos.object.using('database1').get(id=id) #por ejemplo

2.-  Crear un archivo llamado routers.py, donde se define una clase sobreescribiendo algunos metodos
class DatabaseRouter(object):
def db_for_read(self, model, **hints):
    request = HttpRequest()
    if request.META.get('HTTP_HOST) == 'domain1':
        return 'database1'
    if request.META.get('HTTP_HOST) == 'domain2':
        return 'database2'
    return None

def db_for_write(self, model, **hints):
    request = HttpRequest()
    if request.META.get('HTTP_HOST) == 'domain1':
        return 'database1'
    if request.META.get('HTTP_HOST) == 'domain2':
        return 'database2'
    return None

def allow_syncdb(self, db, model):

    if db == 'database1' or db == 'database2':
        return model._meta.app_label == 'app'
    elif model._meta.app_label == 'app':
        return False

    return None

se integra esa clase al Settings.py
DATABASE_ROUTERS = ['APIapp.routers.DatabaseRouter',]

Hasta aqui va bien la información.
Ahora, la pregunta es ¿ Como puedo hacer para que al momento de ingresar el dominio, routers.py sepa que dominio y por ende que database elegir?
Segun lo que yo he leido, hacerlo a través de un middleware pero no he podido, entonces se me ocurre recuperar el en routers.py el dominio. Las vistas de Django contienen un argumento request donde incluye el hostname, pero no he podido recuperar ese objecto de Django y mandarselo a routers.py
¿Que es lo que puedo hacer ?

A: Pues si, la mejor manera era a través de un middleware
y ahora routers.py quedo asi:
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.http import Http404
import threading
request_cfg = threading.local()

class RouterDBMiddleware(MiddlewareMixin):
    def process_view( self, request, view_func, args, kwargs ):
        for db_name in settings.DATABASE_CURSORS:
            if db_name in request.get_host():
                request_cfg.db = db_name
        if not request_cfg:
            request_cfg.db = 'default'

    def process_response(self, request, response):
        if hasattr(request_cfg, 'db'):
            del request_cfg.db
        return response

class DatabaseRouter(object):
    def _default_db( self ):
        if hasattr( request_cfg, 'db' ):
            return request_cfg.db
        else:
            return 'default'

    def db_for_read(self, model, **hints):
        return self._default_db()
    def db_for_write(self, model, **hints):
        return self._default_db()
    def allow_syncdb(self, db, model):
        if db == request_cfg.db:
            return model._meta.app_label == 'APIapp'
        elif model._meta.app_label == 'APIapp':
            return False
        return None

En settings.py declare una lista con los valores de las bases de datos para llamarla
DATABASE_CURSORS = ['interprice','prueba1','prueba2']

El middleware
'APIapp.routers.RouterDBMiddleware',

y el router
DATABASE_ROUTERS = ['APIapp.routers.DatabaseRouter',]

y funciono !!!
Comparto las ligas de donde me base:
http://django-book.blogspot.mx/2012/06/capitulo-3-los-principios-de-las.html
http://django-book.blogspot.mx/2012/06/middleware.html
https://djangosnippets.org/snippets/2037/
https://gist.github.com/gijzelaerr/7a3130c494215a0dd9b2


text:
Q: Jquery replace all strings starting with # and add link I have a large blocks or text on a message board that will contain strings beginning with #. Can I use jquery to replace these with a link containing the string?
For example, changing:

This is my #block of text with #multiple hash strings

to:

This is my #block of text with #multiple hash strings

Thanks in advance!

A: You could use the following code to replace strings:
var string = "#has etc #has ";
string = string.replace(/#(\S+)/g, '#$1');

A: This will do the work:
$('*:contains("#")').each(function(){
 if($(this).children().length < 1)
      $(this).html(
           $(this).text().replace(
                /#(.*)#/
                ,''+$(this).text()+''
           )
       )
});


text:
Q: Can't remove old kernels due to unmet dependencies I'm trying to remove old kernels on Ubuntu 17.10, but am being hit with an unmet dependencies error. My current kernel is linux 4.13.0-38-generic.
My output from dpkg -l | grep linux-image | awk '{print$2} is this:
linux-image-4.13.0-36-generic
linux-image-4.13.0-37-generic
linux-image-4.13.0-38-generic
linux-image-4.13.0-39-generic
linux-image-extra-4.13.0-36-generic
linux-image-extra-4.13.0-37-generic
linux-image-extra-4.13.0-38-generic
linux-image-extra-4.13.0-39-generic
linux-image-extra-4.13.0-41-generic
linux-image-generic

When I try to remove older kernels (sudo apt-get purge linux-image-x.x.x-x-generic ), this is the error:
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
 linux-image-extra-4.13.0-41-generic : Depends: linux-image-4.13.0-41-generic but it is not installed
 linux-image-generic : Depends: linux-image-4.13.0-41-generic but it is not installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

To fix the broken dependencies, I use sudo apt --fix-broken install, click Yes when asked whether I want to continue, and get this output:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
  libqpdf18 linux-headers-4.13.0-37 linux-headers-4.13.0-37-generic
  linux-image-4.13.0-37-generic linux-image-extra-4.13.0-37-generic
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
  linux-image-4.13.0-41-generic
Suggested packages:
  fdutils linux-doc-4.13.0 | linux-source-4.13.0 linux-tools
The following NEW packages will be installed:
  linux-image-4.13.0-41-generic
0 upgraded, 1 newly installed, 0 to remove and 15 not upgraded.
5 not fully installed or removed.
Need to get 0 B/20.9 MB of archives.
After this operation, 72.6 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
(Reading database ... 374331 files and directories currently installed.)
Preparing to unpack .../linux-image-4.13.0-41-generic_4.13.0-41.46_amd64.deb ...
Examining /etc/kernel/preinst.d/
run-parts: executing /etc/kernel/preinst.d/intel-microcode 4.13.0-41-generic /boot/vmlinuz-4.13.0-41-generic
Done.
Unpacking linux-image-4.13.0-41-generic (4.13.0-41.46) ...
dpkg: error processing archive /var/cache/apt/archives/linux-image-4.13.0-41-generic_4.13.0-41.46_amd64.deb (--unpack):
 cannot copy extracted data for './boot/vmlinuz-4.13.0-41-generic' to '/boot/vmlinuz-4.13.0-41-generic.dpkg-new': failed to write (No space left on device)
No apport report written because the error message indicates a disk full error
    dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
    Examining /etc/kernel/postrm.d .
run-parts: executing /etc/kernel/postrm.d/initramfs-tools 4.13.0-41-generic /boot/vmlinuz-4.13.0-41-generic
run-parts: executing /etc/kernel/postrm.d/zz-update-grub 4.13.0-41-generic /boot/vmlinuz-4.13.0-41-generic
Errors were encountered while processing:
 /var/cache/apt/archives/linux-image-4.13.0-41-generic_4.13.0-41.46_amd64.deb

Output of uname -r is: 4.13.0-38-generic
Output of df -h is:
Filesystem              Size  Used Avail Use% Mounted on
udev                     63G     0   63G   0% /dev
tmpfs                    13G  2.7M   13G   1% /run
/dev/mapper/sdb2_crypt  1.9T 1004G  779G  57% /
tmpfs                    63G   39M   63G   1% /dev/shm
tmpfs                   5.0M  4.0K  5.0M   1% /run/lock
tmpfs                    63G     0   63G   0% /sys/fs/cgroup
/dev/nvme0n1p1          1.1T  472G  573G  46% /mnt/scratch
/dev/sdb1               231M  222M     0 100% /boot
/dev/md126p1            9.1T  3.0T  6.2T  33% /mnt/10TB
tmpfs                    13G   84K   13G   1% /run/user/1001
tmpfs                    13G     0   13G   0% /run/user/1004

A: You need to free up space in your /boot directory first. You have four 4.4.13.0 chain kernels: -36, -37, -38 and -39. You only need -38 and -39. So you need to remove -36 and -37. I don't have them installed but to give you an idea of what they would look like I used this command:
$ ll /boot/*4.4.0-124*
-rw-r--r-- 1 root root  1251054 May  2 08:58 /boot/abi-4.4.0-124-generic
-rw-r--r-- 1 root root   190654 May  2 08:58 /boot/config-4.4.0-124-generic
-rw-r--r-- 1 root root 43369621 May 17 06:00 /boot/initrd.img-4.4.0-124-generic
-rw-r--r-- 1 root root      255 May  2 08:58 /boot/retpoline-4.4.0-124-generic
-rw------- 1 root root  3898100 May  2 08:58 /boot/System.map-4.4.0-124-generic
-rw------- 1 root root  7143952 May  2 08:58 /boot/vmlinuz-4.4.0-124-generic

Repeat this command on  your system by substituting 4.4.0-124 with 4.13.0-36 and 4.13.0-37. As you will see each kernel takes about 450 MB in /boot.
Then very carefully type these commands (but not the comments #):
sudo rm -f /boot/*4.13.0-36*
sudo rm -f /boot/*4.13.0-37*
sudo apt install -f  # Ensure all dependency errors are now fixed.
sudo apt update      # There should be no errors reported.
sudo apt autoremove  # This will finish removing kernels -36 & -37.
sudo apt upgrade     # This should install new kernel 4.13.0-41
sudo reboot          # You will now boot into kernel 4.13.0-41

After rebooting, and any other time after booting a new kernel update run:
sudo apt autoremove  # This will keep you at current kernel plus previous version (4.13.0-39) and remove all others

If you have the slightest doubt or uncertainty post a comment below.


text:
Q: mkfifo pipes, file descriptors and ImageMagick (convert) I'm in trouble using named pipes (i.e. created with mkfifo) and file descriptors to redirect outputs and grab inputs to/from them within ImageMagick (convert).
Basically, with the following bash code (well, an easier equivalent to what I'm trying) the script hangs and won't show the image:
#!/bin/bash
mkfifo myPipe                              # Create a named pipe
exec 3<>myPipe                             # I/O file descriptor using the pipe
convert rose: -resize 640x480\! png:fd:3   # Write the image to the pipe
convert png:fd:3 win:                      # To read from the pipe using the file descriptor
exec 3>&-                                  # Close the file descriptor
rm myPipe                                  # Close and remove the pipe

Making some research, I saw here this paragraph (it's from Jonathan Leffler's answer):

When a FIFO is opened for reading, it blocks the calling process
  (normally). When a process opens the FIFO for writing, then the reader
  is unblocked. When the writer closes the FIFO, the reading process
  gets EOF (0 bytes to read), and there is nothing further that can be
  done except close the FIFO and reopen.

To avoid that, I tried to use Mark Edgar's solution consisting of these instructions (code taken from the answer):
# Create pipe and start reader.
mkfifo pipe
cat pipe &
# Open pipe for writing.
exec 3>pipe
echo one >&3
echo two >&3
# Close pipe.
exec 3>&-

Unfortunately, I need to read from the pipe and write to it with file descriptors (i.e. fd:X using convert). How can I accomplish that without the hanging problems?

A: The problem is that while
exec 3<>myPipe

opens both the R and the W end of the FIFO simultaneously, thereby preventing a deadlock there,
convert rose: -resize 640x480\! png:fd:3

is a normal/foreground command that needs to finish before the next command can run.
Because it's writing what's likely to be a lot of data to a FIFO, it won't finish, but instead get blocked when the FIFO buffer is full, effectively deadlocking the script.
To prevent that, you need put this command in the background so that the next process can concurrently drain the FIFO, preventing it from filling up.
As I've mentioned in the comment, in this case I'd recommend using regular pipes instead of named pipes:
convert rose: -resize 640x480\! png:fd:1 |
   convert png:fd:0 win:

If you're worried about your code lines becoming too long, you can create continuation lines by ending lines with \ or by putting newlines after tokens that need a right-hand side (such as ||, &&, or | as I did it) (I also tend to indent my continuation lines for better readability, but that's purely optional).


text:
Q: Powershell: Where-Object wildcard I want to search all the properties of an Active Directory user for a particular phone number/extension.
I can get all the properties like so:
get-aduser joesmith -Properties *

but I want to filter the results for, say extension 1234 (which may be in many places, like extensionAttribute1, OfficePhone, HomePhone, Mobile, etc).
I tried:
get-aduser joesmith -Properties * | where-object {$_ -like "*1234*" }

but where-object wants $_.value, and I don't know the precise value.
How should I search the values for multiple properties?  I'd like to see results like:
mobile        1234
officephone   12345
othermobile   61234

A: To iterate through the values for properties you don't know the names of (i.e OfficePhone, CustomAttribute2, mobile), you can use the following:
get-aduser joesmith -Properties * | foreach-object {
  foreach ($property in $_.PSObject.Properties) {
    if ($property.value -like "*1234*") {
      "$($property.name) $($property.value)"
    }
  }
}


text:
Q: vscodevim - find character - comma remap I a using vscodevim with VS Code. I have mapped my leader to comma:
"vim.leader": ",",

Now when i do f<some_character>;, it works as expected to go the second matched character. But afterwards, the , (comma) does not work as it is being used as leader. We can do F<same_character> to navigate backward. Is there a way to map backward search (via comma originally) to some other key like \ (slash).

A: You can use :noremap to accomplish what you need. It maps a key non-recursively, which will let you define some other key to have the original behaviour of ,. With your example:
:noremap \ ,

Here, :map would not work, since :map \ , would make \ behave like your modified , key, so you really need noremap.


text:
Q: get value from textfield html into java variable I am tring to run function that get 2 variables one of them should get the value from textfield.
any advice?
<%@page import="root.SQLQuery"%>
<%@ page language="java" contentType="text/html; charset=windows-1255"
pageEncoding="windows-1255"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="root.SQLQuery"%>
<%
String emp_email = session.getAttribute("email").toString();
SQLQuery sql = new SQLQuery();
String link="";

%>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Insert title here</title>

your email is:<%=emp_email%>>
Copy the link here: <input type="text" name="videoLink" id="link">
<input type="submit" value="submit" onclick="<%sql.meetingUpdateVideoLink(emp_email,        request.getParameter("videoLink").toString()); %>>">

I am tring to insert the fanction meetingUpdateVideoLink() two variables:

*

*email - that easy I get from session.

*Link - that is the tricky one I need to get it from the textfield name="videoLink"
Thanks,
Cfir


text:
Q: Couldn't get a file descriptor referring to the console this is my first post, so don't be harsh if something isn't right. I'm by no means an advanced linux user.
I'm using XFCE, but I am only trying to change the font of text mode consoles. I was trying to change the font on my system. I 'cd'ed into /usr/share/kbd/consolefonts and was trying to 'setfont' from the list.
Both 'setfont' and 'showconsolefont' gave the following error message:"Couldn't get a file descriptor referring to the console."
I tried to run showconsolefont with root privileges and it worked, however when I tried to run 'setfont' with root privileges it didn't seem to make any change whatsoever.
I even tried to set FONT= variable in /etc/vconsole.conf and reboot the system, but it didn't make any change.
The only similar problem I've managed to find online was some guy that had the problem due to 'setfont' lines in .xinitrc, .bashrc and .bashprofile. For this reason I even tried to reset all those files using the originals from /etc/skel and overwriting ones in my home directory.
Help would be highly appreciated. Thanks in advance.


text:
Q: Can't make socket.io work on HTTPS I'm using simple socket.io 2.0.3 server without express or anything similar to run simple chat feature in my Laravel app.
Everything was working well until I decided to switch website to HTTPS. Now socket.io refuses to connect (ERR_CONNECTION_CLOSED).
Here is my simplest setup:
server.js:
var io = require('socket.io')(8080, {
    origins : //some stuff
});

HTML file
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>

var socket = io(':8080');
//more stuff

I have all needed certificate files in server folder, intermediate.crt, domain.com.crt and domain.com.key
Can someone help with simplest example how to make this work on https? Thanks in advance!
Edit: Need possible solution without using Express.

A: I couldn't manage to write this in simple socket.io code, so I ended up using express after all.
Here is the simplest working code if anyone needs it in future:
server.js
var express = require('express');
var app = module.exports = express();
var https = require('https');
var fs = require('fs');
var server = https.createServer({
    key: fs.readFileSync(/*full path to your key*/),
    cert: fs.readFileSync(/*full path to your cert*/),
    ca: fs.readFileSync(/*full path to your intermediate cert*/),
    requestCert: true,
    rejectUnauthorized: false
},app);
server.listen(8080); //listen on port 8080

var io = require('socket.io').listen(server);

io.set('origins', /*your desired origins*/);

io.set('transports', ['websocket',
    'flashsocket',
    'htmlfile',
    'xhr-polling',
    'jsonp-polling',
    'polling']);

var sockets = {};
//your socket logic

in HTML:
var socket = io(':8080',{secure: true});

A: You can create an instance of an HTTPS server with all your relevant settings
var https = require('https');
https.createServer(options, app).listen(443);

Then simply pass it to the constructor:
new SocketIo(https)

A: Important facts :
You must use https not http ,
 Need to load crt files and create options object like in example
 Client side need only correct address like : https://YOUR_domain.com:PORT
Server side :
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//High definition
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
// Globals
//var MEMORY_CLEANER_INTERVAL = 5000;
//var crypto = require('crypto');
var tls = require('tls');
//dl  = require('delivery');
var fs = require("fs");
var mysql      = require('mysql');
var express    = require("express");
var app = express();
var http = require('http');
var https = require('https');
//var mkdirp = require('mkdirp');
var path = require('path');
//var nodemailer = require('nodemailer');
//includer
function read(f) {return fs.readFileSync(f).toString();}
function include(f) {eval.apply(global, [read(f)]);}

//var BASE = require('./lib/level1_module');
//BASE.NAME = "YEap";

var pkey = fs.readFileSync('/etc/httpd/ssl/YOUR_FILE.key');
var pcert = fs.readFileSync('/etc/httpd/ssl/YOUR_FILE_com.crt')

var SERVER_PORT = 9000;
 var options = {
    hostname: 'YOUR_PAGE.com',
    port: 9000,
    key: pkey,
    cert: pcert,
    requestCert: true,
    rejectUnauthorized: false,
};

var server = https.createServer(options, app).listen(SERVER_PORT, function(){
  console.log("Express server listening on port " + SERVER_PORT);
});

var io = require('socket.io').listen(server);
server.listen(SERVER_PORT);
console.log('Socket server listening on port : ' , SERVER_PORT);


text:
Q: PIL: ImageGrab.grab() failed - OSError: screen grab failed I have a script that is constantly taking screenshots via PIL ImageGrab. Code looks like this:
def updateScreenshot(self):
        self.screen = ImageGrab.grab()

The updateScreenshot() function is called pretty often, like 2-3 times a second. The script was running fine until i refactored the class and moved all the screenshot related code to an external model class that encapsulates all the screenshot logic. Now my mainclass has:
self.screenshotService = ScreenshotService()

in it's __init__ function. The ScreenshotService then fires updateScreenshot(). The first few attempts of updateScreenshot() still work, after that the following error occurs:
File "...\screenshotService.py", line 15, in updateScreenshot
    self.screen = ImageGrab.grab()
  File "C:\Python34\lib\site-packages\PIL\ImageGrab.py", line 31, in grab
    size, data = grabber()

I found:

*

*https://github.com/python-pillow/Pillow/issues/1601

*Take a screenshot via a python script. [Linux]
but these dont really point me in the right direction.
Any ideas? Thanks.
Python 3.4,
PIL: 5.4.1


text:
Q: Are many generalized formula unprovable (related to Godel's first incompleteness theorem)? Context: I've been reading through the Dover English translation of Godel's paper "On Formally Undecidable Propositions of Principia Mathematica and Related Systems".
It seems the key to producing Godel formulas is the generalization operation, such as the formula "17 Gen r".  Without generalization, it seems impossible to create an unprovable formula.
Looking through the axioms and proof schema earlier in the paper, I did not see any that would allow introduction of generalization.  This suggests to me that many generalized formula are unprovable in Godel's system in the sense that any proof of a generalized formula would require another generalized formula as a premise.  Assuming there's no infinite regress, then working backwards means we end up with a primal generalized formula which has no proof, since there is no precursor generalized formula.  Unless there is a "super generalized formula" that can prove most other generalized formula, which seems implausible, this means there are loads and loads of unprovable generalized formula.
In which case, "17 Gen r" is not particularly notable in being unprovable, except for the fact that we can interpret it as saying "this formula is unprovable" and consequently more formally prove its unprovability.
Am I missing something here?


text:
Q: UICollectionView reloadData resigns first responder/dismisses keyboard when searchBar is in section header I have a UICollectionView that have section header. In the section header I have a UISearchBar. I want to filter the content in my collection view when I type in the search bar. I do this with the following method:
// The method to change the predicate of the FRC
- (void)filterContentForSearchText:(NSString*)searchText
{
    NSString *query = searchText;
    if (query && query.length) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@ or createdAt contains[cd] %@ or noteText contains[cd] %@ or keywords contains[cd] %@", query, query, query, query];
        [self.fetchedResultsController.fetchRequest setPredicate:predicate];
    } else {
        [self.fetchedResultsController.fetchRequest setPredicate:nil];
    }
    NSError *error = nil;
    if (![[self fetchedResultsController] performFetch:&error]) {
        // Handle error
        NSLog(@"Error");
    }
    [self.collectionView reloadData];
}

This method gets called every time the search bar text changes. The line [self.collectionView reloadData] hided the keyboard for every character. Is it possible to reload only the data in a UICollection view and not reload the Supplementary views like section headers headers?
The data in my collectionView comes from a NSFetchResultController.
I'm pretty happy with how my UI works so if there is a simple way to NOT reload the section header, then that would be great!

A: did you tried with one of this options?
To reload just the new items
    [self.collectionView reloadItemsAtIndexPaths:indexPaths];

To reload the complete section
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];

Or, if it doesn't work.. make searchBar  first responder again after your updates
    [self.collectionViewPackages performBatchUpdates:^{
        [self.collectionView reloadData];
    } completion:^(BOOL finished) {
        [self.searchBar becomeFirstResponder];
    }];

A: I finally figured this out after trying many different options. The solution is to make your header of its own section so you can reload the other sections independently without reloading the one your header is attached to.
So:

*

*Section 0

*

*Header

*

*Search bar (or other text fields)

*Rows

*

*(None)

*Section 1

*

*Header

*

*Create an empty UICollectionReusableView and override ...sizeForItemAtIndexPath:(NSIndexPath *)indexPath to return CGSizeZero

*Rows

*

*Your actual rows that would have originally gone with section 0

Then, we you need to reload your data:

[collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];

Your searchbar or text fields should retain their focus while the user is typing and you can update the results in the background.


text:
Q: Problem modifying UITableViewCell accessoryType in tableView:didSelectRowAtIndexPath: I have a transparent table view (UIViewController with subview UIImageView, and another subview UITableView on top of the UIImageView sibling with background = clearColor, UITableViewCells background = clearColor).  I also want taps on the cells to toggle the cell's accessoryType between checkmark and none.   If I modify the UITableViewCell's accessoryType in tableView:didSelectRowAtIndexPath:, sometimes (30-50% of the time, both on the ios4.1 simulator and on a 3GS iphone running os4.1) when toggling from accessoryType None to accessoryType checkmark the checkmark image is painted against an opaque white background instead of a transparent background.   If instead I reload the table (where the accessoryType is also set appropriately for each cell) the transparency works correctly 100% of the time.
Is this a bug?  Or is modifying a cell in tableView:didSelectRowAtIndexPath: not the right thing to do, and that row should be reloaded instead?   Or is there something else I'm missing?
edit: Here's my didSelectRowAtIndexPath code that shows the undesirable behavior:
edit 2: One more detail of what's happening.   It's the very tail end of the deselect animation where the problem happens.   The checkmark appears and is displayed properly & transparently while the deselect animation is running and the blue selection is gradually fading out.   After the deselect animation finishes and the blue is all gone, maybe 1/10 of a second after the selection color is completely gone, is when the checkmark accessory "automagically" turns opaque with no further user input.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ( self.editing )
    {
    }
    else
    {
        [self.myTableView deselectRowAtIndexPath:indexPath animated:YES];
        UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];

        // toggle the selection status of the selected row
        //
        NSNumber *rowObj = [NSNumber numberWithUnsignedInt:indexPath.row];
        if ( [self.selectedRows containsObject:rowObj] )
        {
            // currently selected, now de-select
            //
            cell.accessoryType = UITableViewCellAccessoryNone;
            [self.selectedRows removeObject:rowObj];
        }
        else
        {
            // currently unselected, now select
            //
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            [self.selectedRows addObject:rowObj];
        }
    }
}

A: I think it's cleaner if you move the toogle selection piece of code to
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

and on didSelectRowAtIndexPath call to
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

This way you will reload only the selected row as soon as it is selected, and no need for calling reloadData.
Hope this helps!

A: This post hasn't been updated in 4 months but I figured I would submit my solution as it seems to work and could help somebody else with a similar problem.
Everything happens in the didSelectRowAtIndexPath method. The self.view I call is a tableView (so replace it with your tableView's name, e.g. self.tableView)
// let's go through all the cells to update them as I only want one cell at a time to have the checkmark next to it
for (int i=0; i<[self.detailsArray count]; i++) {
    // whenever we reach the cell we have selected, let's change its accessoryType and its colour
    if (i == indexPath.row) {
        // that's the row we have selected, let's update its
        UITableViewCell *cell = [self.view cellForRowAtIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        cell.textLabel.textColor = [UIColor colorWithRed:51.0f/255.0f green:102.0f/255.0f blue:153.0f/255.0f alpha:1.0f];
    }
    // if it isn't the cell we have selected, let's change it back to boring dark colour and no accessoryType
    else {
        UITableViewCell *cell = [self.view cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.textLabel.textColor = [UIColor darkTextColor];
    }
}

// don't forget to deselect the row
[self.view deselectRowAtIndexPath:indexPath animated:YES];

A: this UITableViewDelegate method:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

is called right before displaying a cell. Modifying your accessory view there should work.

A: In debugging another problem in an unrelated project with a custom table row selection animation, I found that if the cell selection style is not UITableViewCellSelectionStyleNone, then any changes to the cell performed in didSelectRowAtIndexPath are subject to glitches and other desirable results (the changes made to cell N do not show up until cell != N is selected later, and animations performed on the cell never show up at all).   When I changed the selection style to UITableViewCellSelectionStyleNone, then all visual cell changes made in didSelectRowAtIndexPath show up right away without problems.


text:
Q: Choose an infinite GP from given terms for a particular sum Is it possible to choose an infinite GP from amongst the terms 1, 1/2, 1/4, 1/8, 1/16 ... with a sum a) 1/5? b) 1/7 ?
My approach was simply choosing terms and probable ratios to match the sum...I would be grateful if you could reveal any trick for this question?

A: Since all terms are of the form $\frac{1}{2^n}$, any geometric progression will be with ratio $\frac{1}{2^k}$
The summation of a geometric series is:
$$\sum\limits_{k=0}^\infty ar^k = \frac{a}{1-r}$$
The question then is what choice of $a$ (initial term) and what choice of $r$ (ratio) will give the desired results.
Since $a$ and $r$ will both be of the form $\frac{1}{2^n}$ we have the sum must be of the form
$$\frac{\frac{1}{2^m}}{1-\frac{1}{2^n}} =\frac{2^{n-m}}{2^n-1}$$
for some given $n$ and $m$
The question is, can you find non-negative integers $n$ and $m$ such that $\frac{2^{n-m}}{2^n-1}$ is equal to $\frac{1}{5}$?  is equal to $\frac{1}{7}$?  If not, then why?  If yes, which?

For $\frac{1}{5}$, the question becomes whether we can find $a,b$ such that $5\cdot 2^a = 2^b-1$.  Notice that for $a\geq 1$ and $b\geq 1$ the left side is even while the right side is odd.  If $b=0$ the right side is zero and the left side is positive.  If $a=0$, the left side is equal to $5$, but no integer $b$ satisfies $2^b-1=5$
Thus $\frac{1}{5}$ is impossible.
For $\frac{1}{7}$, we ask if we can find $a,b$ such that $7\cdot 2^a=2^b-1$.  From the same logic, we see that they cannot both be positive and $b$ cannot be zero.  This leaves $a=0$ and we find that $b=3$ works.
This corresponds back to our $n$ and $m$ from before implying the geometric progression $\frac{1}{8},\frac{1}{64},\frac{1}{512},\dots$ has sum equal to $\frac{1}{7}$

A: Nothe that sum of an infinite G.P. is given by $\displaystyle\sum_{n=1}^{\infty} ar^{n-1}=\frac{a}{1-r}$ where $a$ is the first term and $r$ is the common ratio.
Note that in the series $\displaystyle\frac{1}{1},\frac{1}{2},\frac{1}{4}...$ all terms have a common ratio of the form $\frac{1}{2k}$ where $k\in\mathbb Z^+$.Or,all possible common ratios are $\frac{1}{2}$ or $\frac{1}{4}$ or $\frac{1}{8}$ and so on.This is because whenever we divide any two terms in the series we get a number of the form $\frac{1}{2k}$.
So,$$\frac{a}{1-\frac{1}{2k}}=\frac{1}{5}$$
$$\implies a=\frac{2k-1}{10k}$$
Now,$\frac17$ or $\frac15$ has $1$ in numerator.
So,$k=1$ in $a$ for numerator to become $1$.Plugging $k=1$,we get $a=\frac{1}{10}$.Now,this is not a term of the series.So,we have disproved one case.
Do the same for the other case.
Hope this helps!!

A: A geometric series picked from the given series will have initial term $\frac1{2^a}$ ($a\ge0$) and ratio $\frac1{2^r}$ ($r\ge1$). The sum of this sub-series will be
$$\frac{\frac1{2^a}}{1-\frac1{2^r}}=\frac{2^{r-a}}{2^r-1}$$
We cannot pick a geometric series for (a) that sums to $\frac15$ because a power of two (the numerator) multiplied by 5 cannot equal a Mersenne number (the denominator); this may be seen by comparing binary expansions.
For (b), however, we can find a geometric series summing to $\frac17$; take $r=a=3$.


text:
Q: Android TextView's Background Not Moving When TextView.Padding Changes I have a TextView that I created in the main.xml. In my app.java I am dynamically positioning that TextView based on where the user taps the screen. The problem I am having is that when I call myTextView.setPadding(100,100,0,0), it moves the actual Text of the TextView, but does not move the Colored Background of the TextView.
Ideas?

A: The padding only affect the contents of the View, you could embed your View inside a LinearLayout and change the padding of the LinearLayout to move the TextView.

A: If you want to move the entire contents you might want to use margins instead.

A: You may use animation to move a view.
Animation a = new TranslateAnimation((oldPos),
                 newPos, 0.0f, 0.0f);
        a.setDuration(300);
        a.setStartOffset(100);
        a.setRepeatMode(Animation.ABSOLUTE);
        a.setFillAfter(true);

        a.setInterpolator(AnimationUtils.loadInterpolator(this.getContext(),
                        android.R.anim.accelerate_decelerate_interpolator));

 View.startAnimation(a);


text:
Q: Multipart form component "cannot POST / divespotform" not working parseInt issue? I have  a multipart form that I am nearly finished working on that is still not posting to my backend database. Could this be to do with the fact that I am not parsing my two ID fields as ints correctly?
The two text fields and file field look like they are being sent in the request correctly. Is the random pink/blue/black/red symbols the image being sent to the backend? Should my two ID int fields also be showing here as they are on the same form?
The method I have for my Argument 1 is not an object seems to be related to the diveSpotForm line of my handle submit method. Am I passing the form data to the action correctly? I think I might have over complicated the method not posting straight from the form component.

form component
 const [spot, setSpot] = useState({
        diveLocation: "",
        diveRegionID: parseInt(``),
        diveTypeID: parseInt(``),
        diveSpotDescription: "",
        diveSpotPhotos: "",
        error: ''
    });

    // all onChange functions do the exact same thing, so you only need one
    // pass to a component like onChange={handleChange('typeID')}
    const handleChange = (property) => (e) => {
        setSpot({
            // override the changed property and keep the rest
            ...spot,
            [property]: e.target.value,
        });
    }

    // get access to dispatch
    const dispatch = useDispatch();

    // useEffect with an empty dependency array is the same as componentDidMount
    useEffect(() => {
        dispatch(requireFieldData());
    }, []);

    const handleSubmitDiveSpot = () => {

        const diveSpotForm = new FormData(document.querySelector("diveSpotForm"))
        console.log('diveSpotForm', diveSpotForm);

        const diveSpot = {
            diveLocation: spot.diveLocation || undefined,
            diveRegionID: spot.diveRegionID || undefined,
            diveSpotTypeID: spot.diveSpotTypeID || undefined,
            diveSpotDescription: spot.diveSpotDescription || undefined,
            diveSpotPhotos: spot.diveSpotPhotos || undefined
        }

        // do some stuff with the form
        createDiveSpot(diveSpot).then((data) => {
            const newSpot = data.error
                ? {...spot, error: data.error}
                : {...spot, error: '', open: true};
            setSpot(newSpot);
            dispatch(addDiveSpot(newSpot));
        })
    }

    const classes = useStyles;

    return (

        <form className="diveSpotForm" method="POST" encType="multipart/form-data" onSubmit={handleSubmitDiveSpot}>
            <>
                <Grid container spacing={3}
                      direction="row"
                      justify="center"
                      alignItems="center">
                    <Grid item xs={4}>
                    <FormControl className={classes.formControl}>
                        <PopulateDropdown
                            dataList={diveTypeList}
                            titleProperty={"diveType"} // option label property
                            valueProperty={"diveTypeID"} // option value property
                            name="diveType"
                            placeholder="Dive Type"
                            label="Select Dive Type"
                            value={spot.diveTypeID}
                            onChange={handleChangeInt(parseInt("diveTypeID"))}/>
                    </FormControl>
                    </Grid>

                   ........

                    <Grid item xs={10}>
                        <FormControl fullWidth className={classes.margin}>
                            <TextField
                                label="Description"
                                name="diveSpotDescription"
                                value={spot.diveSpotDescription}
                                onChange={handleChange("diveSpotDescription")}
                                multiline
                                rowsMax={6}/>
                        </FormControl>
                    </Grid>

                    <Grid item xs={12}>
                        <FormControl fullWidth className={classes.margin}>
                            Photo Upload
                            <input
                                type="file"
                                name="photo"
                                value={spot.diveSpotPhotos}
                                onChange={handleChange("diveSpotPhotos")}/>
                        </FormControl>
                    </Grid>

                    <Grid item xs={3}>
                        <Button variant="primary" type="submit">
                            Submit</Button>

                    </Grid>
                </Grid>
            </>
        </form>

action
export const createDiveSpot = async (diveSpot) => {
    try {
        let response = await fetch('http://localhost:5002/api/divespot/createdivespot', {
            method: 'POST',
            headers: {
                "Content-Type":"multipart/form-data"
            },
            body: new FormData(diveSpot)
        })
        return await response.json()
    } catch(err) {
        console.log(err)
    }
}

backend
exports.createDiveSpot = async (req, res) => {

    const fileNameWithExtension = `${req.file.filename}-${req.file.originalname}`
    const newPath = `./assets/diveSpot/${fileNameWithExtension}`

    fs.rename(req.file.path, newPath, function (err) {
            if (err) {
                console.log(err)
                res.send(500)
            }
            diveSpot.create({
                diveLocation: req.body.diveLocation,
                diveRegionID: req.body.diveRegionID,
                diveSpotTypeID: req.body.diveLocation,
                diveSpotDescription: req.body.diveSpotDescription,
                photos: fileNameWithExtension,
            })
                .catch((err) => {
                    res.status(500).send({
                        message: err.message || 'Some error occurred while creating the post.',
                    })
                })
        }
    )}

route
app.post('/api/divespot/createdivespot', upload.single("diveSpotPhotos"), controller.createDiveSpot);

update
I have also tried the below handleSubmit method and it is still showing the same two argument 1 is not an object errors. As there are two of them it looks like it could be the two id fields ( which are also not appearing on the payload request in the console).
function diveSpotForm(e: React.FormEvent<HTMLFormElement>) {
        e.preventDefault();
        const formData = new FormData();
        formData.append("diveLocation", spot.diveLocation);
        formData.append("diveRegionID", spot.diveRegionID);
        formData.append("diveSpotTypeID", spot.diveSpotTypeID);
        formData.append("diveSpotDescription", spot.diveSpotDescription);
        formData.append("photos", file);
        axios.post("http://localhost:5002/api/divespot/createdivespot", formData);
    }

A: Hard to figure this out without full code, runnable project etc...
But here are some problems that I could spot in your code.

*

*The FormData constructor should get form object as it's argument,
not an object with values (and you are redefining the same diveSpot variable with no reason - remove this let diveSpot = new FormData()).
https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

*Here is the backend function fixed (at least an attempt)
 exports.createDiveSpot = async (req, res) => {
    try {
        console.log(req.diveSpot);

        // if (req.diveSpot == undefined) {
        //     return res.send(`You must select a file.`);
        // }

        return diveSpot.create({
            diveLocation: req.diveSpot.diveLocation,
            diveRegionID: req.diveSpot.diveRegionID,
            diveSpotTypeID: req.diveSpot.diveSpotTypeID,
            diveSpotDescription: req.diveSpot.diveSpotDescription,
            // You want the file location here
            diveSpotPhotos: "/assets/" + req.file.filename
            ),
        }).then((diveSpot) => {
            fs.writeFileSync(
                __basedir + "/assets/" + req.file.filename,
                req.file.buffer
            );

            return res.json(`File has been uploaded.`);
        });
    } catch (error) {
        console.log(error);
        return res.send(`Error when trying upload images: ${error}`);
    }
};

*You action fixed (Again an attempt)

export const createDiveSpot = async (diveSpot) => {
   return fetch('http://localhost:5002/api/divespot/createdivespot', {
            method: 'POST',
            headers: {
                "Content-Type":"multipart/form-data"
            },
            body: new FormData(diveSpot)
        })
.then(response => response.json())
.catch(err => console.log(err));

}


text:
Q: How to disable XSS clean particular page in codeigniter? How to disable XSS clean particular page in codeigniter? I am new codeigniter framework. How to fix this?

A: try this one
$this->input->post('message',false);


text:
Q: vb.net continue for inside a for each i have a for each loop inside a for loop, the for each loop checks if a value in some column in the current row exists in an array, if it exists i want to do whats in the for loop and if it doesnt exist i want to continue the for loop
for i = 0 To DataGridView1.RowCount - 1
        For Each id In IDs
            If (DataGridView1.Item(1, i).Value <> id) Then
               'continue the for loop, by continue i mean using continue statement and not executing the outer for loop for this case
            End If
        Next
  'do for loop things
Next

what i am trying to do is to do calculations for the rows that have a specific id and skip the rows with the ids that are not in the array.

A: You can use  Exit For to exit the inner For Each loop.  The outer For loop will be resumed where it left off.
Exit For

Optional. Transfers control out of the For Each loop.
When used within nested For Each loops, Exit For causes execution to exit the innermost loop and transfers control to the next higher level of nesting.

http://msdn.microsoft.com/en-us/library/5ebk1751.aspx
for i = 0 To DataGridView1.RowCount - 1
        For Each id In IDs
            If (DataGridView1.Item(1, i).Value <> id) Then
               Exit For 'continue the for loop
            End If
        Next
  'do for loop things
Next

A: Do you want to "do for loop things" only if there is a match? Why not just like this?
For i = 0 To DataGridView1.RowCount - 1
    doThings = False
   For Each id In IDs
      If (DataGridView1.Item(1, i).Value = id) Then
        doThings = True
        Exit For
      End If
  Next
  If doThings Then
    ** do for loop things
  End If
Next

Could be improved by creating more methods

*

*a function to determine whether an id appears in "IDs". Is it a List? Can you use IDs.Contains()

*a method to "do for loop things"

A: Rather than checking not equal condition, check for equal condition.
for i = 0 To DataGridView1.RowCount - 1
    For Each id In IDs
        If (DataGridView1.Item(1, i).Value == id) Then
            'continue the for loop
        End If
    Next
    'do for loop things
Next

A: Exit Statement (Visual Basic) - MSDN
for i = 0 To DataGridView1.RowCount - 1
    For Each id In IDs
        If (DataGridView1.Item(1, i).Value <> id) Then
           Exit For ' Exit this For Each loop
        End If
    Next
'do for loop things
Next

A: The doThings answer is fine and readable, but to actually use a Continue For you need to change the inner For loop to one of the other loops availble to VB.NET.
for i = 0 To DataGridView1.RowCount - 1
    Using EnumId As IEnumerator(Of String) = IDs.GetEnumerator
        'For Each id In IDs
      While EnumId.MoveNext
        Dim id = EnumId.Current
            If (DataGridView1.Item(1, i).Value <> id) Then
               'continue the for loop, by continue i mean using continue statement and not executing the outer for loop for this case
               Continue For
            End If
        'Next
      End While
    End Using
  'do for loop things
Next

(Typed in without checking syntax in the IDE.)


text:
Q: drop down menu updates inner HTML when changed, javascript I have drop down menus, the last 2 are price and tickets which then makes a calculation and shows the total amount on screen when selected.  It works fine although if i change the selection to a different price the total does not update.  Also the same idea applies to the part where the user selects 4 or more tickets and an message appears on screen.  Im sure its something simple but i cant seem to figure it out.
I have attached a Jsfiddle.
http://jsfiddle.net/Dwdqg/
function totalPrice(ticketCount,priceAmount)
{
    if (tickets.selectedIndex != 0 && price.selectedIndex != 0)  // if the price and tickets is not 0 or not selected
    {
        tickets.onchange = ticketCount;  //when tickets is changed assign the index to var ticketCount

        price.onchange = priceAmount;

        var ticketCount = tickets.value;  //get the value of ticketCount index

        var priceAmount = price.value;

        var totalPrice = (ticketCount * priceAmount);

        document.getElementById("totalPrice").innerHTML = ("Total Price £" + totalPrice);

    }

    if (ticketCount >= 4)  // if ticketCount is 4 or more
    {
        totalPrice = totalPrice + 10;  // add on 10 to the price

        document.getElementById("totalPrice").innerHTML = ("Total Price £" + totalPrice);

        document.getElementById("moreTickets").innerHTML = ("Buying four or more tickets will add an additional £10 fee.")

    }

}

A: You're not calling totalPrice in your change handlers.
For example:
price.onchange = function()
  // totalPrice needs to be called
}

You've attached it here
<select name="tickets" id="tickets" onChange="totalPrice(tickets)" style="width:120px">

However, that only responds to changes to number of tickets. You haven't attached it to the other elements.
Also - your onchange only fires once because you're replacing the option fields using fillList after the change event fires. You can either reattach the handler or have it respond to a click event.
With that said - I don't recommend attaching handlers as HTML attributes and I suggest cleaning up your code to be more readable.


text:
Q: How to connect to SQL Server Express DB from Server Explorer VS 2010? I'm trying to connect to SQL DB from Server Explorer to generate context classes for Linq to SQL. Doing it like described here: http://visualcsharptutorials.com/ado-net/querying-database-linq-to-sql/
I'm getting "This file is in use." error when I try to connect. Even if I stop SQL Server in Configuration Manager I get the same error.
I can connect to DB using SSMS at the same time.
What am I doing wrong? Is it possible to connect to a DB simultaneously from VS and SSMS?
Thanks

A: When you say I can connect to DB using SSMS at the same time this sounds to me as if you've attached the database to SQL Server Express, and you're talking to it through its logical database name.
When you have done this (which is the best approach, in my opinion), then SQL Server (Express) is using that file and controls all access to it; you cannot just reference the .mdf file from your VS solution - you need to use the SQL Server approach and connect to the SQL Server (Express) instance and pick the database:

Select

*

*Microsoft SQL Server (SqlClient) from the Data Source dropdown (NOT something like "database file")

*the server name and instance you want to use (typically: .\SQLExpress - the SQLExpress instance on your local machine)

*the database from the Select or enter a database name dropdown

*DO NOT use anything that has to do with "attach database file" or anything like that


text:
Q: Updated Bootstrap + SASS in ASP.NET CORE 2, with Gulp? I'm trying to add Bootstrap with SASS capability to my ASP.NET Core 2 project, but have difficulty accomplishing this. I used NPM to install Bootstrap into node_modules, then got Gulp to move minified css and js dependencies into my wwwroot directory. Now I want to have a SASS file where I override Bootstrap's defaults to fit my needs, and this is where I'm stuck. Here's my Gulp code, 'compile-sass' is not working. I get missing binding error.
const gulp = require('gulp');
const concat = require('gulp-concat');
const sass = require('gulp-sass');

const root = "./wwwroot/";
const bootstrapStyles = "node_modules/bootstrap/dist/css/bootstrap.min.css";
const bootstrapSass = "node_modules/bootstrap/scss/bootstrap.scss";
const bootstrapScripts = [
    "node_modules/jquery/dist/jquery.min.js",
    "node_modules/popper.js/dist/umd/popper.min.js",
    "node_modules/bootstrap/dist/js/bootstrap.min.js"
];

gulp.task('default', ['build-all']);
gulp.task('build-all', ['build-css', 'build-js']);

gulp.task('build-css', () => {
    return gulp.src(bootstrapStyles)
        .pipe(gulp.dest('./wwwroot/'));
});

gulp.task('build-js', () => {
    return gulp.src(bootstrapScripts)
        .pipe(concat('bootstrap.min.js'))
        .pipe(gulp.dest(root));
});

gulp.task('compile-sass', () => {
    gulp.src(bootstrapSass)
        .pipe(sass())
        .pipe(gulp.dest(root));
});

// watch bootstrap-overrides.scss for changes and recompile SASS
gulp.task('watch-sass', () => {
    gulp.watch(root + 'bootstrap-overrides.scss', ['compile-sass']);
});

This is the exact excerpt of the problem:
    gulp.task('compile-sass', () => {
    gulp.src(bootstrapSass)
        .pipe(sass())
        .pipe(gulp.dest(root));
});

Edit: Solved the build error by running the following command: npm rebuild node-sass
My bootstrap-overrides.scss edits are not changing variable values. How do I correctly compile SASS?

A: Solved it.
const gulp = require('gulp');
const concat = require('gulp-concat');
const sass = require('gulp-sass');
const rename = require('gulp-rename');

const root = "./wwwroot/";
const vendorScripts = [
    "node_modules/jquery/dist/jquery.min.js",
    "node_modules/popper.js/dist/umd/popper.min.js",
    "node_modules/bootstrap/dist/js/bootstrap.min.js"
];

const vendorStyles = "node_modules/bootstrap/scss/bootstrap.scss";
const customerStyleOverrides = root + "scss/*.scss";

gulp.task('default', ['build-vendor']);

gulp.task('build-vendor', ['build-vendor-css', 'build-vendor-js']);

// merge javascripts into a single vendor.min.js file and save it to wwwroot
gulp.task('build-vendor-js', () => {
    return gulp.src(vendorScripts)
        .pipe(concat('vendor.min.js'))
        .pipe(gulp.dest(root));
});

// compile bootstrap and save as vendor.min.css to wwwroot
gulp.task('build-vendor-css', () => {
    return gulp.src([vendorStyles, customerStyleOverrides])
        .pipe(sass({ outputStyle: 'compressed' }))
        .pipe(rename('vendor.min.css'))
        .pipe(gulp.dest(root));
});

// watch for changes to styles.css and recompile bootstrap on styles change
gulp.task('watch-sass', () => {
    gulp.watch(root + "scss/styles.scss", ['build-vendor-css']);
});


text:
Q: Floating point assembly on intel processor I have been studying how floating point operations are performed on a 32 bit intel machine. I have disassembled the following lines of C code to obtain how the compiler translates these lines on assembly.
a = 13;
b = 5;
d = (float) a / (float) b;

And here is the disassembled version of the code shown above:
mov    DWORD PTR [ebp-0x10],0xd
mov    DWORD PTR [ebp-0x14],0x5
fild   DWORD PTR [ebp-0x10]
fild   DWORD PTR [ebp-0x14]
fdivrp st(1),st
fstp   DWORD PTR [ebp-0x18]

What I find confusing is the fdivrp and fstp instructions. From what I read the code above will store the result of the floating point division on the st(1) register, and then pop the top of stack making st(1) the top and not st(0). However the next fstp instruction stores the contents of st(0) to the memory location pointed by the address ebp-0x18 and then pops the stack making st(1) the top. I believe I have misunderstood the documents on how these instructions operate as my understanding will not store the result in memory. I would be grateful if someone can please explain how exactly these 2 instructions operate.

A: Floating point registers are always addressed relative to the current stack top. Thus, st(0) is always the stack top. The fdivrp st(1), st places the result in st(1) and then immediately pops st(0) so the stack only holds a single item, which is the new st(0) containing the result. The fstp writes it to memory and removes it from the fpu stack, leaving it empty.


text:
Q: TestNG groups with custom SpringContext I am doing a refactoring of my entire test suite by grouping the different test types into multiple groups ( unittest, integration test ...tests).
TestNG allows you to do that with the groups annotation like below
@Test(groups = [ "integrationTest" ])
class MyGroupedTest : MySprpingTestClass() {

  private lateinit var myVar: MyVarService

  @Autowired
  private lateinit var myRepo: MyRepo

  @Autowired
  @Named("requires_new")
  lateinit var txTemplate: TransactionTemplate

I encounter that when adding the group to my Test class, TestNg throughs does not loads my SpringApplicationContext and claims that MyRepo dependency is not initliazed
The following link redirects me to

But I do not see how does it translate to my problem.
Note that my class is inheriting from a base class which bootstraps a small Spring application with few beans and a connection to database with not issues