text:
Q: how to retrieve quarter and year values to date I am using the table below:

Period
County
Cost
product

01/11/2019
DE
1.54
Product1

01/11/2019
US
2.35
Product1

01/11/2019
DE
4.21
Product2

01/11/2019
US
0.87
Product2

01/12/2019
DE
1.456
Product1

01/01/2020
DE
5.3
Product2

01/02/2020
US
9.76
Product1

01/03/2020
DE
6.78
Product1

01/03/2020
US
1.2
Product2

01/03/2020
DE
3.964
Product2

01/04/2020
US
2.58
Product1

01/04/2020
US
2.8
Product2

01/04/2020
DE
0.5
Product1

Code to test:
    CREATE OR REPLACE TEMPORARY TABLE "TMP_TEST" (
        "Period"  DATE,
        "Country"     VARCHAR,
        "Cost"    FLOAT,
        "Product"    VARCHAR
    );

    INSERT INTO "TMP_TEST"
    VALUES
('01/11/2019','DE','1.54','Product1'),
('01/11/2019','US','2.35','Product1'),
('01/11/2019','DE','4.21','Product2'),
('01/11/2019','US','0.87','Product2'),
('01/12/2019','DE','1.456','Product1'),
('01/01/2020','DE','5.3','Product2'),
('01/02/2020','US','9.76','Product1'),
('01/03/2020','DE','6.78','Product1'),
('01/03/2020','US','1.2','Product2'),
('01/03/2020','DE','3.964 ','Product2'),
('01/04/2020','US','2.58','Product1'),
('01/04/2020','US','2.8','Product2'),
('01/04/2020','DE','0.5 ','Product1');

select * from TMP_TEST;

WITH TOTAL AS (
    SELECT
        "Period","Country","Cost","Product"
    FROM "TMP_TEST"
)
SELECT
    TOTAL.*,
    IFF(UPPER("Country") = 'DE', "Cost", 0) as "Cost DE",
    IFF(UPPER("Country") = 'US', "Cost", 0) as "Cost US",
    DATEADD(MONTH, -1, "Period") AS "Period M-1",
    LAG("Cost", 1, 0) OVER (PARTITION BY "Country", "Product" ORDER BY "Period") AS "Cost USD M1",
    LAG("Cost DE", 1, 0) OVER (PARTITION BY "Country", "Product" ORDER BY "Period") AS "Cost DE M1",
    LAG("Cost US", 1, 0) OVER (PARTITION BY "Country", "Product" ORDER BY "Period") AS "Cost US M1"
FROM TOTAL

Now i want the same results adding a column for the total cost by product for current quarter (imagine we are on period 01/02/2020, i want cumulative sum for the product Quarter to date (january & febuary included))

A: WITH TOTAL AS (
    SELECT
        "Period","Country","Cost","Product"
    FROM "TMP_TEST"
)
SELECT
    DATE_TRUNC('Q',"Period") AS "Quarter",  -- New Quarter Column added for Quarter
    TOTAL.*,
    IFF(UPPER("Country") = 'DE', "Cost", 0) as "Cost DE",
   IFF(UPPER("Country") = 'US', "Cost", 0) as "Cost US",
    DATEADD(MONTH, -1, "Period") AS "Period M-1",
   LAG("Cost", 1, 0) OVER (PARTITION BY "Country", "Product" ORDER BY "Period") AS "Cost USD M1",
   LAG("Cost DE", 1, 0) OVER (PARTITION BY "Country", "Product" ORDER BY "Period") AS "Cost DE M1",
   LAG("Cost US", 1, 0) OVER (PARTITION BY "Country", "Product" ORDER BY "Period") AS "Cost US M1",
   SUM("Cost") OVER (PARTITION BY "Country", "Product","Quarter" ORDER BY "Period") AS"Quarter Cost", -- New Column added For Aggregation By Quarter TO Date

   SUM("Cost DE") OVER (PARTITION BY "Country", "Product","Quarter" ORDER BY "Period") AS"Quarter Aggregation Cost DE" -- New Column added For Aggregation By Quarter TO Date

FROM TOTAL;


text:
Q: Selected Date Field wont stay on page after clicking out of field I've just created my first visualforce page and having an issue with the opportunity close date. When I select the close date on the page, I am able to enter this via typing it out or the date picker. The issue I'm running into now is that the selected date wont stay in the field after I click out of the field.
For example, I enter 9-27-2022, when I click out of the field, it reverts back to having no input.
Do I need to create a separate class for this field?
<apex:page standardController="Opportunity" lightningStylesheets="TRUE" showHeader="TRUE" docType="html-5.0">
<apex:SectionHeader title="New Opportunity">
    <apex:form >
        <apex:pageBlock title="Add Opportunity"  mode="edit">

            <apex:pageBlockSection >
                <apex:inputField value="{!Opportunity.Name}"  required="TRUE"/>
                <apex:inputField value="{!Opportunity.AccountId}"  required="TRUE" />
                <apex:inputField value="{!Opportunity.Stagename}"  required="TRUE"  />
                <apex:inputField value="{!Opportunity.Type}"  required="TRUE"  />
                <apex:inputField value="{!Opportunity.Starting_ARR__c}"  required="TRUE" />
                <apex:inputField value="{!Opportunity.Product__c}"  required="TRUE" />
                <apex:inputField type="date" showDatePicker="TRUE" value="{!Opportunity.CloseDate}" required="TRUE" />
            </apex:pageBlockSection>
        </apex:pageBlock>
        </apex:form >
    <apex:form >
        <apex:pageBlock title="Additional Information"  mode="edit">
                <apex:pageBlockButtons location = "bottom" >
                <apex:commandButton action="{!save}" value="Save"/>
                <apex:commandButton action="{!cancel}" value="Cancel" immediate="true"/>
            </apex:pageBlockButtons>
         <apex:pageBlockSection >
            <apex:inputField value="{!Opportunity.Competitor__c }" />
              <apex:inputField value="{!Opportunity.Other_Competitor__c }" />
               <apex:inputField value="{!Opportunity.Product_Gap__c}"  required="TRUE"  />
         </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:SectionHeader>

</apex:page>

A: Set

showDatePicker = "false"

should work. Setting showDatePicker = "true" is defaulting the date format to dd/mm/yyyy format which doesn't conform to HTML5

redpajama_set_name: RedPajamaStackExchange


text:
Q: MSBuild project vs PowerShell build procedure I have to complete the following tasks:

*

*Prebuild setup (download dependencies etc.)

*Build .net solution

*Run Tests (unit tests and functional tests)

*Generate documentation

*Generate nuget packages

*Sign output

I'm able to complete the task by creating PS build procedure(that uses msbuild just to compile the solution) or MSBuild project with targets(that uses some helper PS scripts). PowerShell is more flexible but MSBuild is a build framework an has some integrated build related features. I'm wondering what will be the best approach. Please share thoughts.

A: Out of the box, MSBuild is specialized in handling tasks and its dependencies. So when you want to do custom stuff that MSBuild can't do by default, you need to call scripts/tools through targets or you can add more types of tasks by including community/custom extensions to your project.
On the other hand, Powershell is free of form, so you have to work your way without built-in structure, but you have the liberty to do whatever you want right out of the box and without having to use another tool/language to fill up the gaps. For multiple projects, you'll have to create some sort of framework if you want to keep your build system maintainable.
If you want both worlds, PSAKE is a tasks handling Powershell module that acts similarly to MSBuild and has syntax based on RAKE, which is pretty neat. In short, PSAKE have a lighter syntax than MSBuild and has most of its features available through Powershell, so you benefit from both worlds.
Generally, it's a matter of taste and needs. I favor short and sweet syntax that tells clearly what part of code do what. MSBuild is based on XML, so there is a lot of redundancy, it has no IDE shipped with it and needs an external tool like Visual Studio to debug it. PSAKE is a Powershell module, so you can spawn Powershell ISE, load the module and enjoy IntelliSense while creating your build scripts.
But understand that there is a lot of possibilities as of what to choose, so pick your poison and don't narrow your choices to only MSBuild and Powershell. See some alternatives here.

A: MSBuild (Now we have a wrapper using dotnet cli) is the Microsoft build engine, its goal is to create a set of task to finally get artifacts or assemblies.
On the other hand PowerShell is a task automation and configuration management. It means you can create scripts for more complex pipelines including Calling a MSBuild,NuGet CLI and so on (e.g. calling Remote modules or any other additional tasks).


text:
Q: Django-paginator + Javascript | Cómo contar respuestas correctas y no perder el dato Un usuario responde una pregunta tras otra, y si es correcta se cuenta y se guarda el valor contado en la etiqueta
. Claro que como cada pregunta está en una página de Paginator (Django), la página se refresca y se pierde el valor guardado en la etiqueta
 (comienza con el 0, y se va cambiando el valor, o esa es la idea).
¿Cómo puedo contar sin perder el dato y sin utilizar la base de datos? ¿Hay otra mejor manera?

if (respuesta == "correcta") {
  var correctas = 0;
  valcorrectas = document.getElementById('respCorrectas').innerHTML;
  valcorrectas = parseInt(valcorrectas) + 1;
  document.getElementById('respCorrectas').innerHTML = valcorrectas;
}

0

A: Pdrías usar el sessionStorage para almacenar el valor y persistirlo en el navegador. Siempre que el navegador no sea cerrado o la pestaña de la página sea cerrada, podrás establecer y obtener el valor almacenado en dicho objeto.
Por ejemplo:
var correctas = window.sessionStorage.getItem('correctas');

if(correctas) { // si el elemento existe debo convertirlo a tipo Integer
  correctas = parseInt(correctas);
} else {
  correctas = 0;
}

// ahora viene la lógica para aumentar el contador si la respuesta es correcta
// supongo que eso lo haces en algún botón de acción
if(respuesta == "correcta"){
  // aumentamos el contador
  correctas++;
  //almacenamos el valor en el sessionStorage
  window.sessionStorage.setItem('correctas', correctas);
}

De esta forma al cargar la nueva pregunta, se ejecuta el código que verifica si existe la variable correctas en el Objeto sessionStorage, la convierte en entero.
Cuando la página carga por primera vez, la variable no existe en el sessionStorage, es por ello que la establece a 0, para iniciar el contador.
Espero que de esta forma puedas solventar el problema.


text:
Q: How can I prove the general formula for Taylor Series? I am trying to prove the general form for practice and I am having some trouble with it. The question in my book is "Suppose f is infinitely differentiable on an open interval I containing the point x = c, and there exists a constant M > 0 such that |$f^{(n)} (x)$| $\leq$ M for all x $\in$ I and all n $\geq$ 0. Show that
$$ f(x) = \sum_{n=0}^\infty \frac{f^{(n)}(c)}{n!} (x-c)^n $$
My thoughts were to use the definition of a power series
$$ \sum a_n (x-c)^n $$
and then to make the assumption that the power series converges with $|x-c| < M $ then to let $f(x)$ to be equal to our power series than evaluating each n-th derivative at $x=c$ than to make the statement that if we repeat this process infinitely many times we get the desired form of $a_n = \frac{f^{(n)}(c)}{n!} $
This is what I am unsure about because I am not sure if this would be strong enough to prove the Taylor's form especially with trying to get the form of $a_n$ any suggestions would be appreciated. Cheers

A: Your approach is a reasonable one to gain intuition.  However, it tacitly assumes that one can differentiate the power series term by term as if it were a finite sum.  The fact that it is not a finite sum creates a need to apply a more rigorous way forward.  To that end we proceed.

