text:
Q: Custom web control. how to render child controls I'm trying emulate the IE Webcontrols Pageview system.
Basically I have
<c:Multipage>
<c:pageview>
[Block of ASP.NET / HTML]
</c:pageview> (More pageviews)</c:Multipage>
And I want to simply render the inner text of the pageview.
I've tried
protected override void  AddParsedSubObject(object obj) {
...
ControlList.Add((Control)obj);
...
}
and
Render(HtmlTextWriter output) {
...
foreach (Control c in ControlList) c.RenderControl();
...
}
It seems to render simple things but any more complex set ups it makes mistakes on. I don't think this is the way to do it at all. I'm having difficulty finding out how I am supposed to be able to just render this. And whether I should treat it as text or child controls

A: You shouldn't need to explicity call Render.  If the control is part of your page's control tree, it will get rendered.

A: It generally depends on whether or not you are display effectively read-only information or control information that would require view-state information. You can output raw HTML if it's read-only just fine but if it contains controls and requires view-state interaction then you'll want to create actual control objects and insert them into the containing object in the code behind.
It really depends on your specific situation, but it sounds like you could just output raw html into a generic DIV control or something, without knowing the specifics though it's a little tough to point you one way or the other.


text:
Q: Use DLR to run code generated with CompileAssemblyFromSource? Following up on this excellent answer, I'm wondering if the DLR using the dynamic keyword can allow a less verbose way of writing code for the generated assembly.
For example, can the aforementioned answer's code:
using (Microsoft.CSharp.CSharpCodeProvider foo =
           new Microsoft.CSharp.CSharpCodeProvider())
{
    var res = foo.CompileAssemblyFromSource(
        new System.CodeDom.Compiler.CompilerParameters() {
            GenerateInMemory = true
        },
        "public class FooClass { public string Execute() { return \"output!\";}}"
    );

    var type = res.CompiledAssembly.GetType("FooClass");
    var obj = Activator.CreateInstance(type);
    var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
}

become something like:
using (Microsoft.CSharp.CSharpCodeProvider foo =
           new Microsoft.CSharp.CSharpCodeProvider())
{
    var res = foo.CompileAssemblyFromSource(
        new System.CodeDom.Compiler.CompilerParameters() {
            GenerateInMemory = true
        },
        "public class FooClass { public string Execute() { return \"output!\";}}"
    );

    var type = res.CompiledAssembly.GetType("FooClass");
    dynamic obj = Activator.CreateDynamicInstance(type);
    var output = obj.Execute();
}

A: Yes, you can do that and it works well.  However, while using the dynamic keyword is more convenient, it utilizes late-binding and is still just as unsafe, in that sense, as explicitly using reflection.  If your design allows it, it is even better to use a shared interface or base class for early-binding.  You can do this by creating a public type in your assembly or in a third, shared assembly, and then add a reference to that assembly from the new one you are dynamically compiling.  Then, in the generated code, you can inherit from that shared type in the referenced assembly.  For instance, create an interface:
public interface IFoo
{
    string Execute();
}

Then dynamically compile the assembly like this:
using (Microsoft.CSharp.CSharpCodeProvider foo = new Microsoft.CSharp.CSharpCodeProvider())
{
    var params = new System.CodeDom.Compiler.CompilerParameters();
    params.GenerateInMemory = true;

    // Add the reference to the current assembly which defines IFoo
    params.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

    // Implement the IFoo interface in the dynamic code
    var res = foo.CompileAssemblyFromSource(params, "public class FooClass : IFoo { public string Execute() { return \"output!\";}}");
    var type = res.CompiledAssembly.GetType("FooClass");

    // Cast the created object to IFoo
    IFoo obj = (IFoo)Activator.CreateInstance(type);

    // Use the object through the IFoo interface
    obj.Execute();
}

Depending on how much control you have over the dynamic code, this may or may not be possible, but when it is, it's nice to have the compile-time type-checking.  For instance, if you tried to execute:
IFoo obj = (IFoo)Activator.CreateInstance(type);
obj.Execcute();

That second line would immediately fail to compile because it's spelled wrong, whereas with the dynamic keyword or reflection, that line would successfully compile but it would cause a run-time exception.  For instance, the following will not get a compile-time error:
dynamic obj = Activator.CreateDynamicInstance(type);
obj.Execcute();

A: That is one of the scenarios that the DLR was designed for.  You can use it that way to invoke members of a dynamically loaded type while avoiding all of the extra typing from manually calling .GetMethod() and .Invoke().

redpajama_set_name: RedPajamaStackExchange


text:
Q: Determining the ideals of a quotient ring Given an ideal $I = \langle x^3 - x\rangle \subseteq \Bbb{R}[x]$, determine the ideals in the quotient ring $\Bbb{R}[x]/I$.
I understand that the quotient ring is of the form $k[x_1...x_n]/I$ where I is an ideal in $k[x_1...x_n]$. I also understand that the ideals of the quotient ring are in one-to-one correspondence with the ideals of $k[x_1...x_n]$ containing $I$.
However, I'm really confused on how to actually go about finding the ideals of the quotient ring given a specific ideal. Any hints or suggestions would be appreciated, thank you.

A: Note that we can factor $x^3 - x = x(x^2 - 1) = x(x + 1)(x - 1)$. Now, by the Chinese Reimander theorem:
$$\mathbb R[X]/\langle x^3 - x\rangle = \mathbb R[X] /\langle x(x + 1)(x-1) \rangle = \mathbb R[X]/\langle x \rangle \times\mathbb R[X]/\langle x+1 \rangle \times\mathbb R[X]/\langle x-1 \rangle  $$
We know that:

*

*$\mathbb R[X]/\langle x \rangle \simeq \mathbb R$, since quotienting by $x$ kills all polynomials of degree 1 or higher. What's left are the reals

*Similarly, $\mathbb R[X]/\langle x+1 \rangle \simeq \mathbb R [X]/ \langle x-1 \rangle \simeq  \mathbb R$.

To expand on why $\mathbb{R}[X]/\langle x \rangle$ contains only real numbers, notice that for any $p(x) \in \mathbb R[X]$, we can find polynomials $q(x), r(x)$ such that $p(x) = q(x) \cdot x + r(x)$ (by division). Now, we also know that $degree(r(x)) < degree(x)$. If This were not the case, then I could have my quotient be some polynomial, and thereby "remove" higher degree terms.
But now, in the quotient ring $\mathbb R[X]/ \langle x \rangle$, we know that $x \simeq 0$, and hence $p(x) = q(x) \cdot x + r(x) \simeq r(x)$. Since $r(x)$ has degree 0, it's "just a real number".
Now see that the exact same argument will hold for $\langle x + 1\rangle$ and $\langle x - 1 \rangle$, since all we depended on was the degree of $x$.
In general, a ring $\mathbb R [X] / \langle p(x) \rangle$ can only have polynomials of degree less than the degree of $p(x)$, since any polynomial of equal or higher degree can be factorized into some multiple of $p(x)$ plus a remainder. In the quotient ring, $p(x)$ goes to zero, so the multiple of $p(x)$ goes to zero, so all that's left is the remainder.
So, the ring that we have is actually $\mathbb R \times  \mathbb R \times \mathbb R$.
Since $\mathbb R$ is a field, it has only two idels: the zero ideal and the ring itself.
Now, note that:

*

*the product of ideals is an ideal of the product ring

*Every ideal of the product ring is a product of ideals

and we complete the proof, since the set of all ideals will all be:
$$
\{0, \mathbb R\} \times \{0, \mathbb R\} \times \{0, \mathbb R\}
$$

A: Because $\Bbb{R}$ is a field, the polynomial ring $\Bbb{R}[x]$ in one indeterminate is a principal ideal domain. That means every ideal is of the form $\langle f\rangle$ for some $f\in\Bbb{R}[x]$. Now use the fact that
$$\langle x^3-x\rangle\subset\langle f\rangle
\qquad\iff\qquad
x^3-x\in\langle f\rangle
\qquad\iff\qquad
f\text{ divides }x^3-x.$$


text:
Q: Android how to pass url in android iframe webview? Android how to pass url in android iframe webview?
I'm trying to pass url dynamically form server so what i do
if(ResponseProduct.video!=null) {

                            String html = "";
                            WebView webView = (WebView) view.findViewById(R.id.video);
                            webView.setVisibility(View.VISIBLE);
                            webView.getSettings().setPluginState(WebSettings.PluginState.ON);
                            webView.getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);
                            webView.getSettings().setJavaScriptEnabled(true);
                            webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
                            webView.getSettings().setSupportMultipleWindows(true);
                            webView.setWebChromeClient(new WebChromeClient());
                            webView.setHorizontalScrollBarEnabled(false);
                            webView.loadData(html, "text/html; video/mpeg", "UTF-8");

                        }

A: You need to put String url path in src like :
 String videoPath="http://api.thingspeak.com/channels/31592/charts/1?width=450&height=260&results=60&dynamic=true\\";

 String html = "";

if videoUrl is null or  not valid then your page is not load then you need to hide webView
Here is code :
private boolean isValidUrl(String url) {
      Pattern p = Patterns.WEB_URL;
      Matcher m = p.matcher(url.toLowerCase());
      if(m.matches())
         return true;
      else
        return false;
}

then after load it into webView
 webview.getSettings().setJavaScriptEnabled(true);
if(videoPath!=null && isValidUrl(videoPath)
{
mWebView.setVisibility(View.VISIBLE);
webview.loadData(html, "text/html", null);
    }

else
webview.setVisibility(View.GONE);


text:
Q: Change Widget Layout Settings In Blogger In the developped HTML the Image1 widget lines are explicited by b:section and b:widget lines. I want to change the background color and the border settings but where do I put them in the code? It's Blogger Watermark Template. I dont' show the URL because it's private.  Thank's

             https://blogger.googleusercontent.com/img/a/AVvXsEj6giznUBl4gJnRYU6bd5ZoSYI6E9d0vfu59sR41S1NHWjXYD8B7xBxKH43YYKNG1mNztQiOgF8Kn5xeeT7KdL1COuA1LynlL7ZLn4B17X14fd0kGwHQyKRxMYjoQusknfhmLL922V9RKHn4mCk4rkJV4BZdmWiLibUlivhw_5DLpAk175udEHc8I8D=s900
             71
             150
             false
             845

<data:title/>

        <data:caption/>


text:
Q: How is it possible to see C# code after compilation/optimization? I was reading about the yield keyword when I came across a sample chapter from C# in Depth: http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx.
The first block of code utilizes the yield keyword to make a simple iterator. But, the second block of code shows this code after the compiler has had its way with it. Among other things, it has exploded the yield statement into a state machine.
Several other examples of code being modified by the compiler is evident on the page.
My question is: Was the author actually able to access the code after compilation, or did he infer what it was going to look like?

A: The author himself mentioned:

Obviously the compiler doesn't actually produce C#, but I've used Reflector to decompile the code as C#.

in the same paragraph, titled High level overview: what's the pattern?

A: Probably both.  It's quite easy to reverse-engineer compiled assemblies using Reflector.  And the C# language spec, which defines how various syntactic-sugary things are compiled, is a public document.  The author could have used either approach, or a mixture of the two.

A: Check out ildasm to take a look at the compiled IL.
(Really, it's good fun once you get your eye in)

A: .NET CLR actually has a form of assembly called MSIL, along with an assembler and dissembler. So yes, you can actually compile the code, then see the exact compiled CLR instructions.
https://web.archive.org/web/20211020103545/https://www.4guysfromrolla.com/articles/080404-1.aspx

A: dotPeek by JetBrains
https://www.jetbrains.com/decompiler/
It's free and easy to use :)

A: You can have a look using Reflector, that's probably your best bet:
http://reflector.red-gate.com


text:
Q: 2D Laplace Equation with Sine-squared BC I am having a bit of trouble solving the 2D Laplace Equation
$$\nabla^2u(y,z) = 0$$
with 2 BCs being

*

*$\left.\dfrac{\partial u}{\partial y}\right|_{y=0} = 0$

*$u\left(y=\frac{h}{2},z\right) = c\sin^2kz$

for a constant $c\neq0$.In previous mathematics and engineering classes, we have used separation of variables to solve the 2D Laplace equation, which resulted in sinusoidal solutions for one of the variables, and usually the problem was constructed such that at least one BC was periodic (first power) so that a matching solution could be found. How do I go about solving the Laplace equation for a sine-squared boundary?
Thanks!


text:
Q: the equation number jumps to the left of the page I wrote a code and I wonder following the regular order , the number jumps to the left of the page
\documentclass[11pt,a4paper,twoside,openright]{report}

\usepackage{setspace}
\usepackage{graphicx}
\usepackage{tabularx}
\usepackage{tabu}
\usepackage{subfigure}
\usepackage{afterpage}
\usepackage{amsmath,amssymb}
\usepackage{rotating}
\usepackage{fancyhdr}
\usepackage[scriptsize]{caption}
\hyphenation{a-gen-tiz-za-zio-ne}
\usepackage{float}
\usepackage[parfill]{parskip}
\graphicspath{ {images/} }

\usepackage[a4paper,lmargin=2cm,rmargin=2cm]{geometry}

%\setlength{\paperwidth}{16cm}
%\setlength{\paperheight}{24cm}
%\setlength{\oddsidemargin} {2. cm}
%\setlength{\evensidemargin} {2. cm}
%\addtolength{\oddsidemargin} {-0.4 cm}
%\addtolength{\evensidemargin} {-0.4 cm}
%\linespread{1.1}

\usepackage[USenglish]{babel}
\usepackage[latin1]{inputenc}
\renewcommand{\captionfont}{\normalfont \sffamily \itshape \small}

\pagestyle{empty}

\begin{document}

\begin{equation}\label{1}

$(SF1, SF2, SF3, SF4, SF5) =  \int_{-\frac{h}{2} - z0}^{\frac{h}{2} - z0} (\sigma11,\sigma22,\sigma12,\sigma13,\sigma23)dz$

$(SM1, SM2, SM3) =  \int_{-\frac{h}{2} - z0}^{\frac{h}{2} - z0}(\sigma11,\sigma22,\sigma12)zdz$

\end{equation}

\end{document}

A: this is the kind of construction, where only one equation number is wanted for a
multi-line expression, that is best input using the equation environment with a
"subsidiary" environment nested inside of it.
i suggest this input code:
\begin{equation}\label{1}
\begin{aligned}
(SF1, SF2, SF3, SF4, SF5) & =  \int_{-\frac{h}{2} - z0}^{\frac{h}{2} - z0} (\sigma11,\sigma22,\sigma12,\sigma13,\sigma23)dz\\
(SM1, SM2, SM3) & =  \int_{-\frac{h}{2} - z0}^{\frac{h}{2} - z0}(\sigma11,\sigma22,\sigma12)zdz
\end{aligned}
\end{equation}

(i am not repeating the entire code, since this is essentially the same as what was
used in your earlier question. thank you,
though, for posing this as a new question.)
here is the output:

as you can see, the equation number is on the right-hand, not the left-hand side.
as various commenters have pointed out, you should not (not ever!) have blank lines
within the scope of the equation environment (or, indeed, within any math environment).
and once you are in math mode, don't use $ signs; they only confuse things.
you would get some benefit from reading the amsmath documentation -- texdoc amsmath.

A: After removing the syntax errors ($ inside displayed math, \par/empty lines inside environment equation) and some guesses (two equations, maybe aligned at the equals sign, subscripts, ...):
\documentclass[11pt,a4paper,twoside,openright]{report}
\usepackage{amsmath,amssymb}
\pagestyle{empty}

\newcommand*{\diff}{\mathop{}\!\mathrm{d}}

\begin{document}

\begin{align}\label{1}
(SF1, SF2, SF3, SF4, SF5) &=  \int_{-\frac{h}{2} - z_0}^{\frac{h}{2} - z_0}
(\sigma_{11},\sigma_{22},\sigma_{12},\sigma_{13},\sigma_{23})\diff z
\\
(SM1, SM2, SM3) &=  \int_{-\frac{h}{2} - z_0}^{\frac{h}{2} - z_0}
(\sigma_{11},\sigma_{22},\sigma_{12})z \diff z
\end{align}

\end{document}

I am not sure about the meaning of SF1 to SF5 and SM1 to SM3. Therefore I left them unchanged.
Maybe they are some program variables, then they could be set as:
\documentclass[11pt,a4paper,twoside,openright]{report}
\usepackage{amsmath,amssymb}
\pagestyle{empty}

\newcommand*{\diff}{\mathop{}\!\mathrm{d}}

\newcommand*{\var}[1]{\texttt{#1}}

\begin{document}

\begin{align}\label{1}
(\var{SF1}, \var{SF2}, \var{SF3}, \var{SF4}, \var{SF5}) &=  \int_{-\frac{h}{2} -
(\sigma_{11},\sigma_{22},\sigma_{12},\sigma_{13},\sigma_{23})\diff z
\\
(\var{SM1}, \var{SM2}, \var{SM3}) &=  \int_{-\frac{h}{2} - z_0}^{\frac{h}{2} - z_
(\sigma_{11},\sigma_{22},\sigma_{12})z \diff z
\end{align}

\end{document}


text:
Q: Negative Voltage creating Sinking Terminal For powering a RS485 circuit, I am requiring a Negative Power Source.
I was thinking to split a standard power source with 0V, +6V and +12V, using the +6V as ground with LM7805, and using some LM7805|LM7905 (or similar) devices for regulate into +5V|-5V.
In this case, the +6V could become a sinking terminal if the negative voltage circuit is unloaded, which I think should not be correct and could break the source(?).
The arbitrary change of GNDs confuse me, because the GND should always be a sinking terminal, not a sourcing.
So, how should I generate +5V -5V sources in a proper way?
Also, it is a choice to generate a low power -5V from a +5V source?

Edit.

*

*Agreed regarding RS485 not actually requiring -5V source. Please keep the example valid for other application.

*Consider 0V, +7.5V and +15V for the voltage dropout.

*Consider only resistive loads, DC output signals.

In the best case, I am afraid this question depends on the nature of the power source (?). For example,

*

*Case 1: if we have two sources, one from GND to +7.5V and other from GND to +15V, then loading only the 7805 will negatively polarize (charge) the 0 +7.5V source (?), hence this design is wrong in this case?

*Case 2: The proper design should have two sources from GND to +7.5V, and putting them in series (?).

A: First of all, RS-485 does not normally require a negative power supply. It uses a pair of balanced signals that individually swing between 0V and +5V. Only a +5V power supply is required.
But to answer your actual questions:

the GND should always be a sinking terminal, not a sourcing.

Not at all. "Ground" just implies a voltage reference point. It doesn't imply anything about the direction of current flow.
The negative terminal of a power supply "sinks current", but whether that's tied to ground is entirely up to you.
I'm not sure what the nature of the +6V source shown in your diagram is, but it's likely that it can't sink significant current.

So, how should I generate +5V -5V sources in a proper way?
Also, it is a choice to generate a low power -5V from a +5V source?

Sure. There are plenty of DC-DC converters out there that can do exactly that. Some of them use switched-capacitor techniques for very low power circuits; others use inductor or transformer based SMPS techniques.

A: This is a great question.  the LDO's have a 1.5 to 2V dropout so it won't work with 6Vin and 5V out.   But  you do not need V- for a differential RS 485, only bipolar RS232.
You only need 5V and 0V to create RS485 signals.
Other info for future RS232 considerations. we normally use a charge pump for +/-V.
——x-x-xxx— ———
When we have floating DC sources, we can call anything Gnd=0V but use it for two different nodes on a "non-isolated" LDO.

*

*so use a different Gnd symbol like Gnd A and Gnd B, keeping mind the DC difference could be anywhere from
5 to 7 V difference.p and not always 6V! why?

Furthermore, must be aware of the load currents with respect to 6V, 12V and 0V.  Op Amps have a constant current between Vcc and Vee or V+ /V- and only use then middle-level voltage and impedance of that voltage for things like input bias currents, which are small. However, the output load will have some  RLC values with respect to each rail so we can estimate these currents and their effect on each node voltage.
For background info, consider each LDO an Emitter Follower with internal feedback. This means the V+ out is NPN and V- regulator uses PNP outputs ( usually are Darlington's consequently the output can be driven above the regulator's |Vout| with very little current such as in a flyback Voltage).
So each regulator only pulls the load voltage towards the input. (+5 = delta V towards input +12V & -5 = delta V towards input 0V).
Now if your Load is connected to "common V" shared between both LDO's what is the actual source impedance of this node before a load is applied?   This depends on the LDO's internal bias currents as an R divider so if not equal then what? Each LDO will be fighting to get + or -  5V out and if there is any mismatch in current to each regulator they will be noisy one may possibly pull itself towards its input rail thus saturating then error amplifier inside and getting zero feedback gain in the process so then current drops and voltage swings back towards some equilibrium near the LDO input cut-off voltage.
So will it work if the load is connected to input 0V?
No, because as the background info I gave says,  the PNP emitter output becomes reverse biased in the LM 7906.
But putting the load like an Audio speaker Amp to mid-point Voltage could work but may have Noise if the other load currents are not balanced.
So how you fix this? Or does it need fixing? Well, that depends on your exact RLC load to each of 3 rails. this includes RS232 Cable, target SMPS leakage noise current, connections to Earth ground at both ends etc, etc.
Is floating actually infinite impedance. No it depends on the supply. 50,60 Hz transformers are different than 50kHz SMPS transformers and 1nF of leakage capacitance can cause issues.
Finally, if the input is 6V and output is 5V what is the regulator dropout Voltage at desired load current and how will 0V be connected to the target RS232 Earth gnd, assuming yours is isolated but with 1nF of leakage capacitance and Possible SMPS noise current coupling thru.
Summary of wrong assumptions

*

*you can specify different gnd symbols to mean different 0V relative potentials as this is not connected to earth gnd (yet)

*These BJT LDO's need 2V headroom, not 1V, while FET-based LDO's use low RdsOn to get <<1 V  yet not needed for 12 to 5V.

*you don't need V- for RS485 just 5V, 0V

*bipolar LDO's need a low impedance midpoint reference ( e.g. active V/2 driver) otherwise they do not balance well with unknown loads


text:
Q: Add Library JAR Files to EJB project I have created Maven project project using m2eclipe plugin for Eclipse. I have choose ejb-javaee6 archetype and added few dependencies to pom.xml, Eclipse resolved this dependencies fine.
When I try to deploy this project on Glassfish server using WTP plugin, I can see that my dependencies did not copy to ear archive.
There are few commons ways how to add library jar files to classpath of j2ee application. So I have to copy my dependencies in application server lib directory or copy it to top level of EAR file and provide manifest file of EJB module with classpath information.
What is the common way to achieve it ? I want eclipse/maven to automatically add jar files to classpath of EJB.

A: To get this to work properly you need to make sure to install m2eclipse-wtp integration plugin. It is not available as part of the default m2eclipse install. There may also be some flags you need to set in your pom.xml as the "jars that should be packaged with my app" is a subset of all jars on the application's classpath. Maven needs to know what to package, so that m2eclipse-wtp plugin can convey that information to Eclipse so that Eclipse functions like publish and export EAR work as expected.


text:
Q: Parentheses usage in T-SQL? I was experimenting with setting the value of a variable
declare @tablename nvarchar(1000);

set @tablename = SELECT TOP 1 NAME FROM SYS.TABLES ORDER BY NAME; //Error
set @tablename = (SELECT TOP 1 @tablename = NAME FROM SYS.TABLES ORDER BY NAME;) //Works fine

What magic parentheses did here?
I guess it has to do with evaluation. But why it didn't evaluate in the first statement then?

A: A subquery requires its own set of parentheses.  So the second has valid syntax because it is using them.
You may be confused with select versus set.  You can set a parameter using select and no parentheses are needed:
SELECT TOP 1 @tablename = NAME
FROM SYS.TABLES
ORDER BY NAME;


text:
Q: Correct method overloading approach Is overloaded methods returning different data-types good or bad?
I understand overloading can't be done on return types, what I meant is following
1) T Create(T)

2) List<T> Create(List<T>)

I think it would be counter-intuitive if an overloaded method returns different data-types, would like to have thoughts from others?
I do see such approach being following in .Net framework (Where extension method).
I understand this question might get closed as there wouldn't be any yes/no for this one but I would like to hear how people approach this?
Cheers,
Avinash

A: I would not advise that. Sure, you can do it, but you will never know what's going to be a returned value.
It's somewhat confusing when you see
var value = YourClass.Create(AnotherClass.GetResult());

sure, you could replace var with actual type you expect, or add <Type> after Create to indicate what overload would you like to use.
Personally, I would go for
T Create<T>(T values)
List<T> CreateMany<T>(List<T> values)

It is much clearer and when someone reads your code it is immediately obvious what are you trying to do.


text:
Q: "Share to facebook" button issue in displaying thumbnails I have added a "share to Facebook" button in all my website's articles.
Clicking this button would normally open a new window showing the Facebook post's preview: the post's title, the post's description, and the ability to select one of the page's images, as a thumbnail to my Facebook post.
Without no reason, the past few days, this functionality has problems. There are no thumbnails to select and eventually the post in Facebook looks like
"WEBSITE URL" [post title]
website url... [post description]
Can you please help me find what's the reason for this, because I couldn't manage to solve it myself.

A: I would suggest running your URL thru Facebook's linter tool https://developers.facebook.com/tools/explorer and fix any issues it has with your og: tag setup.  Once that is fixed, then you can troubleshoot why the plugin is not picking up the information correctly.


text:
Q: Spring Batch - Create Two Datasources and how to customized to use other properties I need quick guidance to create two relational datasources in Spring Boot Batch project. One is Oracle as a Source DB and Other is Postgres Target DB.
Spring Boot V2.2.5.RELEADE
Spring Boot Version 2.2.5.RELEASE
Here I want to customized both datasources to use all properties mentioned here (http://shekup.blogspot.com/2018/05/multiple-data-sources-in-spring-batch.html#:~:text=Multiple%20Data%20sources%20in%20Spring%20batch,such%20as%20ETL%20batch%20job.) for both datasources
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres?currentSchema=XXXX?useSSL=false
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=admin
spring.datasource.driver-class-name=org.postgresql.Driver

# max no. of connections in the pool
spring.datasource.hikari.maximum-pool-size=30
spring.datasource.hikari.minimum-idle=20
spring.datasource.hikari.connection-test-query=SELECT 1

spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.default_schema=YYYY

spring.batch.initialize-schema=always
spring.batch.table-prefix=YYYY.BATCH_

### Source oracle DS ###
oracle.datasource.url=jdbc:oracle:thin:@//XXXX:1527/XXX
oracle.datasource.username=XXX
oracle.datasource.password=XXX
oracle.datasource.driverClassName=oracle.jdbc.Oracloracleiver

# max no. of connections in the pool
oracle.spring.datasource.hikari.maximum-pool-size=30
oracle.spring.datasource.hikari.minimum-idle=20
oracle.spring.datasource.hikari.connection-test-query=SELECT 1

DBConfig
@Configuration
public class DataSourceConfig {
    @Autowired
    private Environment env;

    @Primary
    @Bean(name = "postgresDataSource")
    @ConfigurationProperties("spring.datasource")
    public DataSource batchDataSource() {
        return DataSourceBuilder.create().url(env.getProperty("spring.datasource.url"))
                .driverClassName(env.getProperty("spring.datasource.driver-class-name"))
                .username(env.getProperty("spring.datasource.username"))
                .password(env.getProperty("spring.datasource.password")).build();
    }

    @Bean(name = "oracleDataSource")
    @ConfigurationProperties("oracle.datasource")
    public DataSource mysqlBatchDataSource() {
        return DataSourceBuilder.create().url(env.getProperty("oracle.datasource.url"))
                .driverClassName(env.getProperty("oracle.datasource.driver-class-name"))
                .username(env.getProperty("oracle.datasource.username"))
                .password(env.getProperty("oracle.datasource.password")).build();
    }
}

A: You have to provide the additional information by your own code.
Do not use DataSourceBuilder.  Here is examples of Tomcat-Jdbc and Hikari
@Bean(name = "sourceBatchDataSource")
public DataSource sourceBatchDataSource() {
    HikariDataSource hikariDataSource = new HikariDataSource();
    hikariDataSource.setJdbcUrl(sourceDataSourceProperties.getUrl());
    hikariDataSource.setUsername(sourceDataSourceProperties.getUsername());
    hikariDataSource.setPassword(sourceDataSourceProperties.getPassword());
    hikariDataSource.setDriverClassName(sourceDataSourceProperties.getDriverClassName());
    hikariDataSource.setAutoCommit(from(environment.getProperty("spring.datasource.hikari.auto-commit")));
    hikariDataSource.setConnectionTimeout(environment.getProperty("spring.datasource.hikari.connection-timeout", Integer.class));
    hikariDataSource.setMaximumPoolSize(environment.getProperty("spring.datasource.hikari.maximum-pool-size", Integer.class));
    hikariDataSource.setMaxLifetime(environment.getProperty("spring.datasource.hikari.max-lifetime", Integer.class));
    hikariDataSource.setMinimumIdle(environment.getProperty("spring.datasource.hikari.minimum-idle", Integer.class));
    hikariDataSource.setPoolName("SourceBatchHikariCP");
    return hikariDataSource;
}

@Primary
@Bean(destroyMethod = "close", name = "sourceDataSource")
public DataSource sourceDataSource() {
    DataSourceProperties dataSourceProperties = dataSourceProperties();
    PoolProperties properties = new PoolProperties();
    properties.setUrl(dataSourceProperties.getUrl());
    properties.setDriverClassName(dataSourceProperties.getDriverClassName());
    properties.setUsername(dataSourceProperties.getUsername());
    properties.setPassword(dataSourceProperties.getPassword());
    properties.setInitialSize(environment.getProperty("spring.datasource.tomcat.initial-size", Integer.class));
    properties.setMaxWait(environment.getProperty("spring.datasource.tomcat.max-wait", Integer.class));
    properties.setMaxActive(environment.getProperty("spring.datasource.tomcat.max-active", Integer.class));
    properties.setMaxIdle(environment.getProperty("spring.datasource.tomcat.max-idle", Integer.class));
    properties.setMinIdle(environment.getProperty("spring.datasource.tomcat.min-idle", Integer.class));
    properties.setDefaultAutoCommit(from(environment.getProperty("spring.datasource.tomcat.default-auto-commit")));
    properties.setValidationQuery(environment.getProperty("spring.datasource.tomcat.validation-query"));
    properties.setTestOnBorrow(from(environment.getProperty("spring.datasource.tomcat.test-on-borrow")));
    properties.setTestWhileIdle(from(environment.getProperty("spring.datasource.tomcat.test-while-idle")));
    properties.setTestOnReturn(from(environment.getProperty("spring.datasource.tomcat.test-on-return")));
    properties.setTimeBetweenEvictionRunsMillis(environment.getProperty("spring.datasource.tomcat.time-between-eviction-runs-millis", Integer.class));
    properties.setMinEvictableIdleTimeMillis(environment.getProperty("spring.datasource.tomcat.min-evictable-idle-time-millis", Integer.class));
    properties.setRemoveAbandoned(from(environment.getProperty("spring.datasource.tomcat.remove-abandoned")));
    properties.setRemoveAbandonedTimeout(environment.getProperty("spring.datasource.tomcat.remove-abandoned-timeout", Integer.class));
    properties.setLogAbandoned(from(environment.getProperty("spring.datasource.tomcat.log-abandoned")));
    properties.setLogValidationErrors(from(environment.getProperty("spring.datasource.tomcat.log-validation-errors")));
    properties.setJdbcInterceptors(environment.getProperty("spring.datasource.tomcat.jdbc-interceptors"));
    return new org.apache.tomcat.jdbc.pool.DataSource(properties);
}


text:
Q: Why does the multiplication of a matrix to a set of linearly independent vectors still produces a set of linearly independent vectors? More specifically, the question states that the intersection of the null space of a matrix and the set of linearly independent vectors is the zero vector.
How do I use this information to prove the question?
If the intersection of the null space of the matrix and the set of linearly independent vectors is not only the zero vector, is it fair to say that the multiplication of the matrix to the vectors will produce a set of linearly dependent vectors?
Can't make sense of where to start. :/


text:
Q: Create cube calculation in SSAS using MDX statement to allocate monthly target to daily level I have a cube fact table for targets, the targets are at the monthly level (Jan = 300, Feb = 450, Mar = 350 etc.)
This is joined to the date dimension in my cube at using month as the join, however the dimensions grain is at the day level.
What I want to do is create a calculation so that the monthly target is allocated evenly to the days in the month so each day in Jan has a target of 300/31 Feb 450/28 etc.
I then want to be able to use this calculated measure as my target and have it available as the daily/monthly/quarterly/Annual Target.
I think this should be possible with an MDX statement (or perhaps a few using a few calculated measures) but I'm not that familiar with it.
So would this approach work and what would the mdx look like?
Thanks

A: If you have the ability to make changes to your source OLTP/staging database, then it would be best to change the grain of your Targets fact table to daily if you need to report at that level. You could do this with a view if you have a date dimension table in your OLTP database by joining your monthly fact table to your date dimension on the month attribute, and then evenly distributing the target value over the days of the month.
If you are using SQL Server and your OLTP schema looks like the following:
CREATE TABLE dimDate (
    Date Date,
    YearMonth Integer,
    ...
)

CREATE TABLE factMonthlyTarget (
   YearMonth Integer,
   Value Integer,
   ...
)

Your new fact view would be something like the following:
CREATE VIEW factDailyTarget AS
   SELECT
      dimDate.Date,
      factMonthlyTarget.Value / Months.DaysPerMonth AS Value
   FROM
      factMonthlyTarget,
      dimDate,
      (
         SELECT YearMonth, COUNT(*) AS DaysPerMonth
         FROM dimDate
         GROUP BY YearMonth
      ) Months
   WHERE factMonthlyTarget.YearMonth = Months.YearMonth
         AND Months.YearMonth = dimDate.YearMonth


text:
Q: check if user uploaded a file in PHP I am try to check whether user choose uploaded file or not
html
<input  type=\"file\" name=\"upload1[]\" multiple />

php
if(is_uploaded_file($_FILES['upload1']['tmp_name'])){
    echo 'ok';
}

I am testing using it doesn't work. is there any other way

A: I would look at this location for further information on how to properly handle this case:
http://www.php.net/manual/en/features.file-upload.multiple.php

A: Check this
            <form enctype="multipart/form-data" method="POST">
                Choose a file to upload:
                <input type="file" name="upload1[]" multiple />

                <input type="submit" value="Upload File" name="submit" />
            </form>
            <?php

                if (isset($_POST['submit'])) {

                    if (isset($_FILES['upload1'])) {

                        $counter = count($_FILES['upload1']['name']);
                        for ($i = 0; $i < $counter; $i++) {

                            if (is_uploaded_file($_FILES['upload1']['tmp_name'][$i])) {
                                echo $_FILES['upload1']['tmp_name'][$i] . ' - ok
';
                            }

                        }

                    }
                }

            ?>


text:
Q: interprate the error in decompiled source I found some helpful code online where only the library file was provided and I recreated the source code but found a couple errors I am not sure of.
<StandardModule()> _
Friend NotInheritable Class CreateFiles
' Methods

' Fields
Private Shared Configuration As Configuration = New Configuration

' Nested Types
Private Delegate Sub showITDelegate(ByVal message As String)

<STAThread()> _
Public Shared Sub Main()
    CreateFiles.Configuration.ReadConfig()
    CreateFiles.DisplayConfig(CreateFiles.Configuration)
    CreateFiles.CreateFiles()
End Sub

Public Shared Sub CreateFiles()

I am trying to understand if there is another class missing because there are errors on the CreateFiles.* lines in the main and these reference subs within this very class:
CreateFiles has 'expression does not produce a value' under it.
Why would it reference itself and the methods and subs within the same class.

A: Seems like it looks at the Sub CreateFiles() rather than the class. And a sub (routine) doesn't return any value. You could remove the (first) CreateFiles in the Main subroutine.
This should work:
<StandardModule()> _
Friend NotInheritable Class CreateFiles
' Methods

' Fields
Private Shared Configuration As Configuration = New Configuration

' Nested Types
Private Delegate Sub showITDelegate(ByVal message As String)

<STAThread()> _
Public Shared Sub Main()
    Configuration.ReadConfig()
    DisplayConfig(Configuration)
    CreateFiles()
End Sub

Public Shared Sub CreateFiles()

Given that you don't have a problem anywhere else.


text:
Q: How to add smart tags to my .NET component? Look at the following picture, which is showing a smart tag for DataGridView.
DataGridView Smart Tags http://img199.imageshack.us/img199/5871/post517531249536112.jpg
Now I'm creating a new component, and I want it to support showing some properties in smart tags. How do I add the properties to the smart tag?

A: I used http://msdn.microsoft.com/en-us/library/default.aspx?q=smart+tag+windows+forms+designer.
As a result, I found Walkthrough: Adding Smart Tags to a Windows Forms Component.
Anyone who does the same search will find the same article.

Update: That link no longer works. I just tried a search for "smart tag windows forms designer", and found "Walkthrough: Adding Smart Tags to a Windows Forms Component" as the first search hit. The same search in Google shows "How to: Attach Smart Tags to a Windows Forms Component" as the first hit, but shows the same Walkthrough as the second hit.

A: You can use the following code to view a sample tag in a custom control.
And you can get a video about that from www.windowsclient.com.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel.Design;
namespace MakeSmartTag
{
    public enum Languages
    {
        English,
        Arabic,
        Japanese
    }

    [Designer(typeof(UserControlDesigner))]
    public partial class UserControl2 : UserControl
    {
        public UserControl2()
        {
            InitializeComponent();
        }

        private Languages _language;

        public Languages Language
        {
            get { return _language; }
            set
            {
                switch (value)
                {
                    case Languages.Arabic:
                        {
                            label1.Text = "مرحباً";
                            _language = value;
                        }
                        break;
                    case Languages.English:
                        {
                            label1.Text = "Hello";
                            _language = value;
                        }
                        break;
                    case Languages.Japanese:
                        {
                            label1.Text = "Conechoa";
                            _language = value;
                        }
                        break;
                }
            }
        }
    }

    public class UserControlDesigner : System.Windows.Forms.Design.ControlDesigner
    {
        private DesignerActionListCollection lists;
        public override DesignerActionListCollection ActionLists
        {
            get
            {
                if (lists == null)
                {

                    lists = new DesignerActionListCollection();
                    lists.Add(new UserControlActioonList(this.Component));
                }
                return lists;
            }
        }
    }

    public class UserControlActioonList : DesignerActionList
    {
        private UserControl2 myUserControl;
        private DesignerActionUIService designerActionSvc = null;

        public UserControlActioonList(IComponent component)
            : base(component)
        {
            this.myUserControl = (UserControl2)component;

            this.designerActionSvc =
              (DesignerActionUIService)GetService(typeof(DesignerActionUIService));
        }

        private PropertyDescriptor GetPropertyByName(string propName)
        {
            PropertyDescriptor prop = default(PropertyDescriptor);
            prop = TypeDescriptor.GetProperties(myUserControl)[propName];
            if (prop == null)
            {
                throw new ArgumentException("Invalid Property", propName);
            }
            else
            {
                return prop;
            }
        }

        public override System.ComponentModel.Design.DesignerActionItemCollection GetSortedActionItems()
        {
            DesignerActionItemCollection item = new DesignerActionItemCollection();
            item.Add(new DesignerActionHeaderItem(
                       "المظهر"));
            item.Add(new DesignerActionPropertyItem(
                       "BackColor", "لون الخلفية", "Appearance", "Set background Color of the control"));
            item.Add(new DesignerActionHeaderItem("تحديد اللغة"));
            item.Add(new DesignerActionPropertyItem(
                       "Language", "اللغة", "Functions", "Set the language of the control"));
            return item;
        }

        public Color BackColor
        {
            get { return this.myUserControl.BackColor; }
            set { GetPropertyByName("BackColor").SetValue(myUserControl, value); }
        }

        public Languages Language
        {
            get { return this.myUserControl.Language; }
            set { GetPropertyByName("Language").SetValue(myUserControl, value); }
        }
    }
}


text:
Q: How can set in session a user authenticated under a external API using AdonisJs? I have a AdonisJS view module that use an external API to authenticate. But Don't know how can set this user in my auth object.
    async login({ request, response, session, auth }){
        const {email, password} = request.only(['email', 'password'])

        try{
           //resp contains user data retrieved
            const resp = await axios.post('myHost/login', {
                "email": email,
                "password": password
            });

            return response.redirect(request.header('origin'))
        }catch(error) {
            session.flash({ 'error': 'Test error' })
        };
    }

I tried set this object in response header, but, isn't correct.


text:
Q: Voltage in a simple LED parallel circuit I tested two parallel LED circuits. In the first circuit, only the red LED glows.  In the second circuit, both of the blue LEDs glow.
I know the forward voltage rose in the second circuit, but why did this happen?
Why does the forward voltage just fit the red LED (low voltage) not the blue one (higher voltage) in the first circuit?

A: The loads are are in parallel so there will be same voltage over both LEDs.
The red LED will turn on at much less than 2V or so and it starts to conduct current and there will be much less than 2V over both LEDs.
The blue LED requires much more than 2V to start conducting current so it will not light up as it only has much less than 2V.

A: The red led acts as a shunt regulator. By putting various voltage shunts in parallel, the one with the lowest voltage "wins" and doesn't allow the voltage to increase. That's what a shunt regulator is, by definition: it limits the voltage by drawing current as the voltage goes up too high.
If you want to learn more about this concept, search using the term shunt regulator.
Now, LEDs may be crude shunt regulators, but consider that the circuit you've shown allows to use a SPST pushbutton as if it was an SPDT button. Shown below, when the button is depressed, the blue led turns off, and the red led turns on. The leds alternate, even though just a simple button is used.

simulate this circuit – Schematic created using CircuitLab
After opening the schematic in CircuitLab, click on SW1 to select it, and use Space to toggle the switch.


text:
Q: Macro Excel: To insert a circle into specific range in cell I have a circle that has a fixed diameter and center. What I need to do now is to insert the circle into the given range. Eg, given 11 boxes of column and 10 boxes of rows to be inserted in excel cell. After entering the given range, the circle will be within the selected range with its fixed center but the boxes would have different measurement for its height and width. My question is how do I insert the circle into any given range (as in 11 x 10 or 9 x 12) with different height and width of the cells?
My code:
Sub DrawCircleWithCenter()
Dim cellwidth As Single
Dim cellheight As Single
Dim ws As Worksheet
Dim rng As Range
Dim Shp2 As Shape

CellLeft = Selection.Left
CellTop = Selection.Top

ActiveSheet.Shapes.AddShape(msoShapeOval, CellLeft, CellTop, 565 / 2, 565 / 2).Select
Selection.ShapeRange.Fill.Visible = msoFalse
With Selection.ShapeRange.Line
    .Visible = msoTrue
    .ForeColor.RGB = RGB(0, 0, 0)
    .Transparency = 0
End With

i = 182
Set Shp2 = ActiveSheet.Shapes.AddShape(i, CellLeft, CellTop, 20, 20)
Shp2.ShapeStyle = msoShapeStylePreset1
Set rng = ActiveWindow.VisibleRange

Selection.Left = rng.Width / 2 - Selection.Width / 2
Selection.Top = rng.Height / 2 - Selection.Height / 2
Shp2.Left = rng.Width / 2 - Shp2.Width / 2
Shp2.Top = rng.Height / 2 - Shp2.Height / 2

End Sub

A: If I'm understanding you correctly this could be what you're after:
Sub DrawCircleWithCenter(rng As Range)
  Dim Shp1 As Shape, Shp2 As Shape

  Set Shp1 = ActiveSheet.Shapes.AddShape(msoShapeOval, rng.Left, rng.Top, rng.Width, rng.Height)
  Shp1.Fill.Visible = msoFalse
  With Shp1.Line
    .Visible = msoTrue
    .ForeColor.RGB = RGB(0, 0, 0)
    .Transparency = 0
  End With

  Set Shp2 = ActiveSheet.Shapes.AddShape(182, rng.Left, rng.Top, 20, 20)
  Shp2.ShapeStyle = msoShapeStylePreset1

  Shp1.Left = rng.Left
  Shp1.Top = rng.Top
  Shp2.Left = rng.Left + rng.Width / 2 - Shp2.Width / 2
  Shp2.Top = rng.Top + rng.Height / 2 - Shp2.Height / 2
End Sub

Sub Test()
  Dim rng As Range
  Set rng = Selection
  DrawCircleWithCenter rng
End Sub

You can modify the Test subroutine to supply the range you're after.  In the above case I use the selection that the user has highlighted in the present worksheet to draw the cross and oval centered inside it.  If you choose a square area the oval becomes a circle, with a rectangular area it'll be squashed into an ellipse.  It'll also work if you have varying cell widths and heights in the range you select.


text:
Q: Backbone model parse method (collection / server) Please, help me :)
I have the backbone model:
var people = Backbone.Model.extend({
...
parse : function() {

  return response
}
})

And have the collection:
var group = Backbone.Collection.extend({
model: people
...
})

Usually i get data by call collection sync method, but sometimes, i call model fetch method.
My backend return answer in format:
{code: 0, data: {'1': {name: 'alex'}, '2': {name: 'max'}}}

Problem:
If i write model parse method for processing my backend answer - collection sync don't work (because server answer have another format), if i write parse method for collection - don't work backend processing.
How i can create universal processing?
I found way, see options in parse method and use else/if but i don't like it.

A: Option-1:
Will using an additional _PeopleBase class help?
var _PeopleBase = Backbone.Model.extend({
    ...
})
var people = _PeopleBase.extend({
...
parse : function() {

  return response
}
})

The collection:
var group = Backbone.Collection.extend({
model: _PeopleBase
...
parse : function() { //Collection parser

  return response
}

})

Option-2:
You can rely on the data returned to decide how to parse it if that is possible
parse : function(response, options) {
  //Test the response with whichever way you can definitely differentiate them

  return response
}

Option-3:
Depending on who is the caller of the parse function:
parse : function(response, options) {
    if (this instanceof People) {

    } else {

    }

  return response
}

Hope this help!

A: Here's how I do it in mine (I have a lot of nested data and have to map existing objects to my views to ensure my view is updated without complete refresh):
//pass {parse: true} if Person has nested data that needs parsing as well
parse: function(response, xhr) {
                for(var key in this) {
                    if (key === 'person') {
                        var embeddedClass,
                            embeddedData = response[key],
                            exsiting = this.get(key);

                       if (existing == null) {

                            embeddedClass = new Person(embeddedData, {parse: true});
                       } else {
                            existing.set(key, existing.parse(embeddedData));
                            embeddedClass = existing
                       }
                       response[key] = embeddedClass;
                    }
                }
                return response;
            }

then when the new data comes and I need to parse it again manually, I call
this.set(this.parse(response));


text:
Q: Cast a variable of filtering_istream type to ifstream type? I am using the filetering_istream type to save the information in a decompressed file while using 'boost/iostreams/filtering_stream.hpp'. But I want to cast it into the ifstream type. It there any way to do it? Great thanks!
The code is as follows:
#include <istream>
#include <fstream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>

int main(){
    std::ifstream file("test_data.dat.gz");

    boost::iostreams::filtering_istream in;

    in.push(boost::iostreams::gzip_decompressor());

    in.push(file);

    /* add code to convert filtering_istream 'in' into ifstream 'pfile' */

    /* It seems that the following code returns a pointer NULL */

    // std::ifstream* pfile = in.component<std::ifstream>(1);

    return 0;

}

After trying boost::ref and boost::wrapper proposed by zett42, the ifstream really works. The only problem is that it doesn't give the phrases wanted.
In my text of .gz file, I wrote:
THIS IS A DATA FILE!
8 plus 8 is 16

But using the ifstream, I got:
is_open: 1

\213<\373Xtest_data.dat\361\360V"G\307G7OWE.\205\202\234\322b\205\314bC3.\327+>\314$
I am not sure what happened here, and can I do something to recover it?

A: From the reference of filtering_stream:

filtering_stream derives from std::basic_istream, std::basic_ostream
  or std::basic_iostream, depending on its Mode parameter.

So no, you can't cast a filtering_stream directly to an ifstream because there is no inheritance relationship between the two.
What you can do instead, if your filter chain ends with a device that is an ifstream, you can grap that device by calling filtering_stream::component(). For streams this function returns a boost::iostreams::detail::mode_adapter (you can see the type by calling in.component_type(1)).
It's propably not a good idea to depend on an internal boost type (indicated by namespace "detail") which could change with next boost version, so one workaround is to use boost::reference_wrapper instead.
#include <iostream>
#include <istream>
#include <fstream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/core/ref.hpp>

int main(){
    std::ifstream file("test_data.dat.gz");

    boost::iostreams::filtering_istream in;

    in.push(boost::iostreams::gzip_decompressor());

    in.push(boost::ref(file));

    if( auto pfile = in.component<boost::reference_wrapper<std::ifstream>>( 1 ) )
    {
        std::ifstream& rfile = *pfile;
        std::cout << "is_open: " << rfile.is_open() << "\n";
    }
}


text:
Q: PHP Redirect for 5 seconds, then return back to originating page I am new to PHP and have been attempting to write a simple PHP script that will is activated from a "submit" button.

*

*Show a "Welcome message"

*Redirect to a an external page for 5 seconds, then return to the script.

*Show a "Thank you"

So far I've tried:
<?php
echo 'Welcome to ......';
header( "refresh:5;url=what.html" );
?>

Any suggestions? At the moment it justs redirects after 5 seconds, and I need to return back to a "Thank you prompt"

A: You can't code on same page 'source.html' to redirect on 'destination.html' for 5 minutes only.
For that you have to first redirect to 'destination.html' and there you have to add code to return back to 'source.html' page after 5 seconds.

A: First of all you need to send the headers before doing any output! You also may use HTML Tags to do the redirection.

        <title>Title</title>
        <meta http-equiv="refresh" content="5; URL=/what.html">

Welcome to ......


text:
Q: Native query instead of createQueryBuilder in entity field type Symfony Maybe someone faced such a problem then please help. I want to add a dropdown field in formbuilder that would feed from native sql query. I made this in my form:
->add('extensionId', 'entity', [
            'required' => false,
            'label' => 'Insurance Company',
            'class' => 'Bundle:Product',
            'query_builder' => function (ProductRepository $repo) {
                return $repo->getPGOperPG();
            }
        ])

It works fine if i use createQueryBuilder, like this:
public function getPGOperPG()
{
    return $this->createQueryBuilder('pgo')
        ->select('pgo')
        ->join('pgo.productGroups', 'pg')
        ->where('pg.id IN (677, 655, 625) AND pgo.isActive = true');
}

But i get error if use this:
public function getPGOperPG()
{
    $sql = <<<SQL
    SELECT product_group_option_id
    FROM product_groups_product_group_options
    WHERE product_group_id in (677, 655, 625)
    SQL;

    $rsm = new ResultSetMappingBuilder($this->getEntityManager());
    $rsm->addRootEntityFromClassMetadata('Bundle\Entity\Product', 'pgo');

    return $this->_em->createNativeQuery($sql, $rsm)
        ;
}

This is the error:
enter image description here.
I understand that only CreateQueryBuilder object is expected.
Question: is there a way how i could pass native query to a dropdown field? maybe some other form type or smth?
Thank you in advance!!!


text:
Q: Where do i start in making an android app? So I'm new to programming and I really want to get into the deep stuffs. So firstly I'm looking to make an android app but I really don't know where to even begin. Which framework do i use? What programming language should I master. I just need a little light to be shed here.

A: For Programming Language, you can learn Java or Kotlin .. Etc
For Java, use NetBeans to train and improve, I really recommend it for beginners.
https://netbeans.org
After you learn programming language, start learning Android development.
You will need Android studio
https://developer.android.com/studio
You also need to learn SQLite for databases.
Wish this helps.


text:
Q: Пузырьковая сортировка по книге Р. Лафоре Есть реализация пузырьковой сортировки по книге Лафоре "Структуры данных и алгоритмы JAVA":
class ArrayBub {
private long[] a;
private int nElems;
public ArrayBub(int max) {
    a = new long[max];
    nElems = 0;
}
public void insert(long value) {
    a[nElems] = value;
    nElems++;
}
public void display() {
    for(int j=0; j<nElems; j++)
        System.out.print(a[j] + " ");
    System.out.println("");
}
public void bubbleSort() {
    int out, in;

    for(out=nElems-1; out>1; out--)
        for(in=0; in<out; in++)
            if( a[in] > a[in+1] )
                swap(in, in+1);
}
private void swap(int one, int two) {
    long temp = a[one];
    a[one] = a[two];
    a[two] = temp;
}}

class BubbleSortApp {
public static void main(String[] args) {
    int maxSize = 100;
    ArrayBub arr;
    arr = new ArrayBub(maxSize);

    arr.insert(77);
    arr.insert(99);
    arr.insert(44);
    arr.insert(55);
    arr.insert(22);
    arr.insert(88);
    arr.insert(11);
    arr.insert(00);
    arr.insert(66);
    arr.insert(33);

    arr.display();
    arr.bubbleSort();
    arr.display();
}}

но она не сортирует массив со значениями - [3, 2, 1] - ответ:  [2, 3, 1].
Помогите пожалуйста разобраться в чем подвох?

A: Для понимания алгоритма можно почитать, что такое Пузырьковая сортировка. Правда там обход массива производится в прямом порядке для каждого элемента, но это не столь важно.
При работе с массивами надо смотреть на значения переменной индекса, правильность границ, инвариантов функции (assert), и т.д., потому что при неверных значениях переменных возникает неверное вычисление.
Как у вас, например сортируется часть массива, а оставшаяся часть не сортируется, т.е. массив остаётся неотсортированным, потому что он отсортирован не полностью.


text:
Q: Data drop duplicates data complex import pandas as pd

search = pd.DataFrame({
  "Code": ["BB", "BB", "CC", "CC", "CC", "DD", "DD"],
  "N1": [22, 20, 33, 30, 31, 44, 40]
})

confirmed = pd.DataFrame({'N2': [30, 40, 50]})

Hi dear, I have a question while learning Python/pandas for data analysis. I have two dataframes above, I wish to search the data value in the comfirmed df, and if the value matches/appears in the first df (search), then we keep that value and its corresponding "Code" and delete the other same Code value. For example, 30 in the "confirmed" df, and it also appears in the "search" dataframe, so we keep value 30 and its code "CC", meanwhile we delete the other "CC"s and values (33, 31). Same for the others.
In the end, the "search" dataframe should look like this:
  Code  N1
0   BB  22
1   BB  20
2   CC  30
3   DD  40

It is quite complex question for me as a Python data rookie, so if anyone has any ideas, please help. Great thanks.

A: Do with transform after isin check
s=search.N1.isin(confirmed.N2)
m=(~s).groupby(search['Code']).transform('all') | s
out=search[m]
out
  Code  N1
0   BB  22
1   BB  20
3   CC  30
6   DD  40

A: Similar to Yorben_s' answer, but with np.where as well:
df = search.copy()
df['flag'] = np.where((df['N1'].isin(comfirmed['N2'])), 1, 0)
df['flag'] = np.where((df.groupby('Code')['flag'].transform(sum) == 0), 1, df['flag'])
df = df.loc[df['flag'] == 1].drop('flag', axis=1)
df


text:
Q: STD c++ set using find function Let's say I want to find the pointer to the element X in my set.I'll do:
set<int>S;
int x;
cin>>x;
//insert elements
set<int>iterator :: it = S.find(x);

How do i find element right after x in my set now?For example , if my set is :1 , 2 , 3 and x is 2 , I want to print 3.This doesn't seem to work:
cout<<*(it+1);

It says no match for operator '+'.Thanks!

A: instead of this:
cout<<*(it+1);

This:
if (it != S.end()) {
    it++;
    if (it != S.end()) {
        cout << *it;
    }
}


text:
Q: Getting floating point exception: 8 I have this line in my code (ll is long long int):
ll d = (x / ( (y / 1000000) - 1) );

which seems to be causing this floating point exception error.
However when I change it to:
ll d = (1000000*x)/(y-1000000);

the error disappears. Simple algebra will lead you to believe that they both are one and the same thing.
Here is the full code, which is for UVa problem 10660, Grocery Store. https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=643&page=show_problem&problem=2177
//Problem Link: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=643&page=show_problem&problem=2177
//Problem type: Complete Search

#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <stdio.h>
#include <queue>
#include <set>
#include <cmath>
#include <assert.h>
#include <bitset>
#include <map>
#include <unordered_map>
#include <iomanip> //cout << setprecision(n) << fixed << num

typedef long long int ll;
using namespace std;

int main() {
    //freopen("output.out", "w", stdout);
    int cnt = 0;
    for (int a = 1; a*4 <= 2000; a++) {
        for (int b = a; a+3*b <= 2000; b++) {
            for (int c = b; a+b+2*c <= 2000; c++) {
                ll x = a+b+c;
                ll y = a*b*c;
                if (y <= 1000000) continue;
                //ll d = (x / ( (y / 1000000) - 1) );
                ll d = (1000000*x)/(y-1000000);
                if (d < c || x + d > 2000) continue;
                if ( abs( (x + d) / 100.0 - ( y * d) / 100000000.0) < 1e-8 ) {
                    cout << setprecision(2) << fixed << a/100.0 <<  " " << b/100.0 << " " << c/100.0 << " " << d/100.0 << endl;
                    cnt++;
                }
            }
        }
    }
    cout << cnt << endl;
    return 0;
}

If I change it to ll d = (x / ( (y / 1000000.0f) - 1) ) however, then the error disappears, but I get a Wrong Answer, and the number of lines in the output is only 717, whereas it should be 949 (I had to google the answer to figure out this weird issue :/)

A: First, there is no floating-point arithmetic going on here: everything is done in integers (specifically, long long ints).
This means that when y is between 1000000 and 1999999, inclusive, the result of the division y / 1000000 is going to be 1. Hence, subtracting 1 from it would lead to zero denominator, and a division by zero exception.
Your second expression will produce the same result only when y is equal to 1000000, but the program is going to crash with the same exception.
The trick to solving problems of this kind is keeping numerator and denominator separate, and performing your math entirely in integers, i.e. without floating point numbers. Constructing a simple class for representing rational numbers should help simplifying your code.

A: The numeric code is a bit flag of exactly what error you hit (8 means division by zero).
These are the other bits:
enum {
    XCP_INVALID=0,
    XCP_OVERFLOW,
    XCP_UNDERFLOW,
    XCP_DIV_BY_ZERO,
    XCP_INEXACT,
    XCP_NXCP
    };


text:
Q: Background video play on hover I am wondering if anyone has suggestions on how to achieve a similar effect like they have on this website http://www.lahautesociete.com/
In particular, how the two different background videos begin playing when you hover over the two buttons.
Thank you!


text:
Q: How to access Dataset from.cs to .aspx using eval() I am coding Gridview programmatically.
I have dataset in code behind part(.cs),when i am trying to access the dataset in .aspx page using Eval() "Error Creating Control" error is coming.
Is it the Right way using Eval()?
<asp:TemplateField>
    <ItemTemplate>
        <asp:Label ID="lblGridTier" runat="server" Text='<%#Eval(dt.Tables[0].Columns["Tier"])%>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>

A: If you are doing something like this in the code behind to bind the GridView (and you actually should do something like this):
DateSet ds = ...
GridView1.DataSource = ds;
GridView1.DataBind();

then the correct way to use eval is to give it just the name of the column you want to show.
Text='<%#Eval("Tier")%>'

A: ok please note html is rendered first then your code behind file is called. Now here dataset is null (not yet created) when HTML is being rendered dataset is null so control will not be created and an exception will be thrown. You can use this work around on Page_Load you can set text property of label or check here if dataset is null then don't assign value using Eval. Hope it will help.

A: Eval function evaluates fields directly from the selected table of datasource which your grid is bound with. A couple of examples as follows:
<asp:TemplateField>
    <ItemTemplate>
        <asp:Label ID="lblSomeField" runat="server" Text='<%# Eval("field1")%>'></asp:Label>
        <asp:Image ID="lblImageLink" runat="server" ImageUrl='<%# Eval("imagefield", "http://somelink.com/images/{0}")%>' />
        <asp:HyperLink ID="lblMember" runat="server" NavigateUrl='<%# "/member.aspx?id=" + Eval("id") %>' Text='<%# Eval("membername") %>'></asp:HyperLink>
    </ItemTemplate>
</asp:TemplateField>


text:
Q: Question Regarding a form that is closed but not exact, and smooth angle function on the punctured plane In Jack Lee's introduction to smooth manifold. Example 11.48 in Chapter 11.
It discusses that the 1 form $\omega = \frac{x dy - y dx}{x^2+y^2}$ is a closed 1 form but not exact (because it is not conservative).
Then Jack goes on to discuss why this form cannot be exact intuitively, here's what he says
"On the other hand, if we restrict the domain to the right
half-plane U = {(x,y) | x>0}, a computation shows that $\omega = d (\tan^{-1}\frac{y}{x})$
.
This can be seen more clearly in polar coordinates, where $\omega = d(\theta)$. The problem,
of course, is that there is no smooth (or even continuous) angle function on all of $\mathbb{R}^2 \backslash  (0,0)$, which is a consequence of the "hole" in the center."
What is a smooth angle function defined on a smooth manifold, and why is the hole in the center a problem, shouldn't the removal of the origin actually takes care of the problem of not having an angle defined at $(0,0)$?
I am at the beginning of the De Rham Cohomology Chapter, and I am trying to understand the relationship between the shape of a smooth manifold and what it has to do with differential forms not being exact, and this first example rather baffles me.
Thank you for your help.

A: Identify $\mathbb R^2$ with $\mathbb C$.  The trick is to define the angle function implicitly: an angle function on a subset $U \subset S^1$ is a continuous function $\theta : U \to \mathbb R$ such that $e^{iθ(p)} = p,$ for all $p \in U.$ This definition makes sense intutively because if $e^{iθ(p)}=\cos \theta(p)+i\sin \theta (p)=p$, then $\theta$ must map $p$ to the angle that the line segment from the origin to $p$ makes with the positive $x$ axis. Of course, there is the question of well-definedness and continuity of $\theta$, which is addressed by the following standard result:
There exists an angle function on an open subset $U\subset  S^1$ if and only if $U\neq S^1$.
Suppose $\theta :U\to \mathbb R$ is an angle function and $U = S^1
\theta$ is continuous and $S^1$ is compact and connected, so $\theta(S^1)$ is an interval closed interval. And since $\theta$ is injective (why?), it is in fact, a homeomorphism from $S^1$ onto its $\theta (S^1)$. But, removing one point from $\theta (S^1)$ disconnects it, whereas removing one point from $S^1$ does not. Contradiction.
On the other hand,  Suppose $U \nsubseteq S^1$ is open in $S^1$. Define $\varphi : [0, 2\pi]\to S^1$ by $\varphi(t) = e^{it}$
.
Continuity of $\varphi$ implies that $V =\varphi^{-1}(U)$ is open in $[0, 2\pi].$ It follows that $\varphi$ is injective on $V$ (why?). So the restriction of $\varphi$ to $V$ is a continuous bijection  $:V\to U$. Now. define $\theta = (\varphi|_V )^{-1}$. Then $e^{iθ(p)} = p$, for all $p \in U$ and if $I\subset V$ is an open interval then $\theta^{-1}(I)=\varphi (I)$ so $\theta$ is continuous.
Now that we have an angle function, we can relate it to the $1$-form $\omega = \frac{x dy - y dx}{x^2+y^2}$:
Without loss of generality, $(0,1)\notin U$. Then, if $p=(x,y)\in S^1$, we may take $\theta(x,y)=\tan^{-1}(y/x)$
and then because
$d\theta \left (\frac{\partial}{\partial x}\right)=\frac{\partial \theta}{\partial x}=\frac{-y}{y^2+x^2}=\omega\left (\frac{\partial}{\partial x}\right)$
and
$d\theta \left (\frac{\partial}{\partial y}\right)=\frac{\partial \theta}{\partial y}=\frac{x}{y^2+x^2}=\omega\left (\frac{\partial}{\partial y}\right)$
it follows that  $\omega=d\theta.$


text:
Q: How to Convert PHP Associative array to json Array I want to convert an associative array in PHP into a a json array but the result is quite different from what i want
PHP Code
$output = array(
            "code": "UEX200",
            'email' => "username@gmail.com",
            'username' => "username,
            'type'         => "user",
            'account_manager' => "manager",
             status'       => "active
        );

i want it to be in this format
{
    "code": "UEX200",
    "details": [{
        "email": "username@gmail.com",
        "username": "username",
        "type": "user",
        "account_manager": "manager",
        "status": "active"
    }]
}

But it outputs in this format
{
    "code": "UEX200",
    "details": {
        "email": "username@gmail.com",
        "username": "username",
        "type": "user",
        "account_manager": "manager",
        "status": "active"
    }
}

A: Your array is not correct for the result you want change your array like mention below.

$output = array(
        "code"=> "UEX200",
        "details"=>array(
        array('email' => "username@gmail.com",
        'username' => "username",
        'type'         => "user",
        'account_manager' => "manager",
         'status'       => "active")
    )
    );

print_r(json_encode($output,true));
?>

A: $output = array(
        "code" => "UEX200",
      "details" => array(
        array(
        'email' => "username@gmail.com",
           'username' => "username,
           'type'         => "user",
           'account_manager' => "manager",
            status'       => "active
        )
     );
    );

try about code snap
{
"code": "UEX200",
"details": [{
    "email": "username@gmail.com",
    "username": "username",
    "type": "user",
    "account_manager": "manager",
    "status": "active"
}]

}


text:
Q: Minimal polynomial for $\sqrt[5]{2}$ over $\mathbb Q(\sqrt[]{3})$
Find the minimal polynomial for $\sqrt[5]{2}$ over $\mathbb
 Q(\sqrt[]{3})$.

The natural candidate is $x^5-2$. But the problem is to prove it is irreducible. In theory, I can write down the roots explicitly and by squaring multiple times somehow show that no root lies in the field. But even then there may be a quadratic factor, and using the method of undetermined coefficients is way too long. Can I prove irreducibility easier?

A: $\Bbb Z[\sqrt3]$ is UFD, $a^2-3b^2=2$ has no solution (since it has no solution mod $3$), so $2$ is prime in $\Bbb Z[\sqrt3]$. Now use Eisenstein.


text:
Q: How to run the Yahoo webplayer? I try to run the Yahoo webplayer like this:

Play Song

Play Text

*

*In Google Chrome it doesn't load at all.. (it's stuck at buffering...)

*in Firefox it tells me that Adobe Flash has stopped 'cause of "potentially unsafe operation" and it still doesn't load when I click "Ok"

Do you know how this player is supposed to work ?

A: check your file names for spaces or invalid characters


text:
Q: how to get tinytex to produce pdfs on rstudio? I have intstalled tinytex and now I was trying to knitr my .rmd to .pdf but I find myself with this message:
output file: *_report.knit.md

tlmgr search --file --global "/multirow.sty"
Trying to automatically install missing LaTeX packages...
tlmgr install multirow
No connection to the internet.
Unable to download the checksum of the remote TeX Live database,
but found a local copy so using that.

You may want to try specifying an explicit or different CTAN mirror;
see the information and examples for the -repository option at
http://tug.org/texlive/doc/install-tl.html
(or in the output of install-tl --help).

tlmgr.pl: package repository http://ctan.math.washington.edu/tex-archive/systems/texlive/tlnet (not verified: unknown)
[1/1, ??:??/??:??] install: multirow [3k]
TLPDB::_install_package: downloading did not succeed
tlmgr.pl: package log updated: C:/Users/***/AppData/Roaming/TinyTeX/texmf-var/web2c/tlmgr.log
tlmgr search --file --global "/multirow.sty"
! LaTeX Error: File `multirow.sty' not found.

! Emergency stop.
<read *>

Error: Failed to compile *_report.tex. See *_report.log for more info.
Execution halted

I suppose that I did something wrong or I am missing some code, but after looking around I just admitted defeat,
any help much appreciated
thanks,


text:
Q: How to add Gridded Reference Graphic widget in arcgis javascript api 4.14 I am using arcgis javascript api 4.14. And I need to add this Gridded Reference Graphic widget in map application.
So can any one please provide me some reference or sample code so I can add this widget.
And in javascript api 4.14 I am not able to find this widget.

A: I think you are talking about the widget or tool for the Web App Builder.
As far as I know it is not included in the API, so at least you are working with the Builder I don't think you can use it.
Web AppBuilder Docs - grg widget
Solution grg Widget - Old repository


text:
Q: why i cannot execute my alert javascript? can anyone help me? i've got a silly question. i try to make an alert function using js but it doesnt execute

and this is my delete button
Delete

A: I'm unsure why you have used the \ around your class name here, but one is within the quotes and one outside. I would remove these.

"btn delete btn-danger"

       Delete

As for your script, you should check if the document is ready before using JQuery - https://learn.jquery.com/using-jquery-core/document-ready/

A: It seems to work fine in the example below for me.

<!DOCTYPE html>

    Delete


text:
Q: How to run Magento 2 from a subdirectory I'm trying to set up a Magento 2 site that will run with http://www.example.com/store/ as its home page, but Magento's router is treating that subdirectory path as a frontend module name, and trying to run a module called store that doesn't exist.
My base URLs are configured as such:
mysql> select * from core_config_data where path like '%url';
+-----------+---------+----------+-----------------------+-------------------------------+
| config_id | scope   | scope_id | path                  | value                         |
+-----------+---------+----------+-----------------------+-------------------------------+
|         2 | default |        0 | web/unsecure/base_url | http://www.example.com/store/ |
|         3 | default |        0 | web/secure/base_url   | http://www.example.com/store/ |
+-----------+---------+----------+-----------------------+---------- --------------------+

With this setup, I updated the Nginx config, altering the location declarations to include /store at the beginning. Once that was done I was able to access the site and static assets were loading properly, however any page I tried to access resulted in Magento's fancy 404 page.
Since I knew the request was making it into the Mageto app, I had a hunch that Magento's routing was causing the issue. To test, I created a new module with a simple controller at /app/code/MyModules/Store/Controllers/Index/Index.php, and gave it a router with a frontName of store. Once I activated that module and reloaded the page, instead of a 404 I got the simple JSON output I had set up in my custom controller. So I know that Magento is getting the request and thinks the initial subdirectory that is part of its base URL is actually a frontName route.
So at this point I have two questions:

*

*Is it even possible to run a Magento 2 store in a subdirectory like this, or do I have to resort to using a subdomain?

*Assuming the answer to 1 is "yes, it is possible", what am I missing to make this work? I feel like there must be some setting somewhere that will resolve this, but I simply don't know where to look anymore.

A: I would recommend asking this on the Magento Stack Exchange and see if you can get more help if the following doesn't work.
My Experience
The short answer to your question is yes. Magento 2 works fine with subdirectories. I actually just pulled our website off a sub directory /store and went back to not having one. Well adding a sub directory and removing one are two different things I still ran into issues similar to what you are having. Here is what I did to debug/ fix the issue:

*

*From the dashboard check your configuration settings to see if it really is pulling in the correct web/unsecure/base_url and web/secure/base_url, this is under Stores > Configuration > Web. It sounds like it is but if not debug and fix this first.

*Through your hosting terminal or over SSH completely delete (remove) the var/di directory and var/view_processed directory.

*Again through your hosting terminal or over SSH run the following commands which assume you are at the root directory of your Magento installation. You may or may not need the php part and I did add extra commands because I don't know what you have done so far. None of these should harm anything.

php bin/magento cache:flush
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy
php bin/magento indexer:reindex

You may need to follow this by manually running the Full Page Cache in the admin dashboard under System > Cache management. After that make sure you hit F5 when you first check the front-end of your website so your browser refreshes its own cache of the site and everything should be working now.
The Main Problem
Magento 2 has done some amazing things to improve the user experience and speed up page load times. One of these things is improvements in caching which as you can see can cause a lot of problems for developers. When in doubt just refresh everything with the commands I posted and it usually resolves a lot of issues.
Update
Sorry just realized you did ask on the Magento Stack Exchange. One thing I should mention is I did not just copy the index.php and .htaccess file over to the /store directory. I actually moved the whole Magento installation into the /store directory before doing any of the stuff I mentioned. Then when I didn't need /store anymore I moved everything out and followed the steps I mentioned.


text:
Q: How to implement "Do you want to save changes?" dialog for a text editing program in Qt? I have written a text editing program similar to Notepad in C++ with the Qt framework. It only has basic functionality such as Undo, Redo etc. I want to show a dialog which will show up if the user hasn't saved his changes and ask whether he/she wants to save the changes similar to the one in Notepad and other such programs. How should I proceed with this?

A: Qt's documentation for QMessageBox discusses this and provides the following example: -
QMessageBox msgBox;
msgBox.setText("The document has been modified.");
msgBox.setInformativeText("Do you want to save your changes?");
msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Save);
int ret = msgBox.exec();

switch (ret) {
  case QMessageBox::Save:
      // Save was clicked
      break;
  case QMessageBox::Discard:
      // Don't Save was clicked
      break;
  case QMessageBox::Cancel:
      // Cancel was clicked
      break;
  default:
      // should never be reached
      break;
}

Applications can monitor when they're about to quit via the aboutToQuit signal, which is where you would prompt the user.
For example (with C++ 11)
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MainWindow w;

    // Note Qt 5 connect syntax with C++ 11 lambda function
    QObject::connect(qApp, &QCoreApplication::aboutToQuit, [&w](){

        qDebug() << "Terminating - Goodbye!\n";

        //Display msg prompt here
        if(QMessageBox::question(NULL, "Test", "Save?", QMessageBox::Yes|QMessageBox::No) == QMessageBox::Yes)
        {
            // if result is save...
            w.save();
        }
    });

    w.show();

    return a.exec();
}

A: you can do something like this:
        Document unsaveDocument = getUnsaveDocument();
        if (unsaveDocument.isModified()) {
           QMessageBox *alert = new QMessageBox;
           alert->setWindowTitle("File is modified");
           alert->setText("Do you want to save your changes?");
           alert->setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
           alert->setDefaultButton(QMessageBox::Save);
           int ret = alert->exec();
           alert->deleteLater();
           if (ret == QMessageBox::Save) {
               saveDocument();
           } else {
               doSomeThing(); //When discard or cancel
           }
       }


text:
Q: How to use iptables in an Android application How can I use iptables in an Android application? I need this for a firewall-like functionality i.e. packet filtering, blocking sites etc.
I'm also not sure whether iptables are available in the Android kernel.
I previously heard that I'd have to create cross-compiled binaries of iptables – but how can I do that? And how can I use them in the application?

A: It's definitely possible. You might consider looking at the source code of Droidwall.

DroidWall - Android Firewall is a front-end application for the powerful iptables Linux firewall. It allows you to restrict which applications are permitted to access your data networks (2G/3G and/or Wi-Fi).

Check out the iptables API from Droidwall for specific examples.
Note that when using iptables you need root access to your phone.


text:
Q: Filtering Columns According to Two Value Thresholds If I can only have a maximum of 2 Lateral and a maximum of 3 Zagueiro, and they cannot repeat values from Column 3, how should I do it?
I've already tried using QUERY with multiple "Limit" and already tried using FILTER(ISNA(MATCH())) but in both options the desired answer is not found.
Note: There can be no preference between Lateral and Zagueiro, the sequence of values is what counts as a rule, the higher, the more important.
Note 2: It may happen to find less than 2 Lateral or less than 3 Zagueiro
Example Data:
Filipe Luís            Lateral          Flamengo
Willian Arão           Zagueiro         Flamengo
Aderlan                Lateral          Bragantino
Mariano                Lateral          Atlético-MG
Nathan Silva           Zagueiro         Atlético-MG
Tinga                  Lateral          Fortaleza
Marcelo Benevenuto     Zagueiro         Fortaleza
Fabrício Bruno         Zagueiro         Vasco
Joaquim                Lateral          Vasco

Example Expected Result:
Filipe Luís            Lateral          Flamengo
Aderlan                Lateral          Bragantino
Nathan Silva           Zagueiro         Atlético-MG
Marcelo Benevenuto     Zagueiro         Fortaleza
Fabrício Bruno         Zagueiro         Vasco

Note 3: It was a coincidence that the values in Column 2 were perfectly separated, it can happen that the Zagueiro is above the Lateral, between two Lateral and so on. There is no specific sequence, everything goes according to the original sequence of data.
Note 4: Column 2 will only have the two values mentioned, there will be no others.
Link To Spreadsheet:
https://docs.google.com/spreadsheets/d/1JmX7V2zAYh-O0POOc0BpRp9ejcgLFRtsGZwlruRgHdY/edit?usp=sharing

A: try:
={ARRAY_CONSTRAIN(UNIQUE(FILTER(A1:C, B1:B="Lateral")), 2, 3);
 ARRAY_CONSTRAIN(FILTER(A1:C, B1:B="Zagueiro", REGEXMATCH(C1:C,
 TEXTJOIN("|", 1, FILTER(FILTER(C1:C, B1:B="Zagueiro"),
 NOT(COUNTIFS(ARRAY_CONSTRAIN(UNIQUE(FILTER(C1:C, B1:B="Lateral")), 2, 3),
 FILTER(C1:C, B1:B="Zagueiro"))))))), 3, 3)}

A: I've added a new sheet ("Erik Help") with the following formula in E1:
=ArrayFormula({VLOOKUP(ARRAY_CONSTRAIN(UNIQUE(FILTER(B1:B&C1:C,B1:B=B1)),2,1),{B1:B&C1:C,A1:C},{2,3,4},FALSE);VLOOKUP(ARRAY_CONSTRAIN(UNIQUE(FILTER(B1:B&C1:C,B1:B<>B1,ISERROR(VLOOKUP(C1:C,QUERY(VLOOKUP(ARRAY_CONSTRAIN(UNIQUE(FILTER(B1:B&C1:C,B1:B=B1)),2,1),{B1:B&C1:C,C1:C},2,FALSE),"Select *"),1,FALSE)))),3,1),{B1:B&C1:C,A1:C},{2,3,4},FALSE)})


text:
Q: How to deal with DataIncomplete error when accessing overpy query result Recently I have asked this question, and I got this answer, which was very helpful in identifying lakes using overpass-turbo.eu. Indeed, if I run the query, I get the desired result. An example, where I have clicked on a fountain is below (Oslo was in the centre of the map when I run the query).

I want to run the same query using Python. I define a bounding box:
bbox = {'latLower':59.9,'lonLower':10.7,'latHigher':60.0,'lonHigher': 10.8}

This bounidng box covers an area in Oslo. Then construct the text of the query:
querytext=\
f'''
/*
From: https://gis.stackexchange.com/a/412100/191643

This has been generated by the overpass-turbo wizard.
The original search was:
"(natural=water and type=multipolygon) or natural=water"
*/
[out:json][timeout:25];
// gather results
(
  // query part for: "natural=water and type=multipolygon"
  node["natural"="water"]["type"="multipolygon"]{overpy_bbox};
  way["natural"="water"]["type"="multipolygon"]{overpy_bbox};
  relation["natural"="water"]["type"="multipolygon"]{overpy_bbox};
  // query part for: "natural=water"
  node["natural"="water"]{overpy_bbox};
  way["natural"="water"]{overpy_bbox};
  relation["natural"="water"]{overpy_bbox};
);
// print results
out body;
'''

Then the query itself using overpy:
import overpy
api = overpy.Overpass()
result = api.query(querytext)

I access all the ways by:
result.get_ways()

which returns a list, a partial screenshot of it:

I highlighted the line which contains the same ID as I had above in the overpass-turbo.eu interface. Accessing the first node, for example:
result.get_ways()[0]

Output:
<overpy.Way id=4258487 nodes=[25526443, 4731901953, 4731901954, 4731901952, 25526546, 6794539693, 25526545, 6794539694, 4731901950, 6794539695, 25526439, 6794539696, 4731901951, 25526544, 4731901957, 7576044285, 7576027484, 25526543, 4731901958, 25526542, 23597818, 7576027483, 5273979151, 4731901959, 23597804, 4751403582, 25526444, 4751403583, 4731901960, 25526445, 4751403584, 4731901961, 4751403585, 25526446, 4751403586, 25526448, 4731901962, 4751403587, 25526452, 347545612, 347545599, 25526454, 23597806, 25526474, 8690362851, 25526558, 4751403592, 25526557, 25526554, 25526553, 25526552, 25526551, 25526498, 25526481, 4731901943, 25526475, 25526456, 23597809, 4731901944, 4731901945, 23597811, 4731901948, 4731901949, 4731901947, 4731901946, 23597814, 4731901963, 6839492557, 6839492556, 23597816, 6839492559, 25526549, 6839492558, 25526550, 7576044287, 25526548, 7576044286, 4731901956, 25526547, 4731901955, 25526443]>

Then I want to access the nodes itself:
result.get_ways()[0].nodes

But this gives me an error:
---------------------------------------------------------------------------
DataIncomplete                            Traceback (most recent call last)
<ipython-input-141-59cf0ff05ef6> in <module>()
----> 1 result.get_ways()[0].nodes

1 frames
/usr/local/lib/python3.7/dist-packages/overpy/__init__.py in nodes(self)
    894         List of nodes associated with the way.
    895         """
--> 896         return self.get_nodes()
    897
    898     def get_nodes(self, resolve_missing=False):

/usr/local/lib/python3.7/dist-packages/overpy/__init__.py in get_nodes(self, resolve_missing)
    921
    922             if not resolve_missing:
--> 923                 raise exception.DataIncomplete("Resolve missing nodes is disabled")
    924
    925             # We tried to resolve the data but some nodes are still missing

DataIncomplete: ('Data incomplete try to improve the query to resolve the missing data', 'Resolve missing nodes is disabled')

So I cannot get data out of the query this way.
How can I access the data which is displayed on the overpass-turbo.eu interface (for example, location of nodes), using Python?
Ideally, I'd like to have shapely polygons / multipolygons for the nodes forming part of a way.

A: The key was to use get_nodes(resolve_missing=True).
The full code is below.
Install overpy:
%%shell
pip install overpy
pip install geopandas

Imports:
import overpy
from overpy.exception import OverpassTooManyRequests, OverpassGatewayTimeout
import time
from tqdm import tqdm
import folium
from shapely.geometry.polygon import Polygon
import numpy as np
import geopandas as gpd

Define a bounding box:
bbox = {'latLower':59.9,'lonLower':10.75,'latHigher':59.91,'lonHigher': 10.775}

Create a string from it, to be used within Overpass query:
overpy_bbox=\
f"({bbox['latLower']},{bbox['lonLower']},{bbox['latHigher']},{bbox['lonHigher']})"

Create text of Overpass query, relying on this answer:
querytext=\
f'''
/*
From: https://gis.stackexchange.com/a/412100/191643

This has been generated by the overpass-turbo wizard.
The original search was:
"(natural=water and type=multipolygon) or natural=water"
*/
[out:json][timeout:25];
// gather results
(
  // query part for: "natural=water and type=multipolygon"
  node["natural"="water"]["type"="multipolygon"]{overpy_bbox};
  way["natural"="water"]["type"="multipolygon"]{overpy_bbox};
  relation["natural"="water"]["type"="multipolygon"]{overpy_bbox};
  // query part for: "natural=water"
  node["natural"="water"]{overpy_bbox};
  way["natural"="water"]{overpy_bbox};
  relation["natural"="water"]{overpy_bbox};
);
// print results
out body;
'''

Query:
api = overpy.Overpass()
result = api.query(querytext)

Process the query:
waydict={}
for way in tqdm(result.get_ways()):
    while True:
        try:
            nodes = way.get_nodes(resolve_missing=True)
            nodelist=[]
            for node in nodes:
                nodelist.append([float(node.lon), float(node.lat)])
            waydict[way.id]=nodelist
        except OverpassTooManyRequests:
            time.sleep(1)
            print('Retrying...')
            continue
        except OverpassGatewayTimeout:
            time.sleep(10)
            print('OverpassGatewayTimeout, retrying...')
            continue
        break

Process result a bit:
for id, way in waydict.items():
    polygon_obj = Polygon(np.array(way))

polygondict={}
for id, way in waydict.items():
    polygondict[id]= Polygon(np.array(way))

Create bounding box Polygon:
bbox_polygon_obj = Polygon(np.array([
                        [bbox['lonLower'],bbox['latLower']],
                        [bbox['lonLower'],bbox['latHigher']],
                        [bbox['lonHigher'],bbox['latHigher']],
                        [bbox['lonHigher'],bbox['latLower']]
                        ]))

Place results on Folium map:
m = folium.Map(location=[0.5*(bbox['latLower']+bbox['latHigher']),
                         0.5*(bbox['lonLower']+bbox['lonHigher'])], zoom_start=15, tiles='CartoDB positron')

for id, polygon in polygondict.items():
    geo_j = folium.GeoJson(data=gpd.GeoSeries(polygon).to_json(),style_function=lambda x: {'fillColor': 'red'})
    geo_j.add_to(m)

geo_j_bbox = folium.GeoJson(data=gpd.GeoSeries(bbox_polygon_obj).to_json(),style_function=lambda x: {'fillColor': 'red'})
geo_j_bbox.add_to(m)

m

A screenshot of the result:

Ie we got accessed the polygon data using Python & showed them on a map (with the bounding box as well): aim achieved.


text:
Q: Syntax error in load data infile I don't know why I am getting a syntax error. I have checked my query carefully many times and read up on mysql reference for load data infile and everything seems fine. Here is my query:
LOAD DATA LOCAL INFILE '/tmp/phpnm6Zek' IGNORE INTO TABLE loaddata_temp FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES (@sku, @model, @option, @option_value, @required, @quantity, @subtract, @price, @points, @weight) SET sku=@sku, model=@model, option=@option, option_value=@option_value, required=@required, quantity=@quantity, subtract=@subtract, price=@price, points=@points, weight=@weight

This is the error that I am getting:
Notice: Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'option=@option, option_value=@option_value, required=@required, quantity=@quanti' at line 1
Error No: 1064
LOAD DATA LOCAL INFILE '/tmp/phpO6k4u3' IGNORE INTO TABLE loaddata_temp FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES (@sku, @model, @option, @option_value, @required, @quantity, @subtract, @price, @points, @weight) SET sku=@sku, model=@model, option=@option, option_value=@option_value, required=@required, quantity=@quantity, subtract=@subtract, price=@price, points=@points, weight=@weight

A: The word option is a reserved word :
You need to surround the word option with back quotes.
LOAD DATA LOCAL INFILE '/tmp/phpnm6Zek'
IGNORE INTO TABLE loaddata_temp
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES (@sku, @model, @option, @option_value, @required,
@quantity, @subtract, @price, @points, @weight) SET sku=@sku, model=@model,
`option`=@option, option_value=@option_value, required=@required, quantity=@quantity,
subtract=@subtract, price=@price, points=@points, weight=@weight

Give it a Try !!!


text:
Q: Trapping and throwing errors when using ExecuteNonQueryAsync which returns Task When I do the following, I get a warning that not all code paths return a value if the catch block doesn't return an int; when that catch block returns an int, the capturedException test for null becomes unreachable unless it is placed inside a finally block.  Is putting the throw inside finally{}  acceptable?  Is the connection closed automatically as it would be in a synchronous method that employs the using syntax?
public async Task<int> Write2Log()
{
  ExceptionDispatchInfo capturedException = null;
  using (SqlConnection conn = new SqlConnection(connectionString))
  {
      using (SqlCommand cmd = new SqlCommand(commandText, conn))
      {
         try
           {
         await cmd.Connection.OpenAsync();
         return await cmd.ExecuteNonQueryAsync();
            }
           catch (Exception ex)
             {
               capturedException=ExceptionDispatchInfo(ex);
               return -1;
             }

             // unreachable unless placed inside `finally` block
            if (capturedException != null)
              {
                   capturedException.Throw();
              }

      }

  }
}

A: your code in question seems to be incorrect but anyway you need not return in catch.....you can return in end of the method. you know that successful scenario will never reach end of method.
public async Task<int> Write2Log()
{
  ExceptionDispatchInfo capturedException = null;
  using (SqlConnection conn = new SqlConnection(connectionString))
  {
      using (SqlCommand cmd = new SqlCommand(commandText, conn))
      {

          try
{
         await cmd.Connection.OpenAsync();
         return await cmd.ExecuteNonQueryAsync();
}
           catch (Exception ex)
             {
               capturedException=ExceptionDispatchInfo(ex);

             }

             // unreachable unless placed inside `finally` block
            if (capturedException != null)
              {
                   capturedException.Throw();
              }

      }

  }
   return -1;
}

A: The code you're clumsily trying to write is equivalent to the much simpler
public async Task<int> Write2Log()
{
  using (var conn = new SqlConnection(connectionString))
  {
    using (var cmd = new SqlCommand(commandText, conn)
    {
      await conn.OpenAsync();
      return await cmd.ExecuteNonQueryAsync();
    }
  }
}

If you don't see why, you might want to refresh your knowledge about how .NET exceptions work, and how await works (and in particular, how it handles exceptions).
If you also want to observe the exception (e.g. for logging), you can use throw; to rethrow the exception at the end of the catch. There's no need to use ExceptionDispatchInfo, and there's no point in storing the exception in a local to rethrow later.
If you're instead trying to return -1 when there's an error, just do
public async Task<int> Write2Log()
{
  using (var conn = new SqlConnection(connectionString))
  {
    using (var cmd = new SqlCommand(commandText, conn)
    {
      try
      {
        await conn.OpenAsync();
        return await cmd.ExecuteNonQueryAsync();
      }
      catch
      {
        return -1;
      }
    }
  }
}

A method cannot throw an exception and return a value at the same time. You have to choose one.