text:
Q: Getting GML features with OpenLayers from Spanish Cadaster fails I'm trying to paint parcels retrieved from Spanish land register by their API (as described here, PDF Spanish only!). It's an WFS service (complying INSPIRE) and offers the information as GML versión 3.2.1 files.
Here an example response (using this call) to retrieve parcels by their cadaster reference:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--Parcela Catastral de la D.G. del Catastro.-->
<!--La precisión es la que corresponde nominalmente a la escala de captura de la cartografía-->
<FeatureCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:cp="http://inspire.ec.europa.eu/schemas/cp/4.0" xmlns:gmd="http://www.isotc211.org/2005/gmd" xsi:schemaLocation="http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd http://inspire.ec.europa.eu/schemas/cp/4.0 http://inspire.ec.europa.eu/schemas/cp/4.0/CadastralParcels.xsd" xmlns="http://www.opengis.net/wfs/2.0" timeStamp="2022-08-30T19:29:52" numberMatched="1" numberReturned="1">
  <member>
    <cp:CadastralParcel gml:id="ES.SDGC.CP.3662001TF3136S">
      <cp:areaValue uom="m2">3814</cp:areaValue>
      <cp:beginLifespanVersion>2021-06-09T00:00:00</cp:beginLifespanVersion>
      <cp:endLifespanVersion xsi:nil="true" nilReason="http://inspire.ec.europa.eu/codelist/VoidReasonValue/Unpopulated"></cp:endLifespanVersion>
      <cp:geometry>
        <gml:MultiSurface gml:id="MultiSurface_ES.SDGC.CP.3662001TF3136S" srsName="http://www.opengis.net/def/crs/EPSG/0/25830">
          <gml:surfaceMember>
            <gml:Surface gml:id="Surface_ES.SDGC.CP.3662001TF3136S.1" srsName="http://www.opengis.net/def/crs/EPSG/0/25830">
              <gml:patches>
                <gml:PolygonPatch>
                <gml:exterior>
                    <gml:LinearRing>
                      <gml:posList srsDimension="2" count="68">233565.81 4016077.37 233581.88 4016079.67 233582.39 4016079.64 233582.41 4016079.64 233582.93 4016079.61 233582.95 4016079.79 233584.21 4016095.89 233590.37 4016086.81 233608.95 4016076.64 233622.4 4016059.04 233634.4 4016039.96 233635.42 4016038.33 233637.7 4016034.42 233639.69 4016030.68 233639.92 4016030.24 233641.36 4016028.14 233641.81 4016027.47 233643.7 4016024.87 233644.86 4016023.27 233646.95 4016020.39 233645.01 4016006.5 233655.45 4015995.96 233655.14 4015995.64 233651.48 4015991.83 233650.44 4015990.75 233648.45 4015992.4 233640.59 4015999.13 233639.85 4015999.81 233639.12 4016000.48 233637.69 4016001.88 233636.31 4016003.33 233634.97 4016004.81 233633.68 4016006.34 233633.17 4016006.97 233628.43 4016014.77 233626.25 4016018.35 233623.19 4016023.38 233623.04 4016023.63 233619.94 4016026.88 233615.37 4016031.67 233614.08 4016033.01 233613.46 4016033.66 233610.82 4016035.98 233602.71 4016043.12 233600.17 4016045.28 233596.47 4016048.66 233591.23 4016053.38 233589.87 4016052.05 233584.62 4016052.25 233584.33 4016052.26 233581.97 4016049.04 233578.37 4016045.27 233576.52 4016043.93 233574.11 4016042.19 233569.38 4016039.9 233564.32 4016038.46 233559.09 4016037.93 233553.84 4016038.31 233548.39 4016039.75 233543.94 4016041.75 233537.63 4016037.54 233535.81 4016033.81 233535.16 4016033.58 233530.41 4016023.48 233532.15 4016035.61 233543.76 4016066.93 233552.15 4016070.9 233565.81 4016077.37</gml:posList>
                    </gml:LinearRing>
                </gml:exterior>
                </gml:PolygonPatch>
              </gml:patches>
            </gml:Surface>
          </gml:surfaceMember>
        </gml:MultiSurface>
      </cp:geometry>
      <cp:inspireId>
        <Identifier xmlns="http://inspire.ec.europa.eu/schemas/base/3.3">
          <localId>3662001TF3136S</localId>
          <namespace>ES.SDGC.CP</namespace>
        </Identifier>
      </cp:inspireId>
      <cp:label>01</cp:label>
      <cp:nationalCadastralReference>3662001TF3136S</cp:nationalCadastralReference>
      <cp:referencePoint>
        <gml:Point gml:id="ReferencePoint_ES.SDGC.CP.3662001TF3136S" srsName="http://www.opengis.net/def/crs/EPSG/0/25830">
          <gml:pos>233584.35 4016065.6</gml:pos>
        </gml:Point>
      </cp:referencePoint>
    </cp:CadastralParcel>
  </member>
</FeatureCollection>

Right now I manually parse the XML file and make a vector feature, but would be more elegant to make the feature from GML32 format. To do so, I tried to get the parcel geometry from GML, but without success:
const parser = new ol.format.GML32({
    featureNS: 'http://inspire.ec.europa.eu/schemas/cp',
    featureType: 'CadastralParcel'
});
console.log(parser.readFeature(wfsCPxml));

I also tried using WFS format, but same null result (after changing manually surfaceMember to featureMember as mentioned here):
const wfs = new ol.format.WFS({
  gmlFormat: new ol.format.GML32({
    featureNS: 'http://inspire.ec.europa.eu/schemas/cp',
    featureType: 'CadastralParcel'
  })
});
console.log(parser.readFeature(wfsCPfeaturexml));

Here is the related jsfiddle, any idea what I'm doing wrong?


text:
Q: About threads in c# I have a button click which contains some ten methods. Here I want to use threads in the button click or some where in the code so that my windows form application will not hang.
This what I have tried so far...!!
                collectListOfPTags();

                REqDocCheck = new Thread(new ThreadStart(collectListOfPTags));

                REqDocCheck.IsBackground = true;

                REqDocCheck.Start();

                WaitHandle[] AWait = new WaitHandle[] { new AutoResetEvent(false) };
                while (REqDocCheck.IsAlive)
                {
                    WaitHandle.WaitAny(AWait, 50, false);
                    System.Windows.Forms.Application.DoEvents();
                }

In the method collectionListOfPtags() am getting an exception which says "a combobox is accessed from the thread other than it was created on"
Thank's for the patience..
Any help will be appreciated..

A: What you need here is a delegate! You simply need to create a delegate and put it in the function which accesses GUI from thread function.
public delegate void DemoDelegate();

In your code,
collectionListOfPtags()
{
    if ((this.InvokeRequired)) {
    this.Invoke(new DemoDelegate(collectionListOfPtags));
    return;
    }

     // Your Code HERE
}

I hope this will work!  Good Luck :-)

A: This looks like a good fit for the BackgroundWorker component.
Split your collectListOfPTags method into 2 methods - the first collects and processes the data and the second updates the UI controls.
Something like this:
void OnClick( ... )
{
  var results = new List<string>();

  var bw = new BackgroundWorker();

  bw.DoWork += ( s, e ) => CollectData( results );
  bw.RunWorkerCompleted += ( s, e ) => UpdateUI( results );

  bw.RunWorkerAsync();
}

void CollectData( List<string> results )
{
  ... build strings and add them to the results list
}

void UpdateUI( List<string> results )
{
  ... update the ComboBox from the results
}

The BackgroundWorker will run CollectData in the background on a thread pool thread, but will run UpdateUI on the UI thread so you can access the ComboBox correctly.

A: You should take a look at threadpools?  A thread pool is a collection of threads that can be used to perform several tasks in the background. They are simple of use and thread safe.
Here's an (really simple) example :
http://msdn.microsoft.com/en-us/library/h4732ks0.aspx

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show and Hide only one  using jQuery .hide/.show The .show and .hide jQuery code works for every  with the class .q_open and q_close. I'm well aware that my because all my
 tags have the class of .answer so they will show and hide both answers when I click on any . Is there a way to reference only one
 when clicking on that  tag rather than giving each
 a different class? Thanks!
The JavaScript code:

The HTML code:

          Q1: (the first question)

          This should only open when clicked by the  for Q1.

          Q2: (the second question)

           This should only open when clicked by the  for Q2.

A: I think you are looking for some sort of accordion. For that, you need to target the exact HTML element to open or close.
Try this:
$(function() {
  $(".q_open").click(function() {
    // Select the related target to open
    $(this).closest("h2").next(".answer").slideDown();
  });

  $(".q_close").click(function() {
    // Select the related target to close
    $(this).closest("h2").next(".answer").slideUp();
  });
});

Here is working example: https://jsfiddle.net/ashishanexpert/1xydbj22/

A: Use
$(this).find('.answer').show()

Like this:

A: replace class with id

          Q1: (the first question)
          Open
          Close

  This should only open when clicked by the  for Q1.

          Q2: (the second question)
          Open
  Close

    This should only open when clicked by the  for Q2.


text:
Q: How can I convert the first character of a column to an uppercase for every row? I have this table:
CREATE TABLE [dbo].[Phrase] (
    [PhraseId]     UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
    [English]      NVARCHAR (MAX)   NOT NULL,
    PRIMARY KEY CLUSTERED ([PhraseId] ASC)
);

Can someone give me some advice on how I could convert the first letter of the column English to upper case in all of the rows?

A: Try it like this
DECLARE @tbl TABLE(PhraseId INT,English VARCHAR(100));
INSERT INTO @tbl VALUES(1,'this'),(2,'is'),(3,'easy');

UPDATE @tbl SET English=STUFF(English,1,1,UPPER(LEFT(English,1)));

SELECT * FROM @tbl

A: Another way without using STUFF, though I like STUFF better
Update phrase set English = upper(left([English],1)) + right([English], len([English]) - 1)


text:
Q: Taking the limit of $n(e^{-1/n}-1)$ as $n$ approaches infinity The form is infinity times zero and that is indeterminate which means I need to use L'Hospital's rule, but I have tried to do that but every time I would find another indeterminate form.  How can I use sneaky algebra or sneaky replacements to find the answer?

A: By the verys definition of derivative, this limit equals $f'(0)$ where $f(x)=e^{-x}$: Note that $\frac{f(0+h)-f(0)}{h}=n(e^{-1/n}-1)$ if $h=\frac1n$.

A: Hint: try expanding $e^{-1/n}$ as a power series: $$e^{-1/n}=1-\frac{1}{n}+\frac{1}{2!} \frac{1}{n^2}+ \dots=1-\frac{1}{n}+\mathcal{O}(n^{-2}) .$$

A: recall $$e^x=1+x+O(x^2)$$as $x\to0$ hence$$e^{-1/n}=1-1/n+O(1/n^2)$$ as $n\to\infty$ and so $$\lim_{n\to\infty}n(e^{-1/n}-1)=\lim_{n\to\infty}n(-1/n+O(1/n^2))=\lim_{n\to\infty}(-1+O(1/n))=-1$$

A: Note that, in general $$\lim_{\alpha\to 0}\frac{x^\alpha-1}{\alpha}=\log x$$

A: L'Hospital's Rule is not my favourite approach, since a computation replaces insight about the behaviour of the function. But one cannot deny its usefulness. We do two L'Hospital's Rule calculations.
Calculation 1: We want to find
$$\lim_{n\to\infty}\frac{e^{-1/n}-1}{1/n}.\tag{1}$$
Let $x=\frac{1}{n}$. As $n\to\infty$, $1/n\to 0^+$. So if
$$\lim_{x\to 0^+} \frac{e^{-x}-1}{x}\tag{2}$$
exists, then our limit does, and is the same.
Now use L'Hospital's Rule, taking the derivative of the top and bottom of (2), Since
$$\lim_{x\to 0^+} \frac{-e^{-x}}{1}=-1,$$
our limit exists and is $-1$.
Calculation 2: This time, we deliberately do things in a suboptimal way, by finding
$$\lim_{y\to\infty}\frac{e^{-1/y}-1}{1/y}.$$
Take the derivative of top and bottom. So we want to find
$$\lim_{y\to\infty}\frac{(-1/y^2)(-e^{-1/y})}{(-1/y^2)}.$$
The above simplifies to
$$\lim_{y\to\infty}(-e^{-1/y}),$$
which is $-1$.

A: You can only use L hospitals rule, if you have 0/0 or inf/inf form.
So, rewrite your expression as (e^[-1/n] - 1)/(1/n) and now use the rule


text:
Q: How to set Authorization only in one end point in WCF In WCF service i have added one more Binding (webHttpBinding). Now i want to apply Basic Authorization with these new web behavior. Previous end point and bindings should work without effect any changes is it possible I have one implementation with Same contract and function.

A: In principle every binding can have it's own security setting. webHttpBinding seems to have three security levels to choose from (None, Transport and TransportCredentialOnly) see https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/wcf/security-of-webhttpbinding. If you are careful not to touch the security settings of your other bindings in your other endpoints they should not be affected by introducing a new endpoint with a new binding.


text:
Q: Correct way to dispose a batch of Memory streams in C# I have the following code but am worried about the creation of a List<MemoryStream> just so I can dispose them in the try..finally block
/// <summary>
/// Emit a batch of log events, running to completion asynchronously.
/// </summary>
/// <param name="events">The events to emit.</param>
/// <remarks>Override either <see cref="PeriodicBatchingSink.EmitBatch"/> or <see cref="PeriodicBatchingSink.EmitBatchAsync"/>,
/// not both.</remarks>
protected override async Task EmitBatchAsync(IEnumerable<LogEvent> events)
{
    var streams = new List<MemoryStream>();
    try
    {
        var req = new PutRecordsRequest { StreamName = streamName };

        foreach (var logEvent in events)
        {
            var json = await JsonConvert.SerializeObjectAsync(logEvent);
            var payload = Encoding.UTF8.GetBytes(json);
            var data = new MemoryStream(payload);

            var entry = new PutRecordsRequestEntry
            {
                PartitionKey = Guid.NewGuid().ToString(),
                Data = data
            };

            req.Records.Add(entry);
            streams.Add(data);
        }

        await client.PutRecordsAsync(req);
    }
    catch (Exception e)
    {
        SelfLog.WriteLine(e.ToString());
    }
    finally
    {
        streams.ForEach(x => x.Close());
    }
}

A: When that streams is only used in the finally then you're better off without it.
A MemoryStream does not actually need to be Disposed (Closed) and when it's in some async pipeline, leave it be. The Garbage collector will reclaim it.


text:
Q: NMOS T3 always on
Hi all, i have this circuit that is actually really simple. when I came to do the prototype, something that i can't explain happens.
the transistor T3 is always on even if i do not connect the supply VG1, how this is possible?
i'm sure about the pinout, checked several times. also i'm using a bjt for pnp, so no body diode that accidentally turns the transistor on should be there.
some help?

A: The 2N6755 \$V_{DSS}\$ (maximum drain-source voltage) is spec'd at 60v, but you are applying +/-80v.
\$V_{SD}\$ or diode forward voltage is listed as 1.7v, implying that these also have an intrinsic body diode to consider.


text:
Q: Disabling MAC randomization makes connection to the Internet slower I have two routers, the main connected to the internet in the living room (Router A),and a second one (Router B) in another room, connected to router A via a LAN cable. Router B has DHCP disabled. This works perfectly and I can access the internet while connecting to Router B. However, if I disable MAC randomization, it does connect my laptop to the network instantly but it takes ~5 to 6 minutes to actually connect to the internet. Enabling MAC randomization does solve this issue but I get a different IP every time I switch from router A to router B. And having a static ip for my laptop is not an option.
How do I resolve this? (i.e how do I switch from Router A to B and vice versa while keeping the same IP?)
P.S connecting to Router A occurs instantly regardless of MAC randomization being enabled or disabled. Also, both routers do not have the same SSID


text:
Q: Piping output to local machine in a loop I am trying to read some files located on a server and write only a certain number of columns from those files onto my local machine. I am tried to do this in a for loop to avoid inputting my password for each file. Below is what I was able to cobble till now.
The following code works but writes all the output to a single file which is not manageable due to its large size.
ssh user@xx.xxx.xxx.xx 'for loc in /hel/insur/*/201701*; do zcat $loc | grep -v NUMBER | awk -F',' -v OFS="," '\''{print $1,$2,$3,$4,$5}'\'' | gzip; done'  > /cygdrive/c/Users/user1/Desktop/test/singlefile.csv.gz

So, I tried to write each file individually as shown below but it gives me an error saying that it cannot find the location(possibly because I am sshed ito the remote server).
ssh user@xx.xxx.xxx.xx 'for loc in /hel/insur/*/201701*; do zcat $loc | grep -v NUMBER | awk -F',' -v OFS="," '\''{print $1,$2,$3,$4,$5}'\'' | gzip > /cygdrive/c/Users/user1/Desktop/test/`echo $loc | cut -c84-112` ; done'

Any ideas on how to solve this?


text:
Q: Trying to number compounds from ChemDraw I'm new to LaTeX and have been trying to solve this for a few hours now.
Hi everyone - I'm new to LaTeX and have been trying to solve this for a few hours now.
I'm trying to transfer compounds made in ChemDraw (that I've exported as .eps files) into LaTeX. My ideal goal would be to have LaTeX automatically number all my compounds as I put them in (i.e. if I add a compound in before all the others, the compounds would all automatically renumber).
So far, I've not even been able to convert one temporary label to the number "1". See below:
\begin{figure}

\begin{center}

\replacecmpd{TMPA}

    \includegraphics[scale=0.7]{Diagrams/"Taxol, Numbered".eps}

        \caption{Taxol}

\end{center}

\end{figure}

EPS file here: https://drive.google.com/open?id=1BWAuTo6YzSeLVQRIQaf4gzG5k5uw84qY
ChemDraw version: 16.0.1.4 (61)
I'm super confused about chemnum vs chemfig vs chemscheme and so far have not been able to get anywhere with any of them - please help!
Thanks for your time!

A: I have not tried this for a few years, but I used Joseph Wright's chemstyle package as well as the auto-pst-pdf package to automatically number structures. Basically, you would export your structures in .eps with the TMP1, TMP2, etc. placeholders and then insert your pictures in the scheme environment, specifying a code/tag/label/etc for each molecule. The placeholders are then converted to numbers while typesetting. You can also refer to the molecules numbers using \compound{<your compound label>} in inline text.
After fiddling and tinkering with old code, this example says it better:
\documentclass{minimal}
\usepackage[crop=off,runs=2]{auto-pst-pdf}
\usepackage{chemstyle}

\begin{document}

\begin{scheme}[h]
\centering
    \schemeref[TMP1]{msoc2c6f13}
    \schemeref[TMP2]{imc2c6f13}
        \includegraphics[scale=1]{pfaim}
    \caption{a chemscheme}
    \label{sch:pfaim}
\end{scheme}%

Mesylate \compound{msoc2c6f13} was converted to the N-fluoroalkylated imidazole \compound{imc2c6f13}.

\end{document}

Which will give you this result:

There's a few caveats though, which you must be made aware of:

*

*You will need to allow shell escape (i.e. data from your code going out and in your typesetting program, more explanations here: What are \immediate & \write18 and how does one use them?) for auto-pst-pdf to process your TMP tags. Depending on your typesetting habits, you might want to have it for all your documents or just a few. You should be able to allow it either from your typesetting program or the document (e.g. if you're using arara).

*If you need some specific order in the numbering, you will need to declare the compounds in that order, using \compound*{...} (e.g. at the beginning of a section).

*Sometime between 2016 and now, auto-pst-pdf defaulted the crop option; this causes the converted .eps to be cropped, and, in my test case, to lose parts of the structures. Hence the crop=off option.

For (a lot) more details, you should also read Joseph Wright's chemstyle manual, it is full of useful tricks.


text:
Q: If $f+f'<\varepsilon$, then $f'<\varepsilon$
Let $f$ be continuous on $[a,b]$ and differentiable on $(a,b)$ and there exstis $\varepsilon>0$ such that $f(x)+f'(x)<\varepsilon$ for all $x\in (a,b)$. Prove that $f'(x)<\varepsilon$ for all $x\in (a,b)$.

These are my efforts:
$\bullet$ If $f(x)\ge 0$ then $f'(x)<\varepsilon$, so we just need to consider those $x$ such that $f(x)<0$.
$\bullet$ Consider $g(x)=f(x)\cdot e^x-\varepsilon\cdot e^x$ then $g$ decreases on $(a,b)$. If $f(c)<\varepsilon$, then $f(x)<\varepsilon$ for all $x\in [c,b]$.
$\bullet$ If $f(x_0)\ge \varepsilon$ for some $x_0$ then $f$ increases in some neighborhood of $x$.
I cannot completely solve it. Thanks so much for any help.

A: Let $f(x) =- e^{-x}$. Then $f+f^\prime = 0$.


text:
Q: Why does createRef() returns current: null? I am trying to use createRef to get access to the clientHeight property of several images. However, everytime I console.log the "this.imageRef" the return is {current:null}. My react is 16.7. What am I not seeing?
Additionally, PictureForGrid is a component I am using to just render and eventually add the clientHeight to state. It is called by Parent. I will include both, but I think you just need the PictureForGrid.
Component in Question
    import React from 'react';
class PictureForGrid extends React.Component {
constructor(props) {
    super(props);

    this.imageRef = React.createRef();
}

componentDidMount() {
    console.log(this.imageRef.current);
    console.log(this.imageRef);
}

render() {

    return (

    )
}
}

export default PictureForGrid;

The Parent Component
import React from 'react';

import PictureForGrid from '../PictureForGrid';
import '../../styles/Parent.css'
import one from '../../pics/one.jpg'
import two from '../../pics/two.jpg'
.
.
.
.
import fourteen from '../../pics/Alyssa and Ryne/fourteen.jpg'

class Parent extends React.Component {
render() {
    return (

            <PictureForGrid source={one} description="erin working"/>
            <PictureForGrid   source={two} description="hands holding lamp"
/>
            <PictureForGrid   source={three} description="chapel" />
            <PictureForGrid   source={four} description="dancing couple"/>
            <PictureForGrid   source={five} description="couple holding
wedding sign"/>
            <PictureForGrid  source={six} description="couple at steeple"/>
            <PictureForGrid  source={seven} description="post wedding"/>
            <PictureForGrid  source={eight} description="groomsmen"/>
            <PictureForGrid  source={nine} description="bridal party"/>
            <PictureForGrid  source={ten} description="shower"/>
            <PictureForGrid  source={eleven} description="flowers"/>
            <PictureForGrid  source={twelve} description="water fountain"/>
            <PictureForGrid  source={thirteen} description="rings"/>
            <PictureForGrid  source={fourteen} description="ceremony"/>

    )
}
}

export default Parent;

Thanks for any advice, as I am obviously new to this.

A: You have a typo
Change

To


text:
Q: Search for the most efficient voltage regulator on low current consumption I'm currently designing a circuit for a long term device that will consume 1-2mA at 3.3V constantly. The system is run with a default lithium polymer battery and I need to get as much time out of it as possible.
In the current state, I'm searching for the most efficient voltage regulator possible. The best one I could find was the TPS63805. It is a switching voltage regulator which means that it takes more space and costs more, which is luckily not a big problem for my project.
It seems to be that these kind of regulators are a bit more efficient on higher current consumptions. When only using 1mA, it is at about 90% efficiency, which is good but can it get better with another component or technique? (I'm already making sure to minimize the power loss through PCB design.)
Thanks for any help in advance!

PS: Sorry for any grammar or spelling mistakes, I'm not a native English speaker.

A: As Tony mentioned, you might consider running at a lower voltage, so that you can take advantage of an ultra efficient step down regulator, designed for energy harvesting applications. For example, the ADP5304.
If you can run at 2.5v instead, then your efficiency could be 90% - 95%, depending on your battery voltage:

If you really need 3.3v out, then you'd only be able to run until your battery ran down to 3.3v. At that point, the ADP5304 switches to 100% duty mode. However, your efficiency will be better than 95%.

A: The problem with most any switching regulator is that they don't give good efficiency at light load. They also have quiescent current that further reduces efficency.
A more reasonable approach is to specify your powered logic to support a voltage range compatible with your battery, say 3.0 to 3.6V. Then, use an ultra-low dropout LDO to take care of the range above that (up to about 4.2V for a fully-topped LiPo cell, typically 3.7V for most of the range.) For most of the discharge cycle the LDO will only be adding dropout loss (as low as 50mV for some, like the ST LDO40L.)
For your 1mA load, and 100mV overhead at 3.7V (regulator set for 3.6V):

*

*total power: 3.7V * 1mA = 3.7mW

*overhead loss = (0.10V * 1mA) = 0.1 mW

*efficiency: (3.7-0.1)mW / 3.7mW * 100% = 97.3%

This gets even better as the battery voltage gets lower and the regulator is in dropout:

*

*total power: 3.5V * 1mA = 3.5mW

*overhead loss = (0.05V * 1mA) = 0.05 mW

*efficiency: (3.5-0.05)mW / 3.5mW * 100% = 98.6%

MORE: You mentioned that your peak power is ~400mA. One strategy to deal with that is power the RF front end directly from the battery. Many of the ICs used for this purpose support a wider voltage range than digital.

BONUS: a fixed 3.6V regulator with about 2mV dropout at 1mA, and up to 150mA: Maxim MAX887_EUK36 https://www.mouser.com/datasheet/2/256/MAX8878-1389229.pdf


text:
Q: JSON Compression in Scala JSON compression using serialise and deserialise does work. But the storing and reloading of the compressed json is not working.
After storing the compressed JSON in text file. The next application loads that file and tries to deserielise it. The next application loads the file and reads in line-by-line as text, how do i convert the text to byteArray so that I can deserielise it back to JSON
If I serielise a string and take the result and deserielise it, it works. the minute i write the serielse/compressed json to file and reload it into a string variable and then try to deserielse it, it does not work.
I know the problem lies in storing and reloading the compressed JSON
def serialise(value: Any): Array[Byte] = {
    val stream: ByteArrayOutputStream = new ByteArrayOutputStream()
    val oos = new ObjectOutputStream(stream)
    oos.writeObject(value)
    oos.close()
    stream.toByteArray
  }

  def deserialise(bytes: Array[Byte]): Any = {
    val ois = new ObjectInputStream(new ByteArrayInputStream(bytes))
    val value = ois.readObject
    ois.close()
    value
  }

// WORKS (Below)
def main(args: Array[String]): Unit = {
   val json_msg_string = "{\"data_type\":\"input\"}
   val s_result: Array[Byte] = serialise(json_msg_string)
   val d_result = deserialise(s_result)
}

// Does NOT work (Below)
def main(args: Array[String]): Unit = {

   val json_msg_string = "{\"data_type\":\"input\"}
   val s_result: Array[Byte] = serialise(json_msg_string)

   // write to file
   new PrintWriter("/home//test_json_compressed.txt") { write(s_result.toString); close }

   // reload file
   for (line <- Source.fromFile(filename).getLines) {
      deserialise(line)
    }
}

*

*What is the best and fastest way to compress JSON (Scala)

*How do I store the compressed JSON (Scala)

*How do I reload the compressed JSON and convert it back to JSON (Scala)


text:
Q: В матрице A [i, j] m, n поменять местами строки с min и max суммами элементов в строке Проблема следующая мы создаем матрицу, задаем размерность. Дальше считаем суммы каждой строки. Определяем строку с наибольшей суммой и наименьшей сумой и меняем их местами. Строка с наибольшей суммой у меня определяется а наименьшей не получается. По коду будет видно.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class _Program
    {
        static void Main(string[] args)
        {
            int n, m, sum = 0, summax;

            Console.WriteLine("Введ n-рядків и m-стовбців!");
            Console.Write("n=");
            n = Convert.ToInt32(Console.ReadLine());
            Console.Write("m=");
            m = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine();

            int[,] k = new int[n, m];
            Random r = new Random();
            Console.WriteLine("Матриця: ");

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    k[i, j] = r.Next(0, 100);

                    Console.Write(String.Format("{0,3} ", k[i, j]));
                }
                Console.WriteLine();
            }

            summax = -1;
            int summin = 0;
            int rowmin = 0;
            int rowmax = 0;
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                    sum += k[i, j];
                if (sum > summax)
                {
                    summax = sum;
                    rowmax = i + 1;
                }

                else
                {
                    summin =  sum;  // ??
                    rowmin = i-1;
                }

                Console.WriteLine();
                Console.WriteLine("Сума " + (i + 1) + " рядка рівна " + sum);
                sum = 0;
            }

                Console.WriteLine();
                Console.WriteLine("Найбільша сума у " + rowmax + " рядку, сумма " + summax);
                Console.WriteLine("Наймеша сума у " + rowmin + " рядку, сумма " + summin);
                Console.ReadKey();
            }
        }
    }


text:
Q: gRPC How to know if a client is getting throttled In gRPC go, how can I know if a client is getting throttled by a server.
Is there any event I could listen to to observe this?
In my case, I'm using a simple Unary.
I've used a tcpdump and checked for the frequency of window update event, but I guess there may be a better way to do so.

A: Channelz might have what you want: https://github.com/grpc/proposal/blob/master/A14-channelz.md#socket-data
You need to make a server: https://pkg.go.dev/google.golang.org/grpc@v1.44.0/channelz/service#RegisterChannelzServiceToServer, and use a grpc client to read the data (e.g. https://github.com/grpc-ecosystem/grpcdebug)
If I remember correctly, it doesn't send signals when flowcontrol window is depleted. But it prints the window size for debugging purposes.

And note that frequency of window update event doesn't indicate if the client is blocked on flowcontrol. Window updates are exchanges regularly to keep track of the flow control window.


text:
Q: Could I lose reputation on Meta Stack Overflow? When I look at "Meta Stack Overflow" https://meta.stackoverflow.com/, I see many users asking good and bad questions, but I noticed that users asking bad questions who got downvoted don't seem to lose any reputation at all. Is it normal or do the downvotes and upvotes in this need to be validated by a moderator?

A: The reputation on the per-site metas are inherited from the main site. So on Stack Overflow I have 66K reputation, on Meta Stack Overflow I have the exact same amount (it is synced one a while, so it is not totally accurate at all time).
So voting on the per-site meta doesn't bring you any reputation, nor you will lose any. You will only receive badges on posts on the votes (like Nice Question, Motarboard, etc.).
Voting is anonymous, so moderators have no intervention in validating votes, unless someone is suspected to be serial voting for example.

A: No, you cannot lose reputation on a child meta (that is a meta that has a main site - like Meta Stack Overflow that has Stack Overflow).
The reputation on a child meta is inherited from the main site and is synced from it every now and then.
Now, by asking on a child meta, you may get more people looking at your main account and this, indirectly can cause reputation loss/gain, aka the meta effect.


text:
Q: Managing state in a reactive pipeline I am constructing a reactive pipeline that needs to expand (SelectMany) and then flatten (in this case, ToArray) whilst maintaining access to a piece of state obtained at the beginning of the pipeline.
Here is pseudo-code for what I am attempting:
return Observable
    .Start(() => this.GetSearchResults(query))
    .SelectMany(results => results.Hits)     // results.Hits is a list of IDs. But there is also has a bool property that I want to keep through to the end of my pipeline
    .SelectMany(hit => GetById(hit.Id))      // asynchronously load each result
    .ToArray()                               // now need to pull all the results together into a containing data structure, and also include the bool flag from above in it
    .Select(resolvedResults => new ...);     // need access to both resolvedResults and the bool mentioned in the first comment above

So I'm trying to find a way to cleanly access some state determined at the beginning of the pipeline from the code at the end of the pipeline.
The first thing I tried was using anonymous types to bundle the bool with each result. This quickly got out of hand and was wasteful from a performance perspective.
The second thing I tried was using a subject as follows:
var state = new AsyncSubject<bool>();
return Observable
    .Start(() => this.GetSearchResults(query))
    .Do(results =>
        {
            state.OnNext(results.Flag);
            state.OnCompleted();
        }
    .SelectMany(results => results.Hits)
    .SelectMany(hit => GetById(hit.Id))
    .ToArray()
    .Zip(
        state,
        (results, state) => new ResultContainer(state, results));

This seems to work fine, but feels a little icky to me.
So what I'm wondering is whether there is a cleaner way to manage state in a reactive pipeline.
For reference, here is the actual code (rather than just pseudo-code):
public IObservable<ISearchResults<IContact>> Search(string query, int maximumResultCount = 100, float minimumScore = 0.1F)
{
    Ensure.ArgumentNotNull(query, nameof(query));

    var moreHitsAvailable = new AsyncSubject<bool>();

    return Observable
        .Start(
            () => this.searchIndexService.Search<IContact>(query, maximumResultCount, minimumScore),
            this.schedulerService.DataStoreScheduler)
        .Do(
            results =>
            {
                moreHitsAvailable.OnNext(results.MoreHitsAreAvailable);
                moreHitsAvailable.OnCompleted();
            })
        .SelectMany(
            results => results
                .Hits
                .Select(
                    hit => new
                    {
                        Id = hit.Id,
                        ParsedId = ContactId.Parse(hit.Id)
                    }))
        .SelectMany(
            result => this
                .GetById(result.ParsedId)
                .Select(
                    contact => new
                    {
                        Id = result.Id,
                        Contact = contact
                    }))
        .Do(
            result =>
            {
                if (result.Contact == null)
                {
                    this.logger.Warn("Failed to find contact with ID '{0}' provided by the search index. Index may be out of date.", result.Id);
                }
            })
        .Select(result => result.Contact)
        .Where(contact => contact != null)
        .ToArray()
        .Zip(
            moreHitsAvailable,
            (results, more) => new SearchResults<IContact>(more, results.ToImmutableList()))
        .PublishLast()
        .ConnectUntilCompleted();
}

A: You could pop out to Query Comprehension Syntax and do something like this
var x = from result in Observable.Start(() => this.GetSearchResults())
    let hasMore = result.MoreHitsAreAvailable
    from hit in result.Hits
    from contact in GetById(hit.Id)
    select new { hasMore , contact};

Over to you how to deal with the duplicate hasMore values. As we know it will be just the single distinct value (all true or all false) you could group by.


text:
Q: CRM 2015 Microsoft app xpathevaluator' is undefined We are using crm 2015 and it is working without a problem.
All code is executed correctly in IE and in Chrome.
But when we try to use the crm app from Microsoft we get the error: 'xpathevaluator' is undefined.
I think it is the xrmservicetoolkit that is throwing the error.
    if (typeof (node.selectSingleNode) != "undefined") {
        return node.selectSingleNode(xpathExpr);
    } else {
        var xpe = new XPathEvaluator();
        var xPathNode = xpe.evaluate(xpathExpr, node, _NSResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
        return (xPathNode != null) ? xPathNode.singleNodeValue : null;
    }


text:
Q: SharePoint 2013 - Render Page in iFrame without Navigation Elements? I'm in a SP environment that is tightly controlled and for instance don't have access to Designer.
I'm attempting to setup a page to have the user select contents from buttons, which will then load those 'content' pages into an iFrame.  I have a test case setup and working.  However, when I click a button and a page loads within the iFrame it brings with it the global navigation and left menu bar.  I've tried:
1) Appending ?Dlg=1 to the URLs.  No change.
2) Applying following code to the
<style type="text/css">

    #s4-ribbonrow, .ms-cui-topBar2, .s4-notdlg, .s4-pr s4-ribbonrowhidetitle, .s4-notdlg noindex, #ms-cui-ribbonTopBars, #s4-titlerow, #s4-pr s4-notdlg s4-titlerowhidetitle, #s4-leftpanel-content {display:none !important;}

    .s4-ca{margin-left:0px !important; margin-right:0px !important;}

</style>

3) Applying following code through CWEP, but SP keeps overwriting it.
<style>
.ms-core-navigation { DISPLAY: none }
#contentBox { margin-left: 0px }
</style>

Any help would be appreciated!

A: Your #1 should work but you have to use the correct querystring.
Instead of ?Dlg=1 it should be ?isDlg=1.

A: ?Dlg=1 is wrong.
You must use ?isDlg=1.

A: First Add script editor web part and then add style in script editor.


text:
Q: How to bind items in a ListView Adapter to a Service? I'm writing a radio application, in which the user will be able to download some shows.
When the user click on a download button on the audio player, the show is added to the DB as a SavedShow.
The user can see the state of the SavedShow instances in a SavedShowsFragment, which shows a ListView with the list of the saved shows.
In each row of the ListView is the title of the saved show, its state (NOT_STARTED/DOWNLOADING/PAUSED/DOWNLOADED/ERROR), a ProgressBar and a Button to pause the download, resume it or play the file if it's downloaded.
Now I don't know how to bind each item of the list to my DownloadService nor how to implement listeners from DownloadService in the adapter.
Basically, I would like for each row to:

*

*get the progress from the DownloadTask.onProgressUpdate of my DownloadService

*be notified by the DownloadService when a download is finished or if there is an error

*call methods from DownloadService (e.g. pause the download when clicking the button if the file is downloading)

Anybody could help?
SavedShowsFragment
public class SavedShowsFragment extends Fragment {

    private DownloadService mDownloadService;
    private boolean mBoundToDownloadService = false;

    private ListView mListView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.saved_show_list, container, false);
    }

    @Override
    public void onActivityCreated (Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
    }

    private void setSavedShowList(){

        mListView = (ListView) getView().findViewById(R.id.listview);

        SavedShowAdapter adapter = new SavedShowAdapter(getActivity(), MyApplication.dbHelper.getSavedShowList());
        mListView.setAdapter(adapter);
    }

    @Override
    public void onCreate (Bundle savedInstanceState){

        super.onCreate(savedInstanceState);

        // start services

        Intent intent = new Intent(getActivity(), DownloadService.class);
        getActivity().startService(intent);
    }

    @Override
    public void onResume() {
        super.onResume();

        setSavedShowList();

        // bind service

        Intent intent = new Intent(getActivity(), StreamService.class);
        getActivity().bindService(intent, mDownloadServiceConnection, Context.BIND_AUTO_CREATE);

    }

    @Override
    public void onPause() {

        // unbind service

        if (mBoundToDownloadService) {
            getActivity().unbindService(mDownloadServiceConnection);
        }

        super.onPause();
    }

    private ServiceConnection mDownloadServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {

            /*
             * Get service instance
             */

            DownloadServiceBinder binder = (DownloadServiceBinder) service;
            mDownloadService = binder.getService();
            mBoundToDownloadService = true;

            /*
             * Start download for NOT_STARTED saved show
             */

            for(SavedShow savedShow : MyRadioApplication.dbHelper.getSavedShowList()){

                if(savedShow.getState()==SavedShow.State.NOT_STARTED){
                    mDownloadService.downLoadFile(savedShow.getId());
                }
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBoundToDownloadService = false;
        }
    };

}

SavedShowAdapter
public class SavedShowAdapter extends ArrayAdapter<SavedShow> {

    private LayoutInflater mLayoutInflater;

    static class ViewHolder {
        TextView title, status;
        ProgressBar progressBar;
        Button downloadStateBtn;
    }

    public SavedShowAdapter(Context context, List<SavedShow> saved_show_list) {
        super(context, 0, saved_show_list);
        mLayoutInflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        ViewHolder holder;
        View v = convertView;

        if (v == null) {

            v = mLayoutInflater.inflate(R.layout.podcast_list_item, parent, false);

            holder = new ViewHolder();

            holder.title = (TextView)v.findViewById(R.id.title);
            holder.status = (TextView)v.findViewById(R.id.status);
            holder.progressBar = (ProgressBar)v.findViewById(R.id.progress_bar);
            holder.downloadStateBtn = (Button)v.findViewById(R.id.btn_download_state);

            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }

        holder.downloadStateBtn.setTag(position);

        // TODO set button state according to item state

        holder.downloadStateBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                int position = (Integer) v.getTag();

                    // TODO call DownloadService method (download or pause) according to the state
            }
        });

        //holder.title.setText(getItem(position).getTitle());

        // do a publish progress listener for progress bar

        return v;
    }
}

DownloadService
public class DownloadService extends Service {

    private static final int MAX_DOWNLOAD_TASKS = 10;

    private final IBinder mBinder = new DownloadServiceBinder();

    private class MaxDownloadsException extends Exception
    {

        private static final long serialVersionUID = 6859017750734917253L;

        public MaxDownloadsException()
        {
            super(getResources().getString(R.string.max_downloads));
        }
    }

    private List<DownloadTask> mTaskList= new ArrayList<DownloadTask>();

    private void addTaskToList(DownloadTask task) throws MaxDownloadsException {

        if(mTaskList.size() < MAX_DOWNLOAD_TASKS+1){
            mTaskList.add(task);
        }
        else{
            throw new MaxDownloadsException();
        }
    }

    private void removeTaskToList(DownloadTask task) {

        mTaskList.remove(task);

        // if no more tasks, stop service

        if(mTaskList.size() == 0){
            stopSelf();
        }

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return START_NOT_STICKY;
    }

    /*
     * Binding-related methods
     */

    public class DownloadServiceBinder extends Binder {
        DownloadService getService() {
            return DownloadService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public void downLoadFile(long savedShowId){

        new DownloadTask().execute(savedShowId);

    }

    private class DownloadTask extends AsyncTask<Long, Integer, Void> {

        private SavedShow savedShow;

        private int contentLength;

        @Override
        protected Void doInBackground(Long... params) {

            savedShow = MyApplication.dbHelper.getSavedShow(params[0]);

            int contentLength;

            HttpURLConnection connection = null;
            BufferedInputStream in = null;

            try {

                URL url = new URL(savedShow.getUrl());

                connection = (HttpURLConnection) url.openConnection();

                long fileLength = new File(getFilesDir(), savedShow.getFilename()).length();

                FileOutputStream outputStream = openFileOutput(savedShow.getFilename(), MODE_PRIVATE | MODE_APPEND);

                int downloaded = 0;
                contentLength = connection.getContentLength();

                // If there is already a file with that filename,
                // add 'Range' property in header

                if(fileLength != 0){
                    connection.setRequestProperty("Range", "bytes=" + fileLength + "-");
                }

                in = new BufferedInputStream(connection.getInputStream());

                //BufferedOutputStream out = new BufferedOutputStream(outputStream, 1024);

                byte[] data = new byte[1024];
                int x = 0;

                while ((x = in.read(data, 0, 1024)) >= 0) {
                    outputStream.write(data, 0, x);
                    downloaded += x;
                    publishProgress((int) (downloaded));
                }
            } catch (IOException e) {
                MyApplication.dbHelper.updateSavedShowError(savedShow.getId(), e.toString());

            }
            finally{
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(connection != null){
                    connection.disconnect();
                }
            }
            return null;

        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);

            // How can I pass values to SavedShowAdapter's items?
        }

        @Override
        protected void onPostExecute(Void nothing) {
            super.onPostExecute(nothing);

            // TODO remove task

            // How can I notify SavedShowAdapter's items?
        }
    }
}

A: Here's what I did:

*

*to call DownloadService methods from the SavedShowAdapter, I passed the Service bound to the SavedShowFragment to the SavedShowAdapter.

*to get DownloadService listeners in the Adapter, I set some BroadcastReceiver in the SavedShowFragment, which then call SavedShowAdapter's method that modify the data and call notifyDataSetChanged().

A: I see you're already binding to the service. You can inherit the default binder, and implement any methods you like on it, or create a messenger and send messages back and fourth. Both methods are explored in the API Guides, be sure to read through it and fully understand the advantages and disadvantages of each method:
http://developer.android.com/guide/components/bound-services.html


text:
Q: LazyLoading AngularJs module with css file fails with Awesomium web view I try to lazy load an AngularJs module with ocLazyLoad. It all works fine until I add a css file, then the AngularJs application does not work. Here the code that works for any browsers and also CEF but not for Awesomium:
(you can easily test with the Awesomium Tabbed Browser Example)
index.html:
<!DOCTYPE html>

    <title></title>

testApp.js:
(function () {
    'use strict';
    angular.module("testApp", []).directive("sayHello", function () {
        return {
            scope: {
                to: '@to'
            },
            restrict: "E",
            template: '
Hello {{to}}</>'
        };
    });
})();

testApp.css:
body{color: red;}

Is this a problem of Awesomium or ocLazyLoad? Is there a work-around?
EDIT:
Very interesstingly if you test with the WPF example the CSS is not applied at all, in the WinForms example it is. But for both the AngularJs directive does not work.

A: The problem is most certenly with awesomium. It's using the chromium version 18, and a current version is 40. I am having the same problem with it too. I've tried CEF, but the problem with cef is that i get poor performance with it. Next i tried with GeckoFx, but any version from bitbucket that i tried just plain didn't compile...


text:
Q: Change File name , Got weird result I have massive folder full of random images name  so i want to Rename all file according to number from 1 to ... inf
however , its got to weird result in the middle of success

import os
from time import perf_counter , sleep
start = perf_counter()
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
print(BASE_DIR)
folder = input("Folder of Images:")
data = BASE_DIR+f"/{folder}"
images = os.listdir(data)
counter = 0
for i in images:
    counter += 1
    checker = i.split(".")
    try:
        done = os.rename(data+f"/{i}",data+f"/{counter}.{checker[1]}")
        print(f"Images {i} converted")
        sleep(0.1)
    except:
        print(f"{i} is not converted")
print(f"Finish at {perf_counter()}")

You may see i put sleep(0.1) because i thought Maybe the process so fast that the number were messed up , but still does not get the expected result  More weird , there is IE file at file 175

A: Unfortunately , the problem is cause by File type Change the script to check the file type firstand than change images that have png or jpg (since both are very popular )


text:
Q: Find a finite Gröbner basis for ideal $I \subseteq \mathbb{R}[x, y, z]$ Find a finite Gröbner basis in lexicographic ordering $x \prec  y \prec z$ for ideal $I \subseteq \mathbb{R}[x, y, z]$, where
$$ I = \{ f \in \mathbb{R}[x, y, z] \space | \space f(a, -a, 2) = 0 \space \forall \space a \in \mathbb{R} \} $$

I only know how to apply Buchberger's algorithm to determined ideals, for example such as $(xy + 2yz, x-y, yz-y)$. But how to find the basis in my case?

A: You have to find the generators $f_i$ of $I = (f_1, \ldots, f_n)$.
Wlog $f_1=z-2 \in I$, so you can remove all the occurrences of $z$ in the other generators. So you can consider all the $f_i, i > 1$ as polynomials in $x,y$.
Wlog $f_2=x+y \in I$. Are there other "useful" generators or $I = (f_1, f_2)$? Consider $f \in I$ and the monomial order $z>y>x$: the remainder of the division algorithm is a $g(x)$ such that $g(a) = 0 \ \forall a \in \mathbb{R}$. So $g=0$ and $f \in (f_1,f_2)$.


text:
Q: Linq to objects multiple statements vs. single statement In Linq to objects is there any difference in the execution between this code:
var changedFileIDs = updatedFiles.Where(file => file.CurrentVersion != file.OriginalVersion).Select(file => file.ID);
var changedVaultFiles = filesToUpdate.Where(x => changedFileIDs.Contains(x.ID));
foreach (var file in changedVaultFiles)
{
    Vault.Upload(file);
}

and this code?
var changedVaultFiles = filesToUpdate.Where(x => updatedFiles.Where(file => file.CurrentVersion != file.OriginalVersion).Select(file => file.ID).Contains(x.ID));
foreach (var file in changedVaultFiles)
{
    Vault.Upload(file);
}

A: No, there is no difference in performance, because one of the features of Linq is deferred execution, in other words, your query is not going to be executed until the query variable is iterated over in a foreach or for, or calling ToList or ToArray extension method. So in your first example your are composing your main query but is not going to be executed until you iterate over it.
You will find in this link more details about how query execution works in LINQ.
Summary of Deferred Execution:

After a LINQ query is created by a user, it is converted to an command
  tree. A command tree is a representation of a query.The command tree
  is then executed against the data source when the query variable is
  iterated over, not when the query variable is created. At query
  execution time, all query expressions (that is, all components of the
  query) are evaluated, including those expressions that are used in
  result materialization.


text:
Q: Fatal error: Call to a member function count() on a non-object I am learning PHP OOP by utilizing a PHP Academy tutorial. The tutorial is a Registration/Login system. I am having trouble on the "Remember Me" portion of the tutorial. This part of the tutorial retains a users selection to be able to stay logged in.
I am having an error:
"Fatal error: Call to a member function count() on a non-object in C:\xampp\htdocs\Rikarsen.hol.es\core\init.php on line 32
I have placed the PHP classes below to show what I have done thus far. Since I am new to PHP coding I am unable to locate the problem. Can anyone please help me? If any additional code is needed please let me know so I can supply it to you in order to help you discover my problem.
init.php
<?php
session_start();

$GLOBALS ['config'] = array(
    'mysql' => array(
        'host' => '127.0.0.1',
        'username' => 'root',
        'password' => '',
        'db' => 'rikars'
    ),
    'remember' => array(
        'cookie_name' => 'hash',
        'cookie_expiry' => 604800
    ),
    'session' => array(
        'session_name' => 'user',
        'token_name' => 'token'
    )
);

spl_autoload_register(function($class) {
    require_once 'classes/' . $class . '.php';
});

require_once 'functions/sanitize.php';

if(Cookie::exists(Config::get('remember/cookie_name')) && Session::exists(Config::get('session/session_name'))) {
    $hash = Cookie::get(Config::get('remember/cookie_name'));
    $hashCheck = DB::getInstance()->get('users_sessions', array('hash', '=', $hash));

    if($hashCheck->count()) {
        echo 'asass';
    }
}

I think I made a mistake in DB.php
<?php
class DB {
    private static $_instance = null;
    private $_pdo,
            $_query,
            $_error = false,
            $_result,
            $_count = 0;

    private function __construct() {
        try {
            $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
        } catch(PDOException $e) {
            die($e->getMessage());
        }
    }

    public static function getInstance() {
        if(!isset(self::$_instance)) {
            self::$_instance = new DB();
        }

        return self::$_instance;
    }

    public function query($sql, $params = array()) {
        $this->_error = false;
        if($this->_query = $this->_pdo->prepare($sql)) {
            $x = 1;
            if(count($params)){
                foreach($params as $param){
                    $this->_query->bindValue($x, $param);
                    $x++;
                }
            }
            if($this->_query->execute()){
                $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
                $this->_count = $this->_query->rowCount();
            } else {
                $this->_error = true;
            }
        }

        return $this;
    }

    public function action($action, $table, $where = array()) {
        if(count($where) === 3) {
            $operators = array('=', '>', '<', '>=', '<=');

            $field      = $where[0];
            $operator   = $where[1];
            $value      = $where[2];

            if(in_array($operator, $operators)) {
                $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";

                if(!$this->query($sql, array($value))->error()) {
                    return $this;
                }
            }
        }

        return false;
    }

    public function get($table, $where) {
        return $this->action('SELECT *', $table, $where);
    }

    public function delete($table, $where) {
        return $this->action('DELETE *', $table, $where);
    }

    public function insert($table, $fields = array()) {
        $keys = array_keys($fields);
        $values = null;
        $x = 1;

        foreach($fields as $field) {
            $values .= '?';
            if($x < count($fields)) {
                $values .= ', ';
            }
            $x++;
        }

        $sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";

        if(!$this->query($sql, $fields)->error()) {
            return true;
        }

        return false;
    }

    public function update($table, $id, $fields) {
        $set = '';
        $x= 1;

        foreach ($fields as $name => $value) {
            $set .= "{$name} = ?";
            if($x < count($fields)) {
                $set .= ', ';
            }
            $x++;
        }

        $sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";

        if($this->query($sql, $fields)->error()) {
            return true;
        }

        return false;
    }

    public function results() {
        return $this->_results;
    }

    public function first() {
        return $this->results()[0];
    }

    public function error() {
        return $this->_error;
    }

    public function count() {
        return $this->_count;
    }
    public function ins() {
        $instance = DB::getInstance();
        $instance->get('users',array('user_id','=','1'));
        if (!$instance->Count()) {
            echo 'No user';
        } else {
            echo 'User exists';
        }
    }
}
?>

A: Your method action return false but you expect object.
if(Cookie::exists(Config::get('remember/cookie_name')) && Session::exists(Config::get('session/session_name'))) {
    $hash = Cookie::get(Config::get('remember/cookie_name'));
    $hashCheck = DB::getInstance()->get('users_sessions', array('hash', '=', $hash));

    if($hashCheck === false) {
        echo 'Action return false';
    } else {
        $count = $hashCheck->count();
        if($count) {
            echo 'Its object and count ='.$count;
        }
    }
}

A: Make sure your table name and column names are correct in get method. I was having the same problem and this was the solution that worked for me.


text:
Q: Unable to remove interceptors using nock I am using nock and I'm trying to remove interceptors for certain hostname.
I have tried using:
nock.removeInterceptor({
      hostname: 'somehostname.com',
      proto: 'https',
      path: '/',
    }),

When I print the result of this, it actually gives me true
I have also tried:
const mock = nock(somehostname.com)
    .persist()
    .post('/endpoint')
    .reply(200);

nock.removeInterceptor(mock)

But this gives me false somehow.
The way I'm checking if this is working is by printing the activeMocks:
nock.activeMocks()
And it still has the interceptors that I'm trying to remove.
Does anyone know what happens?

A: I'd got the same problem and I solved like this:
const mock = nock(somehostname.com)
    .persist()
    .post('/endpoint')
    .reply(200);

nock.removeInterceptor(mock.interceptors[0])

mock.interceptors is a array of all Interceptor object registered for this scope, so I get the most recently created scope and remove it from nock.

A: It appears that nock uses singletons underneath and that calling nock("my/base-route/i/already/mocked") returns the scope which can then be used to query the interceptor again by using scope.get("my/endpoint/I/already/mocked"), which returns the interceptor. This interceptor can then be removed using nock.removeInterceptor(interceptor) which should return true.
So in total:
function mockRoute() {
    nock("my/base-route/i/already/mocked")
    .get("my/endpoint/I/already/mocked")
    .reply("Something")
}

function removeExistingMock(): boolean {
    const scope = nock("my/base-route/i/already/mocked")
    const interceptor = scope.get("my/endpoint/I/already/mocked")
    return nock.removeInterceptor(interceptor)
}

A: This worked for me:
nock.removeInterceptor({
  proto: 'https',
  hostname: 'www.somehostname.com',
  path: `/somepath`,
})

It did take a bit of trial and error and looking at the code to get the right options. It looks pretty similar to your code, so the only possible differences I can see are that subdomain and full path are included.
Note that removing the interceptors doesn't remove the mock itself. That is, requests will fail rather than be allowed through to the actual url.
I found the boolean return value unhelpful. It can return true even when no interceptors were removed. I created an issue for that.


text:
Q: Stripe coupon not reflected in charge or saved in database for rails 4 app We've gotten Stripe working for subscriptions payments in our rails 4 app using the Mastering Modern Payments approach. We're now trying to add coupons. We want to use Stripe to manage the coupons (create the coupons in the Stripe dashboard).
The problem is that when the user pays, the coupon is not reducing the amount charged, and is not getting saved into the app database with the user and subscription information. We are not getting any errors.
What is working: We see the coupon code in the hash when the user pays, and the coupon is set up in Stripe. Overall the user can sign up and pay fine. We do a two step create user in Devise then have them pay. When they pay their subscription flips to active in our app.
We know there is a missing piece here for coupons to work, but we are trying to figure out what that is and how should it be implemented? I read about creating a virtual attribute in rails, so perhaps we could do that for coupons, since there is not currently any coupon information in the Users table.
The output looks like this when user signs up for subscription (actual data replaced for posting):
... Started POST "/subscriptions" for 127.0.0.1 at 2015-11-30 10:33:40 -0800
Processing by SubscriptionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"XYZ", "plan_id"=>"5", "email_address"=>"test55@gmail.com", "coupon"=>"123", "stripeToken"=>"tok_xyz"}
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 52]]
  Plan Load (0.3ms)  SELECT  "plans".* FROM "plans" WHERE "plans"."id" = $1 LIMIT 1  [["id", 5]]
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = $1 LIMIT 1  [["email", "test55@gmail.com"]]
   (0.3ms)  BEGIN
  SQL (0.4ms)  UPDATE "users" SET "stripe_customer_id" = $1, "updated_at" = $2 WHERE "users"."id" = $3  [["stripe_customer_id", "cus_7Rq9Kv4nGh6uD2"], ["updated_at", "2015-11-30 18:33:41.930863"], ["id", 52]]
  SQL (48.6ms)  INSERT INTO "subscriptions" ("plan_id", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["plan_id", 5], ["user_id", 52], ["created_at", "2015-11-30 18:33:41.934364"], ["updated_at", "2015-11-30 18:33:41.934364"]]
DEPRECATION WARNING: `serialized_attributes` is deprecated without replacement, and will be removed in Rails 5.0. (called from serialized_attributes at /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/attribute_methods/serialization.rb:56)...

Schema for Users and Subscriptions (coupons is a column in subscriptions table):
schema.rb:
...
 create_table "subscriptions", force: :cascade do |t|
    t.date     "purchase_date"
    t.boolean  "active"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
    t.integer  "user_id"
    t.integer  "plan_id"
    t.string   "stripe_id"
    t.string   "coupon"
  end

  add_index "subscriptions", ["plan_id"], name: "index_subscriptions_on_plan_id", using: :btree
  add_index "subscriptions", ["user_id"], name: "index_subscriptions_on_user_id", using: :btree

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "",    null: false
    t.string   "encrypted_password",     default: ""
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,     null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "name"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email"
    t.integer  "role"
    t.string   "invitation_token"
    t.datetime "invitation_created_at"
    t.datetime "invitation_sent_at"
    t.datetime "invitation_accepted_at"
    t.integer  "invitation_limit"
    t.integer  "invited_by_id"
    t.string   "invited_by_type"
    t.integer  "invitations_count",      default: 0
    t.boolean  "terms_accepted",         default: false
    t.string   "phone_number"
    t.string   "plan_id"
    t.string   "employer"
    t.string   "stripe_customer_id"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
  add_index "users", ["invitation_token"], name: "index_users_on_invitation_token", unique: true, using: :btree
  add_index "users", ["invitations_count"], name: "index_users_on_invitations_count", using: :btree
  add_index "users", ["invited_by_id"], name: "index_users_on_invited_by_id", using: :btree
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
...

Coupon is in the Create Subscription service object:
create_subscription.rb
class CreateSubscription
  def self.call(plan, email_address, token)
    user, raw_token = CreateUser.call(email_address)

    subscription = Subscription.new(
        plan: plan,
        user: user
    )

    begin
      stripe_sub = nil
      if user.stripe_customer_id.blank?
        customer = Stripe::Customer.create(
            source: token,
            email: user.email,
            plan: plan.stripe_id,
            coupon: subscription.coupon,
        )
        user.stripe_customer_id = customer.id
        user.save!
        stripe_sub = customer.subscriptions.first
      else
        customer = Stripe::Customer.retrieve(user.stripe_customer_id)
        stripe_sub = customer.subscriptions.create(
            plan: plan.stripe_id
        )
      end

      subscription.stripe_id = stripe_sub.id

      subscription.save!
    rescue Stripe::StripeError => e
      subscription.errors[:base] << e.message
    end

    subscription
  end
end

Coupon is on the pay page:
app/views/subscriptions/new.html.haml
= content_for :header do
    %script{src: 'https://js.stripe.com/v2/', type: 'text/javascript'}

    :javascript
        $(function(){
            Stripe.setPublishableKey("#{Rails.configuration.stripe[:publishable_key]}");
        });

    %script{src: '/subscriptions.js', type: 'text/javascript'}

- unless @subscription.errors.blank?
    = @subscription.errors.full_messages.to_sentence
%h2
    Subscribing to #{@plan.name}
= form_for @subscription, html: { id: 'payment-form' } do |f|
    %input{name: 'plan_id', type: 'hidden', value: @plan.id}/
    %span.payment-errors
    .form-row
        %label
            %span Email Address
            %input{name: 'email_address', size: '20', type: 'email', value: @user.email}
    .form-row
        %label
            %span Card Number
            %input{size: '20', type: 'text', data: {stripe: 'number'}}
    .form-row
        %label
            %span CVC
            %input{size: '4', type: 'text', data: {stripe: 'cvc'}}
    .form-row
        %label
            %span Expiration (MM/YYYY)
            %input{size: '2', type: 'text', data: {stripe: 'exp-month'}}
        %span /
        %input{size: '4', type: 'text', data: {stripe: 'exp-year'}}
    .form-row
        %label
            %span Promo code, if any
            %input{name: 'coupon', size: '20', type: 'text', value: @coupon}
    %button{type: 'submit', class: 'btn btn-lg btn-primary'} Pay Now

And our subscription model looks like this:
subscription.rb:
    class Subscription < ActiveRecord::Base
      belongs_to :user
      belongs_to :plan

      has_paper_trail

      def inactive?
        active ? false : true
      end

  def active?
    active
  end
end

How do we get Stripe coupon reflected in the charge and saved in our app database? Thank you.

A: Your CreateSubscription service doesn't provide a way for you to pass your coupon code.
You'll need to add a new parameter for that eg.
class CreateSubscription
  def self.call(plan, email_address, token, coupon = nil)
    # ...
    subscription = Subscription.new(
      plan: plan,
      user: user,
      coupon: coupon
    )
    # ...
  end
end

Also, there are a couple other things to be aware of with the code you've provided:
customer = Stripe::Customer.create(
  source: token,
  email: user.email,
  plan: plan.stripe_id,
  coupon: subscription.coupon
)

Stipe allows you to set coupon on both Customers and Subscriptions. When billing, a discount applied to a subscription overrides a discount applied on a customer-wide basis. See https://stripe.com/docs/api#subscription_object
So if your customer cancels their subscription, or has other (multiple) subscriptions. They'd potentially be getting their discount applied to those as well, depending on the settings of your coupon.
So depending on what you want to have happen, you may only want to pass the coupon to the Stripe::Subscription instead of to the Stripe::Customer.


text:
Q: CSS - right align block with edge of viewport, but with a limit I have a header bar with a coloured background and some right-aligned menu items inside. The header bar should stretch the full width of the viewport, with a minimum width to avoid shrinking to below the (fixed) width of the main body of the site. The menu items inside should remain right aligned with the main body of the site even when the header bar extends wider. So far so easy: http://jsfiddle.net/symposion/fgrGD/

    Some item

.headerBar {
  margin-top:30px;
  background-color:black;
  color:white;
  min-width:400px;
  padding-top:10px;
  padding-bottom:10px;
}

.headerMenu {
  text-align:right;
  max-width:400px;
  margin-left:auto;
  margin-right:auto;
}

.mainContent {
  width:400px;
  margin-left:auto;
  margin-right:auto;
  background-color:blue;
  height:100px;
}

Where it gets complicated is that I'd also like the menu to move left (while still remaining right aligned to the edge of the screen) when the browser is resized smaller than the minimum width of the main site, to make best use of the remaining space. The naive way of doing this is to remove the min-width from the header bar, but this obviously means that you end up with a nasty blank gap when you scroll over to the right.
Constraints:

*

*I can't make the header a fixed height, it needs to expand and contract based on its content

*No JS

*Ideally I'd like to avoid lots of redundant markup in the header; I can live with a little if it's the only way.

*Needs to work in IE8+, Firefox, Chrome, Safari, iOS

Any ideas?

A: You need to use something called a media query.

A media query is a logical expression that is either true or false. A
  media query is true if the media type of the media query matches the
  media type of the device where the user agent is running (as defined
  in the "Applies to" line), and all expressions in the media query are
  true.

example:
@media screen and (max-width: 765px) {
    ...styles...
}

jsFiddle: http://jsfiddle.net/uRaMS/
source: http://www.w3.org/TR/css3-mediaqueries/


text:
Q: Point selection criterion in `Method->RandomSearch` In NonlinearModelFit one can specify Method->{"NMinimize", Method->"RandomSearch"} while giving a guess for the fit parameters not as a range like {param, pstart, pend} but rather {parap, pguess}. In this last case how does mathematica select the random starting points upon which to run FindMinimum?
Does in the range case it just throw random numbers in that range of values?


text:
Q: Store files into DB (Newbie) I start to develop a web app (asp.net) that will store every kind of document in a DB.
It's a SQL 2008 DB, and I'm analizing what is the best way to store "metadata" in a DB solution?
A few type:
 - file system pointer in protected folder, for me is too complex and insicure
 - filestream
 - varbinary(max) column
 - others?
any suggestion? Someone with a similar dilemma?
Thanks all.

A: Why is it too complex or insecure? It's best to store a filename on the database and access the files themselves from the filesystem. You can use NTFS permissions to secure the locations of the files so that only the account under which your ASP.NET application (pool) is running can get to them. This is especially true for large files.

A: I would check out SQL Server 2008's FILESTREAM attribute on a varbinary column. I haven't used it personally, but it's the first thing I would check out.
I asked a similar question. I'd also check out the great answers people gave there.

A: I tend to stay away from keeping the files in the file system and only storing the metadata in the database. I prefer to keep the files in the database as it greatly simplifies any backup/recovery strategy. The only exception I have to this is if you know you're going to be storing files across multiple devices, which tends to happen if you know you are going to have more images than you can reasonably store on a single logical drive.
Another suggestion I'll make, if you are storing the files in the database, is to store the contents of the file in its own table (i.e. only have the contents and a PK). If you have a file in the table with the entity (say an avatar image in the user table), then if someone were to run a select * against the user table, then the files would be returned as well, which can be very costly if you are returning a large set of users.
I don't have much personal experience with filestream in SQL Server, so I can't speak to it very well, but I would think either that or varbianary(max) would probably be good choices.


text:
Q: After Effect : How can I easily remove "oily or/and shiny skin" with some effects? I have a video in this style:

I would like to know if there is an efficient way to remove that oily/shiny skin?

A: For info, I found the solution with that plug in (Digital Beauty Box) with the oily. Have to find how to use it to eliminate with more efficiency the shiny, but I think it will be okay => Tutorial


text:
Q: What happens when a battery discharges? Questions I am interested in:

*

*What determines the amount of current a battery can supply?

*What changes when a battery discharges - voltage, max current, or both?

*What is the best predictor of the remaining capacity of e.g. AA battery?

A: When a battery is in operation an electrochemical reaction known as a Redox reaction takes place. In it, an oxidiser $\text{O}$ is oxidised (loses electrons) and a reducing agent $\text{R}$ is reduced (gains electrons).
Simplified we can write:
$$\text{O}\to \text{O}^{n+}+n\text{ e}^-$$
$$\text{R} +n\text{ e}^-\to \text{R}^{n-}$$
Note that neutrality is maintained at all times.
By running the reaction with the oxidiser and reducing agent in separate 'compartments' the flow of electrons can be 'harvested' as current.
The voltage a battery (or better put, a cell) can deliver depends exclusively on the type of Redox reaction the cell employs. For example, a typical manganese oxide/zinc cell uses:
$$\text{Zn}+2\text{OH}^{-}\to \text{ZnO}+\text{H}_2\text{O}+2\text{ e}^-$$
$$2\text{MnO}_2 +\text{H}_2\text{O}+2\text{ e}^-\to \text{Mn}_2\text{O}_3+2\text{OH}^{-}$$
and delivers about $\text{1.43 }\mathrm{V}$.
Cells 'run out' when either the oxidiser or reducing agent has been depleted.

A: *

*The max current is the ratio of its voltage V to internal resistance R, as in I = V/R

*Its voltage remains approximately constant but follows a decay curve characteristic of the battery technology. Max current likewise.

*The remaining capacity is the total capacity (specified in Ampere hours) less the charge supplied to date, calculated as Amps x hours.


text:
Q: Firebase writes different files if app is debug or release version I just found out something very odd with Firebase and I would like to know if it is me that's doing something wrong or if there is a solution to this problem.
Basically, this is what it has always written when I was developing the app (and it's precisely what I was expecting):
nscoachtools@gmail¸com
    maxMatches: 60
    maxPlayers: 500
    maxTeams: 30
    userId: "SnMuRZEVqyN***...***hv2"
    userMail: "nscoachtools@gmail.com"
    userName: "Nicola Salvaro"
    userPicture: "https://lh4.googleusercontent.com/-L7lSPz0VJ9A/..."
    userToken: -1
and this is what it writes after I built the app in release mode:
nsalvaro77@gmail¸com
    a: "Nicola Salvaro"
    b: "ESjqwuh***...***wg1"
    c: "nsalvaro77@gmail.com"
    d: "https://lh4.googleusercontent.com/-2kwSEmLEN1c/..."
    e: -2
    f: 30
    g: 500
    h: 60
    userToken: 1499775285255
Every "title" has been replaced with a letter. And "e: " was supposed to be "userToken: " then, when I tried to update it, it wrote it with the proper string but not on top of the original value... just wrote a new one. Then, when I try to read the full user, it gets the value of "e: ", not the "userToken: " one.
Did I do something wrong?

A: In release mode your Android app is being minified by Proguard. This process strips unused methods and makes other method names shorter.
As a consequence, your POJO classes (the classes your read from/write to Firebase) are getting new method names and Firebase reflectively uses those method names to determine the properties in the JSON.
The solution is to tell Proguard to not modify the method names of your POJOs.
More on that:

*

*The oldest Q&A on how to do this is: What ProGuard configuration do I need for Firebase on Android?. But that one is from Firebase 2.x, while many of these are auto-included in Firebase 9 and up.

*You can also potentially mark the classes with @Keep, see Firebase No properties to serialize found on class.

*More interesting Q&A on this topic: https://stackoverflow.com/search?q=%5Bfirebase-database%5D+proguard+release


text:
Q: If $R\subseteq S$ is a split extension of Noetherian domains and $S$ is normal, then is $R$ normal? Let $R\subseteq S$ be a ring extension of Noetherian domains. $S$ naturally has an $R$-module structure. Assume $R$ is a direct summand of $S$ as an $R$-module.
If $S$ is integrally closed in its own field of fractions, then is $R$ also integrally closed in its own field of fractions?
I am willing to assume that $S$ is module finite over $R$.

A: Let $\frac{r_1}{r_2}\in\operatorname{Frac}R\subseteq \operatorname{Frac}S$ be integral over $R$. Then $\frac{r_1}{r_2}$ is integral over $S$ which is integrally closed, so there is an $s\in S$ such that
$$r_1=r_2s.$$
Now, if $R$ is a direct summand of $S$, i.e. $S\simeq R \oplus S'$, we may in a unique way write $s=r_3+s'$ with $r_3\in R, s'\notin R$. Thus,
$$r_1 = r_2r_3 +r_2s',$$
but then $s'=0$ since $r_1$ has the unique decomposition $r_1+0$ in $R\oplus S'$. Hence $r_1=r_2r_3$ and $\frac{r_1}{r_2}=r_3\in R$, so $R$ is integrally closed.


text:
Q: Javascript adding textarea size I have a form that has a textarea and includes a couple of buttons 1 will add an additional textarea and the other will remove a textarea 1 at a time unless it's the last one. It works except that I want the size of each textarea to be the same as the original one but I just can't seem to figure out what I'm doing wrong.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  <title>CPO Exit Form</title>

  <link rel="stylesheet" href = "Styles/Site2.css"></link>

   <fieldset><legend>Action Items:</legend>

       1 : <textarea style="width: 700px; height: 56px" max="255"></textarea>

  <input type='button' value='Add Button' id='addButton'>
  <input type='button' value='Remove Button' id='removeButton'>

A: Your change this sentence
newTextBoxDiv.after().html(''+ counter + ' : <textarea style"width: 700px; height: 56px" max="255"></textarea>')

After...
newTextBoxDiv.after().html(''+ counter + ' : <textarea style"width: 760px; height: 56px" rows="5" style="width: 764px">')

A: This is a tiny bug but you are missing an = after your style attribute in your JavaScript. (demo)
Change this:
newTextBoxDiv.after().html(''+ counter + ' : <textarea style"width: 700px; height: 56px" max="255"></textarea>');

To this:
newTextBoxDiv.after().html(''+ counter + ' : <textarea style="width: 700px; height: 56px" max="255"></textarea>');

An even cleaner approach is to use CSS to set the style of your <textarea> elements like so:
textarea.Wide {
  width: 700px;
  height: 56px
}

Then you can change your HTML (and JavaScript) to this:
<textarea class="Wide" max="255"></textarea>


text:
Q: Set content of particular Pivot Item I wrote a Windows Phone 8.1 (WINPRT) App.
It contains Pivot, in which pivot items are generated dynamically according to JSON.
For example, when I open Clothing Category Page,>> Summer Wear,Winter Wear etc pivot items are generated dynamically.
Now I am clicking the button to load more items in GridView (ObservableCollection) and it is shown on currently selected PivotItem.
(MainPagePivot.SelectedItem as PivotItem).Content = StatusGridObject;

How to add these items to some other pivot item and not the selected one.
example i am on pivotitem  having index 0, how to add data to pivot item having  index 4? Any linq query?? I dont want to use MainPagePivot.SelectedItem but some other pivot item

A: I think you can do something like this:
((PivotItem)MainPagePivot.Items[index]).Content = StatusGridObject;

Of course, thanks to linq you can also use something like .Where() or .Any() on MainPagePivot.Items
example with linq:
((PivotItem)MainPagePivot.Items.First(p => p.Name == "PivotItemFour")).Content = StatusGridObject;

Let me know if it works!


text:
Q: Right clicking a button inflates AppBar instead of firing right click event So I have a button in my AppBar that adds buttons to a stackpanel that is located in a grid on the page.
I assigned a RightTapped event to the new buttons.
However, when I right click a new button, instead of firing the method I assigned to the RightTapped event, the program inflates the AppBar.
I tried to set IsRightTapEnabled="False" one every item but the new buttons, but that didn't help the issue.
I'm stuck and I need help.
Here is my code behind:
public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }
    int index = 0;

    private void AppBarButton_Click(object sender, RoutedEventArgs e)
    {
        index++;
        string ButtonName = "Button" + index;
        Button dummyButton = new Button
        {
            Name = ButtonName,
            Content = ButtonName,
        };
        StackPanel1.Children.Add(dummyButton);
        dummyButton.RightTapped += new RightTappedEventHandler(DummyButton_RightTapped);
    }

    private void Button0_RightTapped(object sender, RightTappedRoutedEventArgs e)
    {
        MenuFlyout myFlyout = new MenuFlyout();
        MenuFlyoutItem firstItem = new MenuFlyoutItem { Text = "Right Clicked" };

        myFlyout.Items.Add(firstItem);
        myFlyout.ShowAt(sender as FrameworkElement);
    }

    private void DummyButton_RightTapped(object sender, RightTappedRoutedEventArgs e)
    {
        //var dialog = new MessageDialog("Right clicked");
        //await dialog.ShowAsync();

        MenuFlyout myFlyout = new MenuFlyout();
        MenuFlyoutItem firstItem = new MenuFlyoutItem { Text = "Right Clicked" };

        myFlyout.Items.Add(firstItem);
        myFlyout.ShowAt(sender as FrameworkElement);
    }
}

Here is my XAML code:
<Page
x:Class="Soundboard.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Soundboard"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
IsRightTapEnabled="False">

<Page.TopAppBar >
    <AppBar IsSticky="True" IsRightTapEnabled="False" >
        <StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
            <AppBarButton Label="Add Sound" Icon="OpenFile" Click="AppBarButton_Click" ></AppBarButton>
        </StackPanel>
    </AppBar>
</Page.TopAppBar>

<Grid Background="#FF004D40" Name="myGrid" IsRightTapEnabled="False">
    <Grid.RowDefinitions>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>
    <StackPanel Name="StackPanel1" Grid.Row="0" Orientation="Horizontal" IsRightTapEnabled="False">
        <Button Content="Button0" Name ="Button0" RightTapped="Button0_RightTapped"></Button>
    </StackPanel>
</Grid>

A: The official does not recommend using the AppBar in UWP. The following section references Official AppBar instructions.

You should use the AppBar only when you are upgrading a Universal Windows 8 app that uses the AppBar, and need to minimize changes. For new apps in Windows 10, we recommend using the CommandBar control instead.

Usage
Add CommandBar to <Page.TopAppBar> just like following code.
 <Page.TopAppBar>
        <CommandBar IsSticky="True">
            <AppBarButton
                Click="AppBarButton_Click"
                Icon="OpenFile"
                Label="Add Sound" />
        </CommandBar>
    </Page.TopAppBar>


text:
Q: Convert SphinxSearch query syntax to boolean search string in Ruby I've been pondering over what is the easiest way to convert the following Sphinx Search query into what is commonly used in typical web searches or portals, e.g. a boolean search string, and vice versa
(A | B) "C D" (E | "F G" | "H I J") ("K L" ("M N" | "O P")) Q R

Needs to be converted to
(A OR B) AND "C D" AND (E OR "F G" OR "H I J") AND ("K L" AND ("M N" OR "O P")) AND Q AND R

also slight variation for example purposes
(A | B) C D (E | "F G" | "H I J") ("K L" ("M N" | "O P")) Q R

should be
(A OR B) AND C AND D AND (E OR "F G" OR "H I J") AND ("K L" AND ("M N" OR "O P")) AND Q AND R

For clarity,
"A" can be any word and any case, its not case sensitive. Spaces denote AND in the starting syntax unless inside quotes. So AB would simply be one word e.g. Java. The space between (A|B) isnt important (A|B) is the same as ( A | B ) or (A | B) etc. Each letter denotes a word.
Some of these queries will be quite long - upto 500 terms. Although this isn't a huge overhead to process, I'm thinking what would be the BEST (most efficient) way to convert this. Tokenization, Regex/pattern matching, simple replace, recursion etc.  What would any of you recommend?

A: Readers are perhaps looking for an elegant, at least not hackish, solution to this problem. That was my objective as well, but, alas, this is the best I've been able to come up with.
Code
def convert(str)
  subs = []
  str.gsub(/"[^"]*"| *\| */) do |s|
    if s.match?(/ *\| */)
      '|'
    else
      subs << s
      '*'
    end
  end.gsub(/ +/, ' AND ').
      gsub(/[*|]/) { |s| s == '|' ? ' OR ' : subs.shift }
end

Examples
puts convert(%Q{(A | B) "C D" (E | "F G" | "H I J") ("K L" ("M N" | "O P")) Q R})
  #-> (A OR B) AND "C D" AND (E OR "F G" OR "H I J") AND ("K L" AND ("M N" OR "O P")) AND Q AND R

puts convert(%Q{(A|B)   C D (E| "F G" |"H I J") ("K L"   ("M N" | "O P")) Q R})
  #-> (A OR B) AND C AND D AND (E OR "F G" OR "H I J") AND ("K L" AND ("M N" OR "O P")) AND Q AND R

Notice that in this example there is no space before and/or after some pipes and in some places outside double-quoted strings there are  multiple spaces.
puts convert(%Q{(Ant | Bat) Cat Dog (Emu | "Frog Gorilla" | "Hen Ibex Jackel") ("Khawla Lynx" ("Magpie Newt" | "Ocelot Penguin")) Quail Rabbit})
  #-> (Ant OR Bat) AND Cat AND Dog AND (Emu OR "Frog Gorilla" OR "Hen Ibex Jackel") AND ("Khawla Lynx" AND ("Magpie Newt" OR "Ocelot Penguin")) AND Quail AND Rabbit

Here I've replaced the capital letters with words.
Explanation
To see how this works let
str = %Q{(A | B) "C D" (E | "F G" | "H I J") ("K L" ("M N" | "O P")) Q R}
  #=> "(A | B) \"C D\" (E | \"F G\" | \"H I J\") (\"K L\" (\"M N\" | \"O P\")) Q R"

then
subs = []
str.gsub(/"[^"]*"| *\| */) do |s|
  if s.match?(/ *\| */)
    '|'
  else
    subs << s
    '*'
  end
end
  #=> "(A|B) * (E|*|*) (* (*|*)) Q R"

  subs
    #=> ["\"C D\"", "\"F G\"", "\"H I J\"", "\"K L\"", "\"M N\"", "\"O P\""]

As you see, I have removed the spaces around pipes and replaced all quoted strings with asterisks, saving those strings in the array subs, so that I can later replace the asterisks with their original values. The choice of an asterisk is of course arbitrary.
The regular expression reads, "match a double-quoted string of zero or more characters or a pipe ('|') optionally preceded and/or followed by  spaces".
As a result of these substitutions, all remaining strings of spaces are to be replaced by ' AND ':
s2 = s1.gsub(' +', ' AND ')
  #=> "(A|B) AND * AND (E|*|*) AND (* AND (*|*)) AND Q AND R"

It remains to replace '|' with ' OR ' and each asterisk by its original value:
s2.gsub(/[*|]/) { |s| s == '|' ? ' OR ' : subs.shift }
  #=> "(A OR B) AND \"C D\" AND (E OR \"F G\" OR \"H I J\") AND (\"K L\" AND (\"M N\" OR \"O P\")) AND Q AND R"


text:
Q: Solve $\sum_{i=1}^n n*x^{2n}$ I know that $\sum_{i=0}^n n*x^n =  \frac{x}{(1-x)^2}$ but the factor of 2 in the exponential makes it a riemann zeta function? Can anyone shed some light on this?

A: Hint: Replace $x$ with $x^2$.

A: Note that, for a geometric series with ratio $r$,
$$\sum_{n=0}^\infty r^n = \frac{1}{1-r}$$
and the derivative is given by
$$\sum_{n=0}^\infty nr^{n-1} = \frac{1}{(1-r)^2}$$
and multiplication by $r$ gives
$$\sum_{n=0}^\infty nr^{n} = \frac{r}{(1-r)^2}$$
Let $r=x^2$. Then we have
$$\sum_{n=0}^\infty nx^{2n} = \frac{x^2}{(1-x^2)^2}$$
(Equivalently we can start the summation at $n=1$ since the summand for $n=0$ is $0$. Thus, we have your desired expression.)

Note that this is not the Riemann zeta function since it is defined by
$$\zeta(s) = \sum_{n=1}^\infty \frac{1}{n^s}$$
It's a rather different function; it's moreso a generalization of the idea behind harmonic series than it is of geometric series.

A: First of all the Riemann zeta function is
$$\zeta(s)=\sum_{n=1}^{\infty}\frac1{n^s}$$
And your sum is $$f(x)=\sum_{i=1}^{n}ix^{2i}$$
You already know that
$$\sum_{i=1}^nix^i=\frac{x}{(1-x)^2}$$
So just replace $x$ with $x^2$ to get
$$f(x)=\frac{x^2}{(1-x^2)^2}$$


text:
Q: VSTO splash screen excel startup Using VSTO to create a document level add-in for Excel 2013, I'm trying to create a splash screen to run at startup for a few seconds (and then close).
I added the Splash Screen to my Workbook in VSTO (Project->Add New Item) and I can see it in the designer.
But how do I show it every time Excel starts?
This is the code I'm using in ThisWorkbook.vb:
Public Class ThisWorkbook
    Dim splash As New SplashScreen1()
    Private Sub ThisWorkbook_Startup() Handles Me.Startup
        splash.Show()
    End Sub

    Private Sub ThisWorkbook_Shutdown() Handles Me.Shutdown

    End Sub

End Class

A: Please remember that you develop an add-in, not a standalone application. Splash screens typically are used for standalone applications only. You may consider developing a standalone application which may automate Excel and load your document. See How to automate Microsoft Excel from Visual Basic .NET to get started quickly. While the work is performed you can display a splash screen. And when the add-in is loaded (or file) you can close the application programmatically, Excel should be left running separately. Hope it makes sense.


text:
Q: Replace all single quotes in a string query I have a file with SQL queries similar to this:
INSERT INTO Bank (bankCode, swiftCode, bankName, country, countryCode, locationCode,
address, city)
VALUES ('MIDL', 'MIDLGB2102N', 'Hsbc Bank Plc', 'United Kingdom', 'GB',
'21', '', 'Bishop's Stortford');

I have to replace all single quotes inside a string literal in order to be able to execute the query.
Can someone provide a regular expression in order to achieve that?
For example the above query should be:
INSERT INTO Bank (bankCode, swiftCode, bankName, country, countryCode,
locationCode,
address, city)
VALUES ('MIDL', 'MIDLGB2102N', 'Hsbc Bank Plc', 'United Kingdom', 'GB',
'21', '', 'Bishop''s Stortford');

Replace 'Bishop's Stortford' with 'Bishop''s Stortford' . Replace ' with ''

A: You have PDO::quote function in PHP for this purpose. Check this link: http://php.net/manual/en/pdo.quote.php

If you want a pattrn for regex replace: /(\(|\s)'([\w ']*)'(,|\))/
Or in PHP: preg_replace("/(\(|\s)'([\w ']*)'(,|\))/", '$1"$2"$3', $line);

A: The easiest approach would likely be something akin to:
/[^,(]\s*'\s*[^,)]/
This would match all ' characters which are not preceded by or following a comma or a paren (only other valid MySQL characters). I included a search for spaces because those are also possible valid characters.
That would certainly match everything. I'm not terribly familiar with how MySQL Workbench parses replaces in regular expressions, so I cannot be much assistance there.

A: To import via MySQL Workbench do the following:

*

*Go to excel and have your data the way you need to reflect your table structure

*In excel Save As -> CSV

*In workbench right click on table and choose 'Select Rows'

*In result set, click icon 'Import Records from External File'

*Select your CSV

*Import