Note that from Taylor's Theorem, we can write for a $n$ times differentiable function at $x=c$
$$f(x)=\sum_{k=0}^n\frac{f^{(k)}(c)}{k!}(x-c)^k+R_n(x,c) \tag1$$
where the remainder $R_n(x,c)=o(|x-c|^n)$ as $x\to c$.
From $(1)$ we have $R_n(x,c)=f(x)-\sum_{k=0}^n\frac{f^{(k)}(c)}{k!}(x-c)^k$,
If for $x\in (c-a,a+c)$, $f$ and all of its derivatives exist, and if $x_0\in (c-a,c+a)$, then $f$ is represented by its Taylor series at $x_0$ if and only if
$$\lim_{n\to \infty}R_n(x,c)=0$$

There are a variety of explicit forms for the remainder term and estimates thereof.    The mean-value form of the remainder,
$$R_n(x,c)=\frac{f^{(n+1)}(\xi)}{(n+1)!}(x-c)^{n+1}$$
for some $\xi\in(c,x)$.  If all derivatives of $f$ are bounded above with $|f^{(k)}|\le M$ for $|x-c|< a$, then
$$|R_n(x,c)|\le M\frac{a^{n+1}}{(n+1)!}$$
and the Taylor series converges uniformly to $f$.  In such as case, we can write
$$f(x)=\sum_{k=0}^\infty\frac{f^{(k)}(c)}{k!}(x-c)^k$$
for $x\in (c-a,c+a)$


text:
Q: Multiple text shadows in 2d canvas In CSS, I can chain multiple definitions in the text-shadow property to achieve effects such as glow:

.green-glow {
    padding:20px 40px 40px;
    font-family:'Georgia';
    font-size:70px;
    background-color:#000;
    color: #fff;
    text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #fff, 0 0 40px #0f0, 0 0 70px #0f0, 0 0 80px #0f0, 0 0 100px #0f0, 0 0 150px #0f0;
}

glow

I would like to achieve similar effects when drawing text on a canvas element using CanvasRenderingContext2D.fillText but since shadow definitions are split among multiple properties (shadowBlur, shadowColor, etc.), it is not immediately obvious for me the adequate way to chain multiple shadows.
I can do multiple calls to CanvasRenderingContext2D.fillText, one for each defined shadow as the following snippet shows...

// get context
var ctx = document.querySelector('#test').getContext('2d');

// clear background to black
ctx.fillStyle = '#000'
ctx.fillRect(0, 0, 500, 150);

// common font attributes
ctx.font = "70px Georgia";
ctx.fillStyle = 'white';

// apply multiple shadows

ctx.shadowColor = '#fff';
ctx.shadowBlur = 10;
ctx.fillText('glow', 50, 90);

ctx.shadowBlur = 20;
ctx.fillText('glow', 50, 90);

ctx.shadowBlur = 30;
ctx.fillText('glow', 50, 90);

ctx.shadowColor = '#0f0';
ctx.shadowBlur = 40;
ctx.fillText('glow', 50, 90);

ctx.shadowBlur = 70;
ctx.fillText('glow', 50, 90);

ctx.shadowBlur = 80;
ctx.fillText('glow', 50, 90);

ctx.shadowBlur = 100;
ctx.fillText('glow', 50, 90);

ctx.shadowBlur = 150;
ctx.fillText('glow', 50, 90);
canvas {
    width: 500px;
    height: 150px;
}
<canvas id="test" width="500" height="150"></canvas>

... and even though it doesn't quite look the same to me, it would be good enough for my purposes. But I am wondering about possible performance issues caused by those multiple calls to fillText and whether there is a more appropriate way to apply multiple text shadows on a canvas.
Thanks!


text:
Q: persistent microcode update on Linux I just tried to update the microcode for my Intel Core i3-3217U processor following the instructions from Intel. I am on Linux Mint Debian edition 2 (3.16.0-5-amd64 kernel).
What I did:

*

*There is a /sys/devices/system/cpu/microcode/reload

*There is no /lib/firmware/intel-ucode, only a /lib/firmware/intel. I added the folder anyway from the downloaded package.

*As per instruction, as SU I executed
echo 1 > /sys/devices/system/cpu/microcode/reload

cat /proc/cpuinfo | grep microcode gives me 0x1f, which is the updated version - but only as long as the system is running. After a reboot I am back to 0x12.
How can I make the update permanent?

A: You can't make the Intel microcode update permanent, it must be loaded after each boot. The microcode is stored in volatile RAM in the CPU.

A: As a intermediate solution while microcode update is not ported into Debian, you may add the "echo 1 > /sys/devices/system/cpu/microcode/reload" to /etc/rc.local after you install microcode update per Intel instructions.
This is a rather late patching, but probably OK if you trust your boot environment :)

A: I found that I can load the microcode to the initial ramdisk leveraging the code from debian package intel-microcode. This is currently at an older version of the microcodes, but they can be overridden.
After installing the package, I manually removed all files in /lib/firmware/intel-ucode and replaced them with the new versions from the Intel download. After that I could update initrd.img-<kernel version> with
update-initramfs -u

grub-mkconfig would also execute this.
As I understand it, the intel-ucode.img mentioned in the other answer would be a so-called "early initramfs archive". It seems the initramfs-tools hook script that is included in the package chooses for itself whether it places the update module in a separate .img or into the main initrd.img.
Edit: It seems the new microcode versions have already landed in the unstable package. Dependencies are unchanged, so they might work on Debian stretch (or jessie, which I am still on.) I suspect it will be only a few days until the new package version will be backported. Then, installing will suffice.

A: Microcode updates are applied during boot, and thus should be added to the bootloader, e.g. GRUB2 or systemd-boot. More specifically, /boot/intel-ucode.img (or wherever this file is located on your system) should be added as the first initrd image of your boot process (but it should not replace your normal initrd image). Once the microcode update package is installed, the grub-mkconfig script usually takes care of this on its own, but you can check if the /boot/grub/grub.cfg file has a similar line:
initrd  /intel-ucode.img /initramfs-linux.img

If not, you may either reinstall the microcode package, or run the grub-mkconfig script manually.


text:
Q: GoLang conventions - create custom type from slice Is it a good idea to create own type from a slice in Golang?
Example:
type Trip struct {
    From   string
    To     string
    Length int
}

type Trips []Trip // <-- is this a good idea?

func (trips *Trips) TotalLength() int {
    ret := 0
    for _, i := range *trips {
        ret += i.Length
    }

    return ret
}

Is it somehow a convention in Golang to create types like Trips in my example? Or it is better to use []Trip in the whole project? Any pros and cons?

A: If this is what your type is (a slice), it's just fine. It gives you an easy access to underlying elements (and allows for range iteration) while providing additional methods.
Of course you probably should only keep essential set of methods on this type and not bloating it with everything that would take []Trip as an argument. (For example I would suggest having DrawTripsOnTheGlobe(t Trips) rather than having it as a Trips' method.)
To calm your mind there are plenty of such slice-types in standard packages:
http://golang.org/pkg/net/#IP
http://golang.org/pkg/sort/#Float64Slice
http://golang.org/pkg/sort/#IntSlice
http://golang.org/pkg/encoding/json/#RawMessage

A: There's no convention, as far as I am aware of. It's OK to create a slice type if you really need it. In fact, if you ever want to sort your data, this is pretty much the only way: create a type and define the sort.Interface methods on it.
Also, in your example there is no need to take the address of Trips since slice is already a "fat pointer" of a kind. So you can simplify your method to:
func (trips Trips) TotalLength() (tl int) {
    for _, l := range trips {
        tl += l.Length
    }
    return tl
}


text:
Q: WP8 ListPicker Bind When I bind my data via item source to my ListPicker:
C#:
var sightingTypes = SightingTypes.List;
sightingTypesPicker.ItemsSource = sightingTypes;

XML:
    <toolkit:ListPicker x:Name="sightingTypesPicker" ItemsSource="{Binding sightingTypes, ElementName=this}">
        <toolkit:ListPicker.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Name}" FontSize="{StaticResource PhoneFontSizeSmall}"/>
                </StackPanel>
            </DataTemplate>
        </toolkit:ListPicker.ItemTemplate>
    </toolkit:ListPicker>

I can see the Name being shown in the ListPicker, but, when I click on the ListPicker it shows the List of the Object Type, like this:
MyProject.Model.SightingType
MyProject.Model.SightingType
MyProject.Model.SightingType
MyProject.Model.SightingType
MyProject.Model.SightingType
MyProject.Model.SightingType

How do I:
A: Make the Name Property show when the list shows
B: Bind the ID Property as the Value but not show it

A: You need to assign FullModeItemTemplate for that to work:
<toolkit:ListPicker x:Name="sightingTypesPicker" ItemsSource="{Binding sightingTypes, ElementName=this}">
    <toolkit:ListPicker.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Name}" FontSize="{StaticResource PhoneFontSizeSmall}"/>
            </StackPanel>
        </DataTemplate>
    </toolkit:ListPicker.ItemTemplate>
    <toolkit:ListPicker.FullModeItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Name}" FontSize="{StaticResource PhoneFontSizeSmall}"/>
                <TextBlock Text="{Binding SomeOtherProp}" FontSize="{StaticResource PhoneFontSizeSmall}"/>
            </StackPanel>
        </DataTemplate>
    </toolkit:ListPicker.FullModeItemTemplate>
</toolkit:ListPicker>

EDIT: To answer your question B: You can use the SelectedItem DependencyProperty to get the instance of the selected object:
With MVVM approach:
<toolkit:ListPicker x:Name="sightingTypesPicker"
                    ItemsSource="{Binding SightingTypes}"
                    SelectedItem="{Binding SelectedSigntingType, Mode=TwoWay}">

With code-behind approach:
sightingTypesPicker.SelectionChanged += (s, e) => {
    MessageBox.Show(((SightingType)e.AddedItems[0]).ID);
};


text: Q: Синхронизация нескольких потоков с главным потоком приложения Есть несколько устройств, управляемых через последовательный интерфейс. Устройства одинаковые по сути, поэтому создал визуальный компонент для управления этими устройствами. Пока со стороны пользователя нет никаких действий, нужно проверять, все ли в порядке на устройстве, (делаю это в отдельном потоке). Если на устройстве возникает какое-то событие, необходимо, чтобы приложение методами визуального компонента обработало это событие. На момент разработки приложения количество устройств неизвестно и может быть любым < 128. Кроме того, есть потребность в дополнительном потоке (выстрелил забыл), который тоже должен управлять устройствами. Во время работы этого потока можно у пользователя отобрать управление, оставить только возможность  остановить поток.


text:
Q: How to continuously load a saved flow file from mitmproxy? (i.e. "follow"/-f the file) I've saved a file with the --save-stream-file (save_stream_file) option.
Now I want to replay that as asked in my previous question, but I want it to continuously follow the saved "flow".
How can I do that?
This is a follow-up question of How to replay/show a saved flow in the console without triggering requests?.

A: After some asking I got around and this should do the trick:
tail -f ./mitmproxy-flow.cap | mitmproxy --rfile - -n

Thanks to @mhils!
Though, at least for me, v5.2 currently still has a bug where it crashes.


text:
Q: parse string to JSON by javascript or JQUERY? My string looks like this one below. But while converting it to JSON by javascript/jQuery the error is received "Invalid Charater". Please help
'[{ color: "#8B0000",  data: [{ "y":  12000,  "x":  0}],  pointRange: 8,  type: "column",  name: "Segment1"}, { color: "#FFA500",  data: [{ "y":  11000,  "x":  10}],  pointRange: 12,  type: "column",  name: "Segment2"}, { color: "#11ddbb",  data: [{ "y":  10000,  "x":  19}],  pointRange: 6,  type: "column",  name: "Segment3"}, { color: "#8B0000",  data: [{ "y":  8000,  "x":  24}],  pointRange: 5,  type: "column",  name: "Segment4"}]'

This is the code I am using to parse it to JSON.
var response ='[{ color: "#8B0000",  data: [{ "y":  12000,  "x":  0}],  pointRange: 8,  type: "column",  name: "Segment1"}, { color: "#FFA500",  data: [{ "y":  11000,  "x":  10}],  pointRange: 12,  type: "column",  name: "Segment2"}, { color: "#11ddbb",  data: [{ "y":  10000,  "x":  19}],  pointRange: 6,  type: "column",  name: "Segment3"}, { color: "#8B0000",  data: [{ "y":  8000,  "x":  24}],  pointRange: 5,  type: "column",  name: "Segment4"}]';
response=$.parseJSON(response);
alert(response);

A: The original reponse message is an invalid json.
Option 1 :
What you have is a Javascript Object (provided you remove those single quotes marks). You don't have a JSON String but Javascript Object.
After removing quotes from the start, it will look like
var response = [{ color: "#8B0000",  data: [{ "y":  12000,  "x":  0}],  pointRange: 8,  type: "column",  name: "Segment1"}, { color: "#FFA500",  data: [{ "y":  11000,  "x":  10}],  pointRange: 12,  type: "column",  name: "Segment2"}, { color: "#11ddbb",  data: [{ "y":  10000,  "x":  19}],  pointRange: 6,  type: "column",  name: "Segment3"}, { color: "#8B0000",  data: [{ "y":  8000,  "x":  24}],  pointRange: 5,  type: "column",  name: "Segment4"}];

var jsonString = JSON.stringify(response);

You now have option of converting it to JSON string using JSON.stringify().
You also have an option 2 :
Add double quotes to all the key values, that will also work. That would make it a JSON string. You can then use JSON.parse() to convert it to JSON Object.
var response = '[{ "color": "#8B0000", "data": [{ "y":12000, "x":0}], "pointRange": 8, "type": "column", "name": "Segment1"}, { "color": "#FFA500", "data": [{ "y": 11000, "x": 10}], "pointRange": 12, "type": "column", "name": "Segment2"}, { "color": "#11ddbb", "data": [{ "y": 10000, "x": 19}], "pointRange": 6, "type": "column", "name": "Segment3"}, { "color": "#8B0000", "data": [{ "y": 8000, "x": 24}], "pointRange": 5, "type": "column", "name": "Segment4"}]';

var jsonObject = JSON.parse(response);

A: If you have time please visit http://www.json.org/. There you will find the specification of JSON.
One of your problems is: the key in the object must be a string in double quotes.
For example:
'{ color: "#8B0000" }'  is wrong
It must be:
'{ "color": "#8B0000" }'

A: the below may be a solution

var response ='[{ color: "#8B0000",  data: [{ "y":  12000,  "x":  0}],  pointRange: 8,  type: "column",  name: "Segment1"}, { color: "#FFA500",  data: [{ "y":  11000,  "x":  10}],  pointRange: 12,  type: "column",  name: "Segment2"}, { color: "#11ddbb",  data: [{ "y":  10000,  "x":  19}],  pointRange: 6,  type: "column",  name: "Segment3"}, { color: "#8B0000",  data: [{ "y":  8000,  "x":  24}],  pointRange: 5,  type: "column",  name: "Segment4"}]';
var Obj=eval(response);
var response=JSON.stringify(Obj);
alert(response);

A: In Javascript json string Convert all keys into quoted string like  color to "color" etc.
var response = '[{ "color": "#8B0000",  "data": { "y":  12000,  "x":  0},  "pointRange": 8,  "type": "column",  "name": "Segment1"}, { "color": "#FFA500",  "data": [{ "y":  11000,  "x":  10}],  "pointRange": 12,  "type": "column",  "name": "Segment2"}, { "color": "#11ddbb",  "data": [{ "y":  10000,  "x":  19}],  "pointRange": 6,  "type": "column",  "name": "Segment3"}, { "color": "#8B0000",  "data": [{ "y":  8000,  "x":  24}],  "pointRange": 5,  "type": "column",  "name": "Segment4"}]';
response=JSON.parse(response);
console.log(response);

A: @Monsta - you are missing double quote in the key; the code should be like this:
var response ='[{ "color": "#8B0000",  "data": [{ "y":12000,  "x":0}],  "pointRange": 8,  "type": "column",  "name": "Segment1"}, { "color": "#FFA500",  "data": [{ "y":  11000,  "x":  10}],  "pointRange": 12,  "type": "column",  "name": "Segment2"}, { "color": "#11ddbb",  "data": [{ "y":  10000,  "x":  19}],  "pointRange": 6,  "type": "column",  "name": "Segment3"}, { "color": "#8B0000",  "data": [{ "y":  8000,  "x":  24}],  "pointRange": 5,  "type": "column",  "name": "Segment4"}]';
JSON.parse(response);


text:
Q: How to setup Trading view pine script alert notification for strategy.exit which is using stop, trail_points and trail_offset I created a script which is working flawlessly on Tradingview so I wanted to create alert notifications. Buy order is coming after certain conditions get satisfied and I'm creating an alter through alertcondition() function, as follows
//Buy Condition
Buy = condition1 and condition2 and testrange
alertcondition(Buy, title = "Buy Signal", message = "Buy Signal Alert")

I'm stuck in the sell order alert notification as I'm using strategy.exit() which has stop, trail_points and trail_offset. So the strategy either hits stop-loss or it starts trailing from a certain percentage with an offset.
//Exit Strategy
strategy.exit("TP/SL", "Enter Long", stop=StopLoss * (1 - sl_inp),
   trail_points = close * TrailPer / syminfo.mintick,
   trail_offset = close * TrailOffset / syminfo.mintick)

I  can't use alertfunction() here as the trailing stoploss and offset are both defined in strategy.exit function.
So how can I set up an alert notification for the exit? Please help!


text:
Q: ¿Como enviar datos mediante AJAX y JQuery? Tengo un formulario con dos inputs, uno de tipo text y otro de tipo password.  Tengo un boton que envía el formulario, el dicho formulario tiene como destino el archivo "login.php" y mi pregunta es: ¿Como puedo enviar los datos mediante AJAX y JQuery para no tener que recargar la pagina, es decir, tengo una sixtaxis basica, me falta saber como llenar dichos campos, a continuación los códigos:  Codigo HTML (Formulario):
<form action="login.php" method="post" id="loginForm">
      <label for="inputUser"> Username </label>
      <input type="text" id="inputUser" name ="user">
      <label for="inpuPassword"> Password </label>
      <input type="password" id="inputPassword" name ="password">
      <input type="button" id="btnLoginForm" form="loginForm" value="Login">
    </form>

Mi estructura basica de AJAX, la idea solo solo saber como llenar esos campos para que envíe los datos.
<script>
    $(document).ready(function(){
      $("#btnLoginForm").click(function(){
        var username = $('#inputUser').val();
        var password = $('#inputPassword').val();
        $.ajax({
          type:
          url:
          data:
          beforeSend:function(){

          },
          success:function(){

          },
        });
      });
    });
  </script>

Si es posible, quisiera recomendaciones de como recibir los datos en el archivo "login.php" y enviar una respuesta al codigo AJAX para saber si se hizo lo que yo quiero, en este caso una consulta SQL

A: Debes enviar  un objeto con la data:
    $.ajax({
      type:
      url:
      data:
       {usuario:username,password:password},
      success:function(){

      },
    });


text:
Q: How to fix CircularProgressIndicator() size in toolbar I am trying to set fixed size CircularProgressIndicator in toolbar actions[] but it is giving me the inappropriate size,
the code I am using,
Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(Lang.postDetails),
        actions: <Widget>[
       Container(

                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(),
                )

and output I am getting,

A: I have solved this myself,
If anyone faces this issue just wrap your Container inside a Center widget,
Center(
       child: Container(
       width: 16,
       height: 16,
       child: CircularProgressIndicator()),
       )

Output


text:
Q: In iOS - Production and staging server included in single build I have an application having two servers STAGING and PRODUCTION. I used to release two builds with changing the servers in coding part. But now my client asked to provide a single build where we can provide an option in app settings or phone settings to chnage the URL.
I reserached a lot in stack overflow and came to know that at runtime when we select debug/release mode at the time of giving build, it can be possible but anyways it is also come under process of giving two builds.
I want to have a single build where the user can change the option of Staging/Producetion. Please help me. Is it possible. ?

A: You can just add a switch somewhere in your application to turn on staging mode (switch off = production). The state of this switch is saved in NSUserDefaults. Then, depending to this state, you choose the right URL of server in your code.

A: You can do this way -
1.In the sign in page depending upon the field you are using to enter the staging or production url ,open an UIAction sheet when the field(In my case i am using tableview cell, you can use a text field or a button) is clicked then show fields like below -
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.row == 2) {
    [self showActionSheet];

[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
}

calling the action sheet above in the didselectrow which will open an action sheet as below
- (void)showActionSheet
{
NSString *actionSheetTitle = @"Choose Connection";
NSString *other1 = @"development";
NSString *other2 = @"staging";
NSString *other3 = @"production";
NSString *cancelTitle = @"Cancel";

UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:actionSheetTitle
                                                         delegate:self
                                                cancelButtonTitle:cancelTitle
                                           destructiveButtonTitle:nil
                                                otherButtonTitles:other1, other2, other3, nil];

[actionSheet showInView:self.view];
}

 - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
//Get the name of the current pressed button
NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex];

if ([buttonTitle isEqualToString:@"development"]) {

    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

    [defaults setObject:nil forKey:@"UserId"];

    NSLog(@"Destructive pressed --> Delete Something");
}
if ([buttonTitle isEqualToString:@"staging"]) {
    NSLog(@"Other 1 pressed");
}
if ([buttonTitle isEqualToString:@"production"]) {
    NSLog(@"Other 2 pressed");
}

}

and finally saving the user state like above using NSUserDefaults like above in the clicked button index.


text:
Q: hadoop cluster is not running map reduce jobs - issue with scheduler (this is a follow-up on a discussion I had regarding an earlier question I had on this matter)
I set up a small Hadoop cluster following these instructions but using Hadoop version 2.7.4. The cluster seems to work OK, but I cannot run mapreduce jobs. In particular, when trying the following
$HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.7.4.jar randomwriter outdenter code here

the job prints
17/11/27 16:35:21 INFO client.RMProxy: Connecting to ResourceManager at
ec2-yyy.eu-central-
1.compute.amazonaws.com/xxx:8032
Running 0 maps.

Job started: Mon Nov 27 16:35:22 UTC 2017

17/11/27 16:35:22 INFO client.RMProxy: Connecting to ResourceManager at
ec2-yyy.eu-central-
1.compute.amazonaws.com/xxx:8032

17/11/27 16:35:22 INFO mapreduce.JobSubmitter: number of splits:0

17/11/27 16:35:22 INFO mapreduce.JobSubmitter: Submitting tokens for
job: job_1511799491035_0006

17/11/27 16:35:22 INFO impl.YarnClientImpl: Submitted application
application_1511799491035_0006

17/11/27 16:35:22 INFO mapreduce.Job: The url to track the job:
http://ec2-yyy.eu-central-
1.compute.amazonaws.com:8088/proxy/application_1511799491035_0006/

17/11/27 16:35:22 INFO mapreduce.Job: Running job:
job_1511799491035_0006

and never gets past this state.
In the job tracker, it says
ACCEPTED: waiting for AM container to be allocated, launched and
register with RM.

I then looked into the log files where I found
2017-11-27 13:50:29,202 INFO org.apache.hadoop.conf.Configuration: found resource capacity-scheduler.xml at file:/usr/local/hadoop/etc/hadoop/capacity-scheduler.xml
2017-11-27 13:50:29,252 INFO org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration: max alloc mb per queue for root is undefined
2017-11-27 13:50:29,252 INFO org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration: max alloc vcore per queue for root is undefined
2017-11-27 13:50:29,256 INFO org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.ParentQueue: root, capacity=1.0, asboluteCapacity=1.0, maxCapacity=1.0, asboluteMaxCapacity=1.0, state=RUNNING, acls=ADMINISTER_QUEUE:*SUBMIT_APP:*, labels=*, reservationsContinueLooking=true
2017-11-27 13:50:29,256 INFO org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.ParentQueue: Initialized parent-queue root name=root, fullname=root
2017-11-27 13:50:29,265 INFO org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration: max alloc mb per queue for root.default is undefined
2017-11-27 13:50:29,265 INFO org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration: max alloc vcore per queue for root.default is undefined

which suggest that there is a problem with the capacity scheduler. The file capacity-scheduler.xml looks as follows:
<configuration>

  <property>
    <name>yarn.scheduler.capacity.maximum-applications</name>
    <value>10000</value>
    <description>
      Maximum number of applications that can be pending and running.
    </description>
  </property>

  <property>
    <name>yarn.scheduler.capacity.maximum-am-resource-percent</name>
    <value>0.1</value>
    <description>
      Maximum percent of resources in the cluster which can be used to run
      application masters i.e. controls number of concurrent running
      applications.
    </description>
  </property>

  <property>
    <name>yarn.scheduler.capacity.resource-calculator</name>
    <value>org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator</value>
    <description>
      The ResourceCalculator implementation to be used to compare
      Resources in the scheduler.
      The default i.e. DefaultResourceCalculator only uses Memory while
      DominantResourceCalculator uses dominant-resource to compare
      multi-dimensional resources such as Memory, CPU etc.
    </description>
  </property>

  <property>
    <name>yarn.scheduler.capacity.root.queues</name>
    <value>default</value>
    <description>
      The queues at the this level (root is the root queue).
    </description>
  </property>

  <property>
    <name>yarn.scheduler.capacity.root.default.capacity</name>
    <value>100</value>
    <description>Default queue target capacity.</description>
  </property>

  <property>
    <name>yarn.scheduler.capacity.root.default.user-limit-factor</name>
    <value>1</value>
    <description>
      Default queue user limit a percentage from 0.0 to 1.0.
    </description>
  </property>

  <property>
    <name>yarn.scheduler.capacity.root.default.maximum-capacity</name>
    <value>100</value>
    <description>
      The maximum capacity of the default queue.
    </description>
  </property>

  <property>
    <name>yarn.scheduler.capacity.root.default.state</name>
    <value>RUNNING</value>
    <description>
      The state of the default queue. State can be one of RUNNING or STOPPED.
    </description>
  </property>

  <property>
    <name>yarn.scheduler.capacity.root.default.acl_submit_applications</name>
    <value>*</value>
    <description>
      The ACL of who can submit jobs to the default queue.
    </description>
  </property>

  <property>
    <name>yarn.scheduler.capacity.root.default.acl_administer_queue</name>
    <value>*</value>
    <description>
      The ACL of who can administer jobs on the default queue.
    </description>
  </property>

  <property>
    <name>yarn.scheduler.capacity.node-locality-delay</name>
    <value>40</value>
    <description>
      Number of missed scheduling opportunities after which the CapacityScheduler
      attempts to schedule rack-local containers.
      Typically this should be set to number of nodes in the cluster, By default is setting
      approximately number of nodes in one rack which is 40.
    </description>
  </property>

  <property>
    <name>yarn.scheduler.capacity.queue-mappings</name>
    <value></value>
    <description>
      A list of mappings that will be used to assign jobs to queues
      The syntax for this list is [u|g]:[name]:[queue_name][,next mapping]*
      Typically this list will be used to map users to queues,
      for example, u:%user:%user maps all users to queues with the same name
      as the user.
    </description>
  </property>

  <property>
    <name>yarn.scheduler.capacity.queue-mappings-override.enable</name>
    <value>false</value>
    <description>
      If a queue mapping is present, will it override the value specified
      by the user? This can be used by administrators to place jobs in queues
      that are different than the one specified by the user.
      The default is false.
    </description>
  </property>

</configuration>

I would be grateful for any hints on how to approach this?.
Thanks
c14

A: Every thing fine with Cluster configuration but When it comes to Job execution, RAM provided by t2.micro instance is not enough to run the MapReduce jobs, so better use bigger instances for cluster creation and job execution


text:
Q: Existence of a weak solution to this SDE? I am looking at an SDE of the form $d{X_t} = \left( {{1_A}({X_t}) - {1_{{A^c}}}({X_t})} \right)d{W_t}$ such that ${X_0} = 0$, $A \in \mathcal{B}(\mathbb{R})$ and ${A^c}$ has a lebesgue measure of zero. I was thinking along the following lines: Consider a complete probability space $(\Omega ,\mathcal{F},\mathbb{P})$ that supports some Brownian Motion $X_t$. Then:
${W_t} = \int\limits_0^t {\left( {{1_A}({X_u}) - {1_{{A^c}}}({X_u})} \right)d{X_u}} $
is a brownian motion by Levy's Characterisation Theorem. Then:
$\left( {{1_A}({X_t}) - {1_{{A^c}}}({X_t})} \right)d{W_t} = \left( {{1_A}({X_t}) - {1_{{A^c}}}({X_t})} \right)\left( {{1_A}({X_t}) - {1_{{A^c}}}({X_t})} \right)d{X_t} = d{X_t}$
From which we may conclude that $\left( {X,W} \right)$, $(\Omega ,\mathcal{F},\mathbb{P})$ and $\mathcal{F}_t$ is a weak solution to the above SDE.
Also can we conclude $\mathbb{P}({X_t} \in {A^c}) = 0$ for all t?

A: Since $X$ is a Brownian Motion, $X_t$ is normally distributed for all $t>0$ and so the fact $\mathbb{P}(X_t \in A^c) = 0$ follows from the fact that $A^c$ has Lebesgue measure $0$.  For $t=0$, we have $\mathbb{P}(X_t \in A^c) = 0$ if and only if $0 \in A$.
On the other hand, we don't necessarily have $\mathbb{P}(X_t \in A \, \forall \, t>0) = 1$.  In fact, as long as $A^c$ is non-empty, $\mathbb{P}(X_t \in A \, \forall \, t>0) = 0$ because Brownian motion almost surely hits all points in $\mathbb{R}$.


text:
Q: "undefined is not a function" on split with pop I have an array of filenames called ret.
I want to get the extension of each file name.
var cList="";
var fName="";
var ext="";
for(var i=0;i<=ret.length-1;i++){
    fName=ret[i];
    ext=fName.split('.').pop();
    if(ext=="msi"){
        cList+="
Yield Monitor Simulators
";
    }
    cList+=""+fName+"
";
}

But on the line:
ext=fName.split('.').pop();

Why do I get the error:

"Uncaught TypeError: undefined is not a function"

If I simply remark out the offending line, I get the list of files as expected.
var cList="";
var fName="";
var ext="";
for(var i=0;i<=ret.length-1;i++){
    fName=ret[i];
    //ext=fName.split('.').pop();
    if(ext=="msi"){
        cList+="
Yield Monitor Simulators
";
    }
    cList+=""+fName+"
";
}

Still the JSFiddle works so it must be something in my code...

A: The solution was to add toString() to the fName variable.
fName=ret[i].toString();

apparently a value taken from array of string values is not a string?
added later:
for(var i=0;i<=ret.length-1;i++){
      console.log(i, ret[i]);
      console.log(i, ret[i], ret[i].split('.'), ret[i].split('.').pop());
        fName=ret[i].toString();

on the first iteration console says:
0 ["2020.pdf"] index.js:115
Uncaught TypeError: undefined is not a function

A: ret is an array containing arrays containing a string...not an array of strings as you expect, check the values of your ret :
[] means an array in javascript
["astring"] is an array containing a string
["astring",99] is an array containing a string at index 0 and a number at index 1

if you console.log(ret) before your loop you will probably get something like :
[["string"],["string"],["string"]...]
instead of ["string","string","string"...]

needs some javascript syntax revision here...work hard


text:
Q: Independence of an interval and a product set in $\mathbb Z/L\mathbb Z$.  I have $k$ distinct prime numbers $\ell_1 < \dots <\ell_k$, and for each $i=1,\dots,k$, a subset $A_i$ of $\mathbb Z / \ell_i \mathbb Z$. Let $L=\ell_1 \dots \ell_k$. Now using the chinese reminder theorem, $\mathbb Z/ L \mathbb Z = \prod_{i=1}^k \mathbb Z /\ell_i \mathbb Z$,
hence the subset $\prod_{i=1}^k {A_i}$ of the RHS is identified to a subset $A$ of $\mathbb Z/L \mathbb Z$ (that what I call a "product set").
Now consider an interval $I$ of $\mathbb Z / \ell \mathbb Z$. I would say (that's acknowledgedly a vague definition) that $I$ and $A$ are "approximately independent" of
$\frac{|A \cap I|}{|I|}$ is close to $\frac{|A|}{L}$. For exemple, when $I = \mathbb Z/L\mathbb Z$, then
these two fractions are  trivially equal.
Now it seems natural to believe that when $|I|$ is large with respect to the $\ell_i$, even if it is small with respect to $L=\prod_i \ell_i$,
then $A$ is approximately independent to $I$.

Is this intuition true in some sense?

I apologize for this vague question: I think it makes sense as it is and it seems that any of my  attempt to make it more precise will result in something false or trivial. I also have
the frustrating impression that I have already seen this problem, or something very close
to it (that is concerning the "independence" of product sets in $\mathbb Z / L \mathbb Z$ with other natural subsets of $\mathbb Z / L \mathbb Z$) discussed somewhere, perhaps even on MO.
But I am not able to recall where, and missing even a name or keywords for this problem,
I don't know where to look for. So any reference or names for this question is welcome.
(PS: I don't even know how to tag this question. Please feel free to change tags)

A: I don't like to answer my own question, but I don't like to have one of my question still open when it should not be anymore. So actually, thanks to Boris Bukh's comments, which put in my mind the word "equidistribution", I eventually remembered where I saw a setting that looked a lot like my question: it is the setting of the large sieve, that I had seen before without really understanding what it was for. But if one looks for instance to Kowalski's beautiful book "The large sieve and its applications", chapter II, one sees a setting in which my question fits naturally. Using it it is an exercise to
 get upper bound on $\frac{|A \cap I|}{|I|}$ which are conforms to my intuition that
this should be close to $\frac{|A|}{|L|}$. For lower bound I don't know, but it was actually
upper bound I was interested in. Unfortunately, the upper bound I get are not quote as good as I would need, but that's my problem.


text:
Q: Trying to get code to output multiple columns in Python I am importing a data set and trying to output some text analysis. However, I can only get it to output the last column of data. Where do I put the csv.writer in order to get all the lines of code in?
from __future__ import division
import csv
import re
from string import punctuation

faithwords = ['church', 'faith', 'faith']

with open('dataset.csv', 'rb') as csvfile:
    data = csv.reader(csvfile, delimiter=",")

    for row in data:

        faithcounter = 0

        row3 = row[3]
        row3 = row3.lower().replace('  ', ' ')
        row4 = row[4]
        row4 = row4.lower().replace('  ', ' ')

        for p in list(punctuation):
            row3 = row3.replace(p, '')
            row4 = row4.replace(p, '')

        essay1= re.split(' ', row3)
        essay2= re.split(' ', row4)

        essay1len = len(essay1)
        essay2len = len(essay2)

        num_of_rows = len(row)

        for word in essay1:
            if word in faithwords:
                faithcounter = faithcounter + 1

        for word in essay2:
            if word in faithwords:
                faithcounter = faithcounter + 1

        totallen = (essay2len + essay1len)

        row.append(essay1len)
        row.append(essay2len)
        row.append(totallen)
        row.append(faithcounter)
        row.append(faithcounter / totallen)

        output = zip(row)

writer = csv.writer(open('csvoutput.csv', 'wb'))
writer.writerows(output)

A: Your problem is with this line:
output=zip(row)

I'm not sure why you are doing zip, but I do know that your are overwriting output on each iteration.
I recommend that you create your csv writer before your loop.  Then, as the last statement in your loop, do:
writer.writerow(row)

A: I would suggest removing output=zip(row) and replace it with writer.write(row)
Remove writer.writerows(output) and put writer = csv.writer(open('csvoutput.csv', 'wb'))
 above your loop.


text:
Q: Find max time delta after sorting data and applying groupby I have a data frame (df) that contains two rows with multiple entries per 'name':
                     name                           date
       Official Press FRC        2015-02-19 20:30:00.000
   Other Publications BOJ        2015-04-16 07:00:00.000
           Bank of Russia        2015-06-11 09:44:37.000

I would like to find the maximum difference in 'dates' for each 'name'. My approach to this was to try and sort the dates while simultaneously grouping by name and then take the difference using .diff(). Below is the code I tried:
grouped = df.sort_values('date').groupby('name')
differences = grouped.diff()

I also tried to approach the problem by constructing a pivot table:
grouped = df.pivot(columns='name', values='date')

A: I think you need custom function with diff and max for max timedelta:
#if necessary convert to datetime
df['date'] = pd.to_datetime(df['date'])
df1 = df.sort_values('date')
        .groupby('name')['date'].apply(lambda x: x.diff().max())
        .reset_index(name='max_diff')


text:
Q: C++ Undefined reference to a function I am using ubuntu 16.04 When I try to compile the program with
g++ -g main.cpp -o main

This is my g++ version
g++ --version

g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

I get this compilation error
main.cpp:8: undefined reference to `Helper::IsStringNumeric(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
collect2: error: ld returned 1 exit status

main.cpp:
#include "Helper.h"
#include <iostream>
#include <vector>

int main()
{
    std::cout << Helper::IsStringNumeric("200");
}

Helper.h
#ifndef HELPER_H
#define HELPER_H

#include <vector>
#include <string>
class Helper
{
private:
    /* data */
public:

   static bool IsStringNumeric(const std::string &str);

};

#endif

Helper.cpp
#include "Helper.h"
#include <string>
#include <algorithm>
bool Helper::IsStringNumeric(const std::string &str)
{
    std::string::const_iterator iterator = str.begin();

    while (iterator != str.end() && std::isdigit(*iterator))
    {
        ++iterator;
    }
    return !str.empty() && iterator == str.end();
}

My cpp and header files seem right , So I am not sure why I am getting errors

A: Adding #include "Helper.h" to your main.cpp makes the declaration of Helper::IsStringNumeric visible to the compiler, but you still need to compile Helper.cpp to object code in order to make the definition of Helper::IsStringNumeric available when you link your main program.
You can either compile each translation unit to an object code file and then link them:
g++ -g -o main.o -c main.cpp
g++ -g -o Helper.o -c Helper.cpp
g++ main.o Helper.o -o main

or (for simple programs) do it all in one step
g++ -g main.cpp Helper.cpp -o main


text:
Q: How can I allow a User to set which friend will be able to see their data? How can I allow a User to set which friend will be able to see their data?

A: There is no off-the-shelf answer to the this question, other than "design, develop, and deploy a server system that offers data sharing with users that are set up as a user's 'friends'."
It sounds to me like you have an original app idea that you will need to research and implement. If you are new to software development a multi-user client/server app is way, way, WAY beyond your abilities.
Come to think of it, the answer is really "hire a developer to help you come up with a functional design, technical spec, and implementation for your product idea."


text:
Q: Architecture used by dropbox I want to know whether client-server or peer-to-peer architecture is used by dropbox.
Here my doubt lies:
Suppose we have two systems which are synced via dropbox.

System1: dropbox > Folder_A > file_1
System2: dropbox > Folder_A > file_1

Initially both are synced. Suppose now, User on System1 adds a file_2 in Folder_A. Now this file gets uploaded to dropbox server. But my question is how does server notifies System2 about file_2.
I am seeing Observer Pattern being used here. But Is Pull or Push mechanism used ??

Point1: Does dropbox client on System2 polls dropbox server after some interval to get updates.
Point2: Dropbox server pushes the file on system2 itself.
Point3: All systems including dropbox central system is considered as a peer. peer-to-peer network is formed. dropbox central peer controls which file to be sent to which system.

PS: My question is not specific to dropbox but all the file sync service provider sites. I just used dropbox as reference.

A: I suspect a pull mechanism is used as there are too many firewall issues in push this article strongly suggests that pull is used. Of course, the easiest way to be sure would be to look at a wireshark trace.

A: dropbox uses push mechanism.Also it has
Constant TCP connection to notification server by Dropbox client used for changes that are performed elsewhere.client eventually requests for new changes and server responds at every 60 seconds in case of no change .new request is sent as soon as response comes from server.Changes on the central storage are instead advertised as soon as they are performed.

A: I dont know much but i think dropbox (or other similar sites) use push mechanism. Because in pull mechanism there will be lot of unnecessary calls. please correct me if i am wrong.


text:
Q: Margins got bugged (elements are buggy) when image inside div is centered horizontally and vertically I have 2 images below each other. I want them to be displayed centered horizontally and vertically inside parent div. Problem is that second element won't fit to parent div.
This is what I want:

and this is what I have now:

Here is code that I am using:
HTML:

CSS
#slika {
border: solid 2px;
display: table;
float: left;
height: 126px;
width: 111px;
text-align: center;
vertical-align: middle;
}
.img-wrapper {
display: table-cell;
vertical-align: middle;
}
img {
max-width: 100%;
}

jsFiddle: HERE

A: You need to make it position: absolute; to take it out of the document flow. The container #silka needs to be set to position: relative; to ensure the image is positioned relative to it rather than the viewport.

#slika {
    position: relative;
    border: solid 2px;
    display: table;
    float: left;
    height: 126px;
    width: 111px;
    text-align: center;
    vertical-align: middle;
}
.img-wrapper {
    display: table-cell;
    vertical-align: middle;
}
.topImage {
    position: absolute;
    left: 0;
    top: 0;
}
img {
    max-width: 100%;
}

JS Fiddle: http://jsfiddle.net/k84mgLnt/


text:
Q: scrapy is there a way to print json file without using -o -t parameters I am usually calling my spider like this:
scrapy crawl Spider -o fileName -t json

and I got the correct data printed in the fileName file as json formated.
Now I want to call my spider like this:
scrapy crawl Spider

my question
is there a way to print the output to a file without using the -o -t parameters?

A: Yes it can be done. add this to your settings
FEED_EXPORTERS = {
 'jsonlines': 'scrapy.contrib.exporter.JsonLinesItemExporter',
}
FEED_FORMAT = 'jsonlines'
FEED_URI = "NAME_OF_FILE.json"

For reference
http://doc.scrapy.org/en/latest/topics/feed-exports.html

A: Here is how i did it in scrapy 2.6.1
def open_spider(self, spider: YellowpagesCategorySpiderSpider):
    feeds = spider.settings.attributes['FEEDS'].value
    output_file_names = list(feeds)
    if len(output_file_names) > 1:
        raise RuntimeError(f"Only one output file is allowed, but {len(output_file_names)} were found")
    self.output_file_name = output_file_names[0]


text:
Q: Public Desktop icons plus more not showing We have one user on one computer that all of the Public Desktop icons is missing from her computer, plus  things like recycle bin. Her personal icons are showing as they should, just not the public and system ones.
I cannot seem to find any one else with the problem on Google. Has anyone ever run into this?

A: Check whether the common desktop icons are enabled under "Control Panel > Personalization > Change Desktop Settings". If the icons are not selected, then check all the icons to be displayed in the desktop.

Hope this helps

A: I had the same problem where (Desktop context menu) → View → Show Icons and the check boxes in Desktop Icon Settings didn't seem to matter.
I began to suspect HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Bags\1\Desktop because my remaining icons went all over the place. I ended up deleting it - after exporting it - and restarting the computer. All of the icons came back in their default locations.
I also deleted Users\my username\AppData\local\IconCache.db, though I don't think that it did anything because I had tried it before.


text:
Q: Bind Angular inputs/outputs via data attributes Is it possible to bind input and output properties using data attributes?
I'm trying to see if we can use Angular 2+ from within a number a different environments where the html editor strips out unknown tags. So, this <ng-test [inTest]="test" (outTest)="test()">NG Test</ng-test> becomes just
NG Test
 after the editor processes the code.
The same question would apply to *ngIf and *ngFor etc. The html editors will strip those away as well.
Does anyone know if this is possible?

A: The Editors like CKEDITOR already covered the configuration for allowed content (elements,attributes).
https://docs.ckeditor.com/#!/guide/dev_advanced_content_filter


text:
Q: Commutativity of the product of two subgroups in a finite group I want to prove that for subgroups $A,B \leq G$ where $G$ has finite order and $A$ has the property $\forall x \in G, a \in A\;\exists n \in\mathbb{Z}: x(ax^{-1})^n \in A$, $AB$ and $BA$ are equal, even though they need not be groups in general.
It is clear that we only need to show that one of the products is a subset of the other; if we know that $AB \subseteq BA$, it follows that $AB \subseteq BA = ((BA)^{-1})^{-1} = (A^{-1}B^{-1})^{-1} = (AB)^{-1}$, thus $AB \subseteq (AB)^{-1}$. Since clearly, $|AB| = |(AB)^{-1}|$, it would follow that $AB = BA$ because $G$ is finite (the case $BA \subseteq AB$ can be proved similarly). I also know that if either $A$ or $B$ is a normal subgroup, then $AB$ is a group and $AB = BA$ follows trivially. In this case, though, $AB$ need not be a group and I don't know how to prove the statement from here.

A: Choose $x=ba$, giving $bab^{-n} \in A$ for some $n$, so $ba \in AB$, and hence $BA \subseteq AB$. Since $G$ is finite, this implies that they are equal.


text:
Q: _construct in C, a macro used in an oop project Recently, I start to learn  object-oriented programming by using C.
I found some interesting material on the web. One of those is QMonkey/OOC-Design-Pattern repository on Github.
https://github.com/QMonkey/OOC-Design-Pattern
Here is my question :
Below is the base.h included in QMonkey/OOC-Design-Pattern.
This is the base macro used in this OOP C project.
I found many explanations about #,##,offsetof,and container_of.
The only thing I can't figure it out is the usage of _destruct and _construct.Where may I find their explanation?
Thanks for any help.
#ifndef BASE_H
#define BASE_H

#include <stdlib.h>
#include <stddef.h>

// clang-format off
#define container_of(ptr, type, member)                 \
    ({                              \
        const typeof(((type *)0)->member ) *__mptr = (ptr); \
        (type *)((char *)__mptr - offsetof(type,member));   \
    })

#define new(TYPE, args...) TYPE ## _construct(malloc(sizeof(TYPE)), ## args)
#define delete(TYPE, ptr)   do              \
                {               \
                    TYPE ## _destruct(ptr); \
                    free(ptr);      \
                }               \
                while(0)
// clang-format on

#endif

A: _construct and _destruct are just suffixes that are appended to the class name using the token pasting operator, ##. So if TYPE is MyClass then there will be constructor/destructor functions called MyClass_construct and MyClass_destruct.


text:
Q: Setting up a developing environment with appfog I am usually developing php applications locally and upload them to the server with ftp.
I am examine appfog as an alternative I want though to set up the developing enviroment
on localhost and use the same database with the staging and production.
Is that possible or do I have to use another service to host my database and use the appfog for the deployment.

A: If you are already using a hosted database service for your app, then you can use the same database on both local and production servers. There are many binds available on AppFog.
But if you are going with SQLite, you should consider using a persistent database solution. It is not recommended on production environment in AppFog. Every time you update your app, your SQLite database will be blown away.
Since AppFog databases are not externally accessible, you'll have to tunnel into them. You will find more information here:
http://blog.appfog.com/how-to-manage-your-appfog-database-from-your-desktop-on-the-other-side-of-the-world/


text:
Q: Dictionary in swift 3.0 giving nil when tried to add a dict var dist: Dictionary<String, NSObject>!
var bigDist : Dictionary<String, Dictionary<String, NSObject>>!

self.bigDist["1" as String] = self.dist

When I try to do this, I get an error:
fatal error: unexpectedly found nil while unwrapping an Optional value

Data set for self.dist:
Optional(["hits": 0, "name": India lags behind China in consumer spends: Stefano Ricci's Jackie Manglani, "web": Livemint, "id": -1655, "like": 0, "iurl": http://www.livemint.com/rf/Image-222x148/LiveMint/Period2/2017/02/21/Photos/Processed/jackiemanglani2-kXhC--621x414@LiveMint.JPG, "notify": 0, "date": 201655200217, "active": 1, "type": Mark, "dateAdded": 20/02/2017, "url": http://www.livemint.com/Consumer/3NT8Vbw7BcGeoPJNMoyK5H/India-lags-behind-China-in-consumer-spends-Stefano-Riccis.html])

A: Your variable bigDist is an implicitly unwrapped optional. (You declare it with) your_type!.
That means that:

*

*It can contain a nil.

*You don't need to unwrap it using ? or !.

*If you reference it and it contains nil, you'll crash.

Number 3 is what's happening.
You need to create an empty dictionary. Try getting rid of the ! in the declaration, and creating an empty dictionary when you declare it:
var bigDist : Dictionary<String, Dictionary<String, NSObject>> = [:]

A: You did not initialize bigDist:
var dist: Dictionary<String, NSObject>? = nil
var bigDist = Dictionary<String, Dictionary<String, NSObject>>()

self.bigDist["1"] = self.dist

The code could be swiftier anyway. Using [String: NSObject] instead of Dictionary<String, NSObject> (which is exactly the same) makes the code easier to read and can prevent such a mistake like you did.
var dist: [String: NSObject]? = nil
var bigDist = [String: [String: NSObject]]()

self.bigDist["1"] = self.dist


text:
Q: Changing state in array state redux react native The inital state I have for result list from server will be on result
var InitialState = Record({
   result:[]
})

The result from server is list of search result.
Example array result
[{id:1 ,Bookmark:true},
{id:2 ,Bookmark:true}],
.....

My reducer
case SET_BOOKMARK:
      return state.setIn(['result', 'Bookmark'], action.payload.total)

I want to update the specific bookmark state when user bookmark specific id, How to achive that? How to reducer look like?

A: Here is an example for your case
const { setIn } = require('immutable@4.0.0-rc.9')

const state = {"results": [{id:1 ,Bookmark:true},
{id:2 ,Bookmark:true}]};

function findElementIndex(arr, key, value) {
  for (let i = 0; i < arr.length; i++)
    if (arr[i][key] === value)
      return i;
}
const newState = setIn(state,
    ['results', findElementIndex(state.results, 'id', 1), 'Bookmark'], false);

console.log(newState);


text:
Q: Count phrases frequency in Python dataframe The data I have is stored in a pandas dataframe - please see a reproducible example below. The real dataframe will have more than 10k lines and a lot more ords / phrases per line.
I'd like to count the number of times each two-word phrase appears in column ReviewContent. If this were a text file and not the column of a dataframe I would use NLTK's Collocations module (something along the lines of answers here or here ). My question is: how can I transform column ReviewContent into a single corpus text?
import numpy as np
import pandas as pd

data = {'ReviewContent' : ['Great food',
'Low prices but above average food',
'Staff was the worst',
'Great location and great food',
'Really low prices',
'The daily menu is usually great',
'I waited a long time to be served, but it was worth it. Great food']}

df = pd.DataFrame(data)

Expected output:
[(('great', 'food'), 3), (('low', 'prices'), 2), ...]

or
[('great food', 3), ('low prices', 2)...]

A: As a sequence/iterable, df["ReviewContent"] is structured exactly the same as the result of applying nltk.sent_tokenize() to a file of text: A list of strings containing one sentence each. So just use it the same way.
counts = collections.Counter()
for sent in df["ReviewContent"]:
    words = nltk.word_tokenize(sent)
    counts.update(nltk.bigrams(words))

If you aren't sure what to do next, that's not connected to using a dataframe. For counting bigrams you don't need the collocations module, just nltk.bigrams() and a counting dictionary.

A: I suggest using join:
corpus = ' '.join(df.ReviewContent)

Here's the result:
In [102]: corpus
Out[102]: 'Great food Low prices but above average food Staff was the worst Great location and great food Really low prices The daily menu is usually great I waited a long time to be served, but it was worth it. Great food'

A: Using Pandas version 0.20.1+, you can create SparseDataFrame directly from sparse matrixes:
from sklearn.feature_extraction.text import CountVectorizer

cv = CountVectorizer(ngram_range=(2,2))

r = pd.SparseDataFrame(cv.fit_transform(df.ReviewContent),
                       columns=cv.get_feature_names(),
                       index=df.index,
                       default_fill_value=0)

Result:
In [52]: r
Out[52]:
   above average  and great  average food  be served  but above  but it  daily menu  great food  great location  \
0              0          0             0          0          0       0           0           1               0
1              1          0             1          0          1       0           0           0               0
2              0          0             0          0          0       0           0           0               0
3              0          1             0          0          0       0           0           1               1
4              0          0             0          0          0       0           0           0               0
5              0          0             0          0          0       0           1           0               0
6              0          0             0          1          0       1           0           1               0

   is usually    ...     staff was  the daily  the worst  time to  to be  usually great  waited long  was the  was worth  \
0           0    ...             0          0          0        0      0              0            0        0          0
1           0    ...             0          0          0        0      0              0            0        0          0
2           0    ...             1          0          1        0      0              0            0        1          0
3           0    ...             0          0          0        0      0              0            0        0          0
4           0    ...             0          0          0        0      0              0            0        0          0
5           1    ...             0          1          0        0      0              1            0        0          0
6           0    ...             0          0          0        1      1              0            1        0          1

   worth it
0         0
1         0
2         0
3         0
4         0
5         0
6         1

[7 rows x 29 columns]

If you simply want to concatenate the strings from all rows into a single one, use Series.str.cat() method:
text = df.ReviewContent.str.cat(sep=' ')

Result:
In [57]: print(text)
Great food Low prices but above average food Staff was the worst Great location and great food Really low prices The daily me
nu is usually great I waited a long time to be served, but it was worth it. Great food


text:
Q: I can not delete Snapshots (Googleplay services C++ 1.3 SDK) My code is pretty simple:
auto response = Snapshots.FetchAllBlocking();
    if (IsSuccess(response.status))
    {
        for (auto& fetch : response.data)
        {
            Snapshots.Delete(fetch);
        }

This throws an exception:
01-27 01:14:11.675: E/GamesNativeSDK(3448): Exception in com/google/android/gms/games/snapshot/Snapshots.delete: java.lang.IllegalArgumentException: Buffer is closed..
What does this mean?
BTW. in my App and client I have two snapshots, and one of them is super corrupted: I can not open it, always returns ERROR_INTERNAL and IDK what can I do.

A: You have to open it with a call to Snapshots().Open before calling Snapshots().Delete
This is what it means by the buffer being closed.


text:
Q: Conda-Build: Unsatisfiable dependencies for platform osx-64: {"torch[version='>=0.4']"} I'm new to building conda package. I've uploaded the package to PyPI, so I followed this documentation about building conda from pip package. It works when I tried building pyinstrument from pip, but I got the following error when I tried building my package.
conda_build.exceptions.DependencyNeedsBuildingError: Unsatisfiable dependencies for platform osx-64: {"torch[version='>=0.4']"}

I found a similar issue here, but adding channel didn't fix my issue since pytorch exists in default channel.
Here is my meta.yml file:
{% set name = "scvi" %}
{% set version = "0.1.2" %}
{% set file_ext = "tar.gz" %}
{% set hash_type = "sha256" %}
{% set hash_value = "ca87155662d85605f86c5e86b7b9f64d881b882177b9642fff8f0ea215c6cb1a" %}

package:
  name: '{{ name|lower }}'
  version: '{{ version }}'

source:
  fn: '{{ name }}-{{ version }}.{{ file_ext }}'
  url: https://pypi.io/packages/source/{{ name[0] }}/{{ name }}/{{ name }}-{{ version }}.{{ file_ext }}
  '{{ hash_type }}': '{{ hash_value }}'

build:
  number: 0
  script: python setup.py install --single-version-externally-managed --record=record.txt

requirements:
  run:
    - python 3.6
    - setuptools
    - numpy>=1.0
    - torch>=0.4
    - matplotlib>=2.0
    - scikit-learn>=0.18
    - scipy>=1.0
    - h5py>=2.8
    - pandas>=0.2
    - loompy>=2.0

test:
  imports:
    - scvi
    - scvi.dataset
    - scvi.metrics
    - scvi.models
  requires:
    - pytest

about:
  home: https://github.com/YosefLab/scVI
  license: MIT
  license_family: MIT
  license_file: 'LICENSE'
  summary: Single-cell Variational Inference
  description: Single-cell Variational Inference
  doc_url: https://scvi.readthedocs.io
  dev_url: https://github.com/YosefLab/scVI

Any possible solutions or suggestions on which direction I should look into would be very helpful. Thanks!

A: Turns out that there's a bug in the automatically generated meta.yml file by running conda skeleton pypi {package name}. In meta.yml, it should be pytorch instead of torch.


text:
Q: Find Minimum value of $P=\frac{1}{1+2x}+\frac{1}{1+2y}+\frac{3-2xy}{5-x^2-y^2}$ Given: $x,y\in (-\sqrt2;\sqrt2)$ and $x^4+y^4+4=\dfrac{6}{xy}$
Find Minimum value Of $$P=\frac{1}{1+2x}+\frac{1}{1+2y}+\frac{3-2xy}{5-x^2-y^2}$$
Could someone help me ?

A: Define the function:
$$
P(x,y) = \frac{1}{1+2x}+\frac{1}{1+2y}+\frac{3-2xy}{5-x^2-y^2}
$$
No clue without an overview. We use brute force graphics :

Mind the circle and the straight lines; they are the singularities in the function $P(x,y)$ . Also note that the whole problem has a mirror symmetry with respect to the line $\;y=x$ . Our viewport is:

  xmin := -4; xmax := +4;
  ymin := -4; ymax := +4;

First investigate where $P$ is positive ($\color{red}{red}$) and where it is
negative ($\color{green}{green}$) . We seek a minimum, so attention will be
preferably be restricted to the domains where $P(x,y)$ is $\color{green}{negative}$.
Then define the curve (yellow in the picture). The minimum of $P(x,y)$ must
be at this curve $C$ :
$$
x^4+y^4+4=\dfrac{6}{xy} \qquad \mbox{or} \qquad C(x,y) = xy \, (x^4+y^4+4)-6=0
$$
The coordinate axes are in black, the area $\;x,y\in (-\sqrt2;\sqrt2)\;$
to be investigated is the square enclosed by the $\color{blue}{blue}$ lines.
Now it is immediately clear that the domain to be investigated in the end
is the one enclosed by the white borders: $\;x,y\in (-\sqrt2;-1/2)$ .
The white bordered part of the picture is enlarged here:

Some contour lines of the function $P(x,y)$ are drawn in black; the curve
$C(x,y) = 0$ is drawn in $\color{green}{green}$. The line of symmetry $y=x$
is colored yellow; extrema of the function $P(x,y)$ are marked with
$\color{red}{red}$ colored dots. A special place is the maximum of $P$ at
the curve $\,C=0$ , the intersection point of the green and the yellow line :
$$
C(-1,-1) = 0 \qquad \mbox{and} \qquad P(-1,-1) = -\frac{5}{3}
$$
The curve $\;C(x,y)=0\;$ intersects the lines $\;x=-\sqrt{2}\;$
and $\;y-\sqrt{2}\;$ just below $\;y=-1/2\;$ and left of $\;x=-1/2\;$ , because
these points are in the negative zone of the function $\;C(x,y)$ :
$$
C(-\sqrt{2},-1/2) = C(-1/2,-\sqrt{2}) = \frac{129}{16}-6\sqrt{2} = -.422781372 < 0
$$
A local maximum ( $\color{red}{red \; dot}$ ) has been detected (but only)
numerically:
$$
P(-1.194436916,-1.194436916) = -1.371703810
$$
Last but not least: the minimum value that is asked for. Because the interval
$(-\sqrt2;\sqrt2)$ is defined by the OP as an open interval (?) , that's a
tricky one. If the interval were closed, then I would say the two minima are
at the solutions of $\;C(-\sqrt{2},y)=0\;$ or $\;C(x,-\sqrt{2})=0\;$ :
$$
y^5 + 8y + 3 \sqrt{2} = 0 \qquad \mbox{or} \qquad x^5 + 8x + 3 \sqrt{2} = 0
$$
A quintic which can be solved (only?) numerically : $\;y = -.5253289716 < -1/2$  or $\;x = -.5253289716 < -1/2$ . The minimum itself is (numerically) :
$$
P(-\sqrt{2},-.5253289716) = P(-.5253289716,-\sqrt{2}) = -19.73131147
$$
But I don't know how to properly handle the open interval, if it is meant as such.
$P(x,y)\;$ along the curve $\;C(x,y) = 0\;$ inside $\;x,y \in (-\sqrt2;-1/2)\;$
is a function $\;y = f(s)\;$ where $\;s\;$ is the arc length. We can plot the graph
of $\;y=f(s)$ . Due to the symmetry, it doesn't matter in which direction we
walk along the curve. It is seen that the maximum is indeed at $\;y=-5/3\;$ and
that the function is uniformly descending from there in both (symmetric) directions.

A: You could try this approach, although I think there is a simpler way.
Firstly, apply the change of variables
$$
v=x^4+y^4, \ w = \frac{1}{xy}
$$
in order to simplify the domain $D$ to
$$
D = \{\ v(w) = 6w-4\ : w \in (-\infty,-1/2) \cup (1/ 2,\infty)\ \}.
$$
The minimal value is now given by invoking the chain rule
\begin{align}
0 =& \frac{dP}{dw}\\
  =& \frac{dP}{dv} \cdot \frac{dv}{dw} \\
  =& \Big(\frac{\partial P}{\partial x} \cdot \frac{dx}{dv} + \frac{\partial P}{\partial y} \cdot \frac{dy}{dv}\Big) \cdot \frac{dv}{dw} \\
  =& \Big( \frac{\partial P}{\partial x} \cdot \frac{dv}{dx}^{-1} + \frac{\partial P}{\partial y} \cdot \frac{dv}{dy}^{-1}\Big) \cdot \frac{dv}{dw},
\end{align}
taking into account that the solution lies in the domain $D$.


text:
Q: Pull .txt file information into RESTful API URL [Ruby] So I am fairly new to Ruby and this may very well be answered elsewhere but I have searched high and low with nothing to show.
I am defining a module for a RESTful API framework and mostly things have gone well apart from trying to get a string from a .txt file into the actual API end point (before parameters)
MY code is this:
require 'rest-client'

module Delete

  def delete

    file = File.open("ST.txt", "r")
    sT = file.read,

    file = File.open("cR.txt","r")
    cR = file.read
    begin

      return RestClient.post({'https://testing.ixaris.com/paymentpartner/virtualcards/{cR}/delete'},
            { },
            {:A => sT,})
    rescue => e
      return e.response
    end

  end
end

The the first "ST.txt" into the "A parameter" works fine but I can't seem to get the "cR" string into the "{cR}" part of the end point.
Any help would be hugely appreciated!

A: I'm not quite sure which line the thing is on so I'm going to try for both.
For only one line files (with a guarantee it's only one line):
cr = File.read('cR.txt')

Which converts the entire content of the file into a string which is fine as there is only one line.
For multiline files you might want to try:
cr =
File.open('cR.txt', 'r') do |f|
  break unless f.each_line do |line|
    break if line =~ /\d*/ # regex for matching any numbers or whatever you want to use to match with like ==,>,<,>=,<=,!=
  end
end

Also, note that ruby implicitly returns from everything so unless you need to return explicitly from the middle of a method i.e. an if statement, you don't need to add return to everything.
Also, if you do a file.read, make sure to file.close when you're done with it, otherwise it won't be cleaned up till the garbage-collector runs and that could waste system resources; which is the advantage of doing a open file with a block as it automatically closes the file when the block is done.


text:
Q: Latex equations inside inkscape figure (.svg) increase figure width/make figure too big I have an image, let's use this one from my thesis:

that I include in my document using:
\begin{figure}
    \centering
    \includesvg[width=\textwidth]{zeeman}
    \caption{Caption}
    \label{fig:theory:zeeman}
\end{figure}

and it makes a nice image... except for the fact that clearly the width is calculated pre "compilation" and therefore is not correct:
.
I've looked at A link to the svg package documentation and on the tex exchange and all I can find are people who make neater images than me :D Is there a way I can ask latex to set the figure size post "compilation" or some other hack?
Thanks :)

A: I recommend svg2tikz, used as an plugin in Inkscape instead of \includesvg
There were some real problems with newer versions of Inkscape, but they were fixed last week so it works again.
The advantage is you get real tikz code, and can edit it as you see fit.  The tikz code is not without some flaws.  In particular, I've had to go in and rotate node labels manually -- but all those edits are straightforward if you're familiar with tikz.  You don't get "how do I fix stuff that's not quite right" mysteries to solve.
Another advantage is not having to use ShellEscape.


text:
Q: Compilation error "option-unknown" - unicode-math I am trying to use a CV template I got online. I really like it, but I am a bit of a noob and don't know how to resolve the errors when I compile.
I get this error first, I am not sure if there may be any more:

unicode-math.sty 385
  ! keyvalue error: "option-unknown"
  !
  ! Unknown option 'vargreek-shape' for package unicode-math.
  !
  ! See the keyvalue documentation for further information.
  !
  ! For immediate help type H .
  !...............................................
  l.385 \ProcessKeysOptions {unicode-math}

I have tried to look at resolutions online for similar problems, none of which helped very much. Is there a way I can modify it to make it compile?
This is the main code:
\documentclass[11pt, a4paper]{awesome-cv}
\fontdir[fonts/] % Specify the location of the included fonts
\colorlet{awesome}{awesome-red}
\renewcommand{\acvHeaderSocialSep}{\quad\textbar\quad}
\name{Claud D.}{Park}
\address{246-1002, Gwangmyeongmayrouge Apt. 86, Cheongna lime-ro, Seo-gu, Incheon-si, 404-180, Rep. of KOREA}
\mobile{(+82) 10-9030-1843}
\email{posquit0.bj@gmail.com}
\homepage{www.posquit0.com}
\github{posquit0}
\linkedin{posquit0}
\position{Software Engineer{\enskip\cdotp\enskip}Security Expert}
\quote{``Make the change that you want to see in the world."}
\makecvfooter{\today}{Claud D. Park~~~•~~~Résumé}{\thepage}
\begin{document}
\makecvheader
\input{cv-sections/education.tex}
\input{cv-sections/skills.tex}
\input{cv-sections/experience.tex}
\end{document}

Sorry, i don't even know where to begin to look and what parts you'd like me to show to you.

A: I managed to fix this issue by commenting out the below line in coverletter.cls and awesome-cv.cls
% comment out this line which causes this issue
%\RequirePackage[math-style=TeX,vargreek-shape=unicode]{unicode-math}

And add a new statement
% add this instead
\RequirePackage{unicode-math}

As Consuelo mentioned, the corresponding fix can be found in this git commit

A: There is a new version of the template.
Check here: https://github.com/posquit0/Awesome-CV/commit/6e8586270b203d5861377ba017f30cf16ed425cc
You have to replace line 1) with line 2) and you will get it fixed:
1) \RequirePackage[math-style=TeX,vargreek-shape=unicode]{unicode-math}
2) \RequirePackage{unicode-math}


text:
Q: Plotting 2D scatter plot from data in tsv file with ticks defined by user I want to plot a 2D scatter plot with the following details:
X axis ticks value as:
x = [0,30,60,90,120,150,180,210,240,270,300,330,359]

Yaxis ticks value as:
y = [0,10,20,30,40]

Now, I have the following data in a tsv file which I want to plot with respect to X axis such that A,B,C,D columns have different color schemes.
A              B               C              D
0
21.55741404    0
41.2249925     52.96216168     0
39.96376049    25.70840987     47.54439749    0
54.9600295     37.72928195     59.73455641    15.57652354
66.82671436    72.50071181     27.44853361    55.92679682
74.29259814    69.56620872     46.19494779    45.41791225

A values should lie where y = 10
B values should lie where y = 20
C values should lie where y = 30
D values should lie where y = 40

The output should be like the one as below:

Would really appreciate any help. Thanks

A: IIUC, I think you need sns.stripplot and melt.
import seaborn as sns
dfm = df.melt()
sns.stripplot(dfm['variable'], dfm['value'])

Output:


text:
Q: WPF Application that runs selenium tests Hi is there a way that I could create a WPF application which acts as the front end for my selenium test scripts. I have created regression tests using selenium and I was wondering if I could create a WPF application which would allow me to set parameters for tests and then run it from the same application? I usually run the tests from visual studio and it would be awesome if there was a way to create an application to run them instead

A: To sum up all the comments - since you are using NUnit there is a GUI runner that can do that for you. Depending on what UI you want to put as top layer, there are Windows Forms and ASP.NET MVC.
Here is how I did it with the later one:
var db = new ServerContext();
Build build = db.Builds.Find(BuildId);
var project = db.Projects.FirstOrDefault(p => p.Id.Equals(build.ProjectId));
string value = Value;
string gitDirrectory = Build.Workspace.Replace("\\", "/") + "/source";

//run NUnit tests
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = @"/c "+ gitDirrectory + @"/packages/NUnit.Runners.2.6.3/tools/nunit-console.exe " + gitDirrectory
        + value
        + " /include:" + project.Name.Replace(" team", String.Empty).Trim()
        + " >> " + Build.Log;
process.Start();
process.WaitForExit();

Feel free to use any part of the repo's code you find useful.


text:
Q: Changing screens when navigating in bottomnavigation bar error Hi Im new to flutter so please bear with me for asking too much nooby question. So I am currently developing an app, the first screen will be a Login/register screen then after a login or registration is directed, the actual main app screen is displayed I also set this screen as stateless and set a body to my HomePage.dart now on my HomePage.dart which is a stateful widget, which contains the navigation bar but for some reason, Im getting an error in
final List<Widget> _children [
    NavHome()
  ];

saying that the children is initialized. And Im confused since I followed the tutorial from medium exactly BUT with just a custom main screen (which appears after the main.dart)
the code for the actual main app screen is below:
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

import 'home.dart';

class MainScreen extends StatelessWidget {
  const MainScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: HomePage(),
    );
  }
}

the code for Home.dart is below which says the children variable isnt initialized
import 'package:flutter/material.dart';
import 'package:vmembershipofficial/screens/nav_home.dart';

class HomePage extends StatefulWidget {
    static final String id = 'homepage';
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _currentTab = 2;
  final List<Widget> _children [
    NavHome()
  ];

  void onTabTapped(int index) {
    setState(() {
      _currentTab = index;
    });
  }
  @override
  Widget build(BuildContext context) {
    return  Scaffold(
        body: _children[_currentTab],
        bottomNavigationBar: BottomNavigationBar(
          onTap: onTabTapped,
          type: BottomNavigationBarType.fixed,
          currentIndex: _currentTab, //makes a new variable called current Tab
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.search, size: 30.0),
              title: Text('Search', style: TextStyle(fontSize: 12.0),),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.favorite),
              title: Text('Favorites', style: TextStyle(fontSize: 12.0),),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text('Home', style: TextStyle(fontSize: 12.0),),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.message),
              title: Text('Messages', style: TextStyle(fontSize: 12.0),),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.account_circle),
              title: Text('Account', style: TextStyle(fontSize: 12.0),),
            ),
          ],
        ),
      );
  }
}

NOTE: I just want the bottom navigation bar to change to the NavHome, or NavProfile when I tapped on different tabs. I just cant seem to find a way why the _children variable isnt initialized.

A: You're almost there!
What went wrong
final List<Widget> _children [ // Missing = sign
   NavHome()
];

What you can do
Convert the code snippet above to:
final List<Widget> _children = [ // Add = sign here
   NavHome(),
   NavProfile(),
   // Add more screens here
];

I created a simple app for you, which mocks your use case that you need to switch between NavHome and NavProfile.
main.dart
import 'package:flutter/material.dart';

void main() => runApp(ExampleApp());

class ExampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Example App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  static final String id = 'homepage';
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _currentTab = 0;
  final List<Widget> _children = [
    RedPage(),
    BluePage(),
  ];

  void onTabTapped(int index) {
    setState(() {
      _currentTab = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _children[_currentTab],
      bottomNavigationBar: BottomNavigationBar(
        onTap: onTabTapped,
        type: BottomNavigationBarType.fixed,
        currentIndex: _currentTab,
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.favorite),
            title: Text(
              'Red',
              style: TextStyle(fontSize: 12.0),
            ),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text(
              'Blue',
              style: TextStyle(fontSize: 12.0),
            ),
          ),
        ],
      ),
    );
  }
}

class RedPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        color: Colors.red,
      ),
    );
  }
}

class BluePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        color: Colors.blue,
      ),
    );
  }
}

I have also noticed that you have 5 widgets in your bottom navigation bar, feel free to add placeholders so you won't get RangeError exception whenever you tap on tabs without the counterpart screen/s.
Hope this helps.


text:
Q: Hibernate Lazy Loading Issue I mapped this entity in Hibernate 5
class A {
    private String code;
    private B child;

    @LazyToOne(LazyToOneOption.PROXY)
    @ManyToOne(fetch=FetchType.LAZY)
    @NotFound(action=NotFoundAction.IGNORE)
    @JoinColumns({...})
    public B getChild() { ... }
}

And my query to load only A is:
from A where a.code like :q

With this configuration Hibernate makes a select on A and on B entities.
I don't want it to load B but only A
What am I missing?

A: I had the same problem, which is caused by Hibernate ignoring the FetchType.LAZY, if NotFoundAction.IGNORE is defined.
After some googling I found a workaround:
http://chekkal.blogspot.com/2012/09/hibernate-lazy-loading-and-notfound.html
public FieldType getField() {
    if(!Hibernate.isInitialized(field)) {
        try {
            Hibernate.initialize(field);
        }catch(EntityNotFoundException one) {
            field=null;
        }
    }
    return field;
}

In Hibernate 5.4.2 the exception has changed to EntityNotFoundException, but this workaround seems to work for me.


text:
Q: isFullScreenSupported always true for monitors Given the following code
 GraphicsDevice screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0];
 if (screen.isFullScreenSupported()) {
      //is it always true for monitors?
 }

Is screen.isFullScreenSupported() always true for monitors?

A: No, it may not be true.
The SecurityManager might disallow you the full screen control. Mainly because one could easily fake whole screen in order to grab a password from not-suspecting user (you could mock a bank website).
It can be false:

*

*in an applet

*in a WebStart Application

*while running in headless mode

JavaDOC of GraphicsDevice.isFullScreenSupported:

Returns true if this GraphicsDevice supports full-screen exclusive
  mode. If a SecurityManager is installed, its checkPermission method
  will be called with AWTPermission("fullScreenExclusive").
  isFullScreenSupported returns true only if that permission is granted


text:
Q: Kinesis Firehose writes to S3 cloud watch subscription filter but the files are not readable I've noticed that Kinesis firehose writes files to kinesis but the files are in non readable human format (probably compressed or binary).
I didn't choose to zip or to encrypt them.
How can i convert the content of this files for human readable format?

A: Cloud watch logs pipe with firehose to S3  are being automatically  gzip compressed when export to designated S3 bucket.
But Firehose wont add the .gz extension to the file so when you download it from s3 bucket you need to manually add the gz extension to the file.
And then decompress the file delivered to s3 bucket first before opening it.


text:
Q: Two way data binding not working for  I am using  with  in Angular 5. I want to bind the complete JSON object on selecting the dropdown value. So I am facing the issue because of that, two-way data binding is not working for it. When I am supposed to edit the object, I am not seeing its type in the dropdown. Below is my code:
HTML:
<select class="w3-input dropDown form-control" [(ngModel)]="selectedTypes"  name="option" (change)="onSelectedType()">
               <option *ngFor="let type of attributeTypes"
                [ngValue]="type"
                [selected]="selectedTypes.title === type.title ? type.title : null">
                {{type.title}}</option>
            </select>

TS:
this.http.get(this.localClient + "attributes?q[_id]=" + this.attributeId, { headers: this.rqstHeader })
              .map(res => res.json())
              .subscribe(data => {
                this.attribute.title = data[0].title;
                this.selectedTypes = data[0].type;
                console.log(data);
             });

Here, 'this.attribute.title is working fine as I have bound it to a textbox. But 'selectedTypes' not working as expected on Edit Mode.
Any help would be highly appreciated.

A: In Angular 5.x *ngFor was remove, use NgForOf Instead Of *ngFor.
TS File
this.ResponseFromAPI = [
    {name : 'Name1', value : 'Value1'},
    {name : 'Name2', value : 'Value2'},
    {name : 'Name3', value : 'Value3'}
];

Html File
<ng-template ngFor let-item [ngForOf]="ResponseFromAPI" let-i="index">
    <option [ngValue]="item.value"  >{{item.name}}</option>
</ng-template>

Hope so it's help. :)


text:
Q: Users image in my site programatically How to get the users image in my site programatically?
I need to show image of the logged-in user in my webpart.

A: The function below will get you the UserProfile based on the accountName
public static UserProfile GetUserInfo(string AccountName)
{
    UserProfile profile = null;
    SPServiceContext serviceContext = SPServiceContext.Current;
    UserProfileManager profileManager = new UserProfileManager(serviceContext);
    if (AccountName != string.Empty)
    {
        profile = profileManager.GetUserProfile(AccountName);
    }
    else
    {
        profile = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.RawSid);
    }
    return profile;
}

The picture URL will be in
userProfile[PropertyConstants.PictureUrl];

A:   SPFieldUrlValue fieldUrl = new SPFieldUrlValue(item["Links"].ToString());
  url = fieldUrl.Url;
  string[] splittedValues = url.Split('=');
  string accountName =splittedValues[1].ToString();
  accountName.Replace("%5C","\\");

  ServerContext ServerContext = ServerContext.GetContext(site);
  UserProfileManager profileManager = new UserProfileManager(ServerContext);
  UserProfile spUser = profileManager.GetUserProfile(accountName);
  IDictionaryEnumerator userProperties = spUser.GetEnumerator();

  string picture = spUser["PictureURL"].Value.ToString();
  row["Links"] = url;
  row["URL"] = picture;


text:
Q: Angular-gridster: Dynamically add in an Angular 1.5 component from another I've created a dynamic dashboard where widgets can be added,edited and deleted. It is using angular-gridster and directives that dynamically adds other directives by using the link function and $compile. I am now trying to move everything over to components and keep the same dynamic ability.
This is the new main component:-
var dashboard = {
templateUrl: 'js/components/dashboard.html',

controller: function () {

this.gridsterOpts = {
  columns: 12,
  margins: [10, 10],
  outerMargin: true,
  pushing: true,
  floating: true,
  swapping: true,
  resizable: {
    enabled: true,
    handles: ['n', 'e', 's', 'w', 'ne', 'se', 'sw', 'nw'],
  }
};
this.widgets = [
  {

    sizeX: 4,
    sizeY: 3,
    domain: 'COMP1',
    title: 'RTEMS Load',
    component: '<rtems-bullet></rtems-bullet>',
    // content: '<nvd3 options="$ctrl.options" data="$ctrl.result"></nvd3>',
    type: 'AgentsPerRTEMS'
  },
  {

    sizeX: 4,
    sizeY: 3,
    domain: 'COMP1',
    title: 'Agents Per RTEMS',
    component: '<rtems-agents></rtems-agents>',
    // content: '<nvd3 options="$ctrl.options" data="$ctrl.result"></nvd3>',
    type: 'AgentsPerRTEMS'
  },
];
}};

angular
.module('app')
.component('dashboard', dashboard);

This dashboard component has the following markup:-

                    {{widget.title}}

                        ADD COMPONENT HERE

I am trying to add the component in the panel-body but everytime I try things like {{widget.component}} a string is inserted rather than a dom object - not surprisingly I guess.
Any ideas how I can get the widget.component instantiated as an actual component rather than a literal string?
* UPDATE *
I am now trying this as an option :-

    <widget-ctrl  dom="widget.domain" widget="widget.component">
    </widget-ctrl>

The widget attribute holds my component template: .
Is there anyway I can make my widget-ctrl component return the value of the attribute instead of the literal 'widget.component'?
This is the component:
var widgetCtrl = {
        transclude: true,
        bindings: {
    widget: '<',
    dom: '<'
  },
  controller: function () {
    console.log(this.widget);

  },

  template: function ($element, $attrs) {
    console.log($attrs.widget);

    return $attrs.widget;
  },
};

angular
  .module('app')
  .component('widgetCtrl', widgetCtrl);

The console.log in the controller function logs out the value of widget whereas the template function logs out the literal. Is there anyway I can change that behaviour?
Thanks for any steer on this.