text:
Q: Compute: f(n) = f(n - 1) + f(n - 2) + f(n - 3) + n * n * (n + 1) For the recurrence relation:
f(0) = p
f(1) = q
f(2) = r
For n > 2,
f(n) = a * f(n - 1) + b * f(n - 2) + c * f(n - 3) + n * n * (n + 1)

Given some n <= 10 ^ 18, I want to find out f(n) using an approach that runs in O(log n) time.
If f(n) = f(n - 1) + f(n - 2) + f(n - 3), we could solve it in O(Log n) time using Matrix Exponentiation. But the n * n * (n + 1) term complicates the problem.

A: That matrix equation can still be set up, but some powers of n need to be in it as well:
|F(n-0)|   | a, b, c, 1, 1, 0, 0 |   |F(n-1)|
|F(n-1)|   | 1, 0, 0, 0, 0, 0, 0 |   |F(n-2)|
|F(n-2)|   | 0, 1, 0, 0, 0, 0, 0 |   |F(n-3)|
|(n+1)³| = | 0, 0, 0, 1, 3, 3, 1 | * | n³   |
|(n+1)²|   | 0, 0, 0, 0, 1, 2, 1 |   | n²   |
| n+1  |   | 0, 0, 0, 0, 0, 1, 1 |   | n    |
| 1    |   | 0, 0, 0, 0, 0, 0, 1 |   | 1    |

Then do exponentiation by squaring, and finally multiply the resulting matrix by this vector:
[r, q, p, 27, 9, 3, 1].T

As usual this can all be done with modular arithmetic if the final answer is requested modulo M, which it probably will be otherwise the values get way too big for n near 1018.


text:
Q: How to execute callback of async call on Java's main thread? Is there a way to force the execution of the callback to be executed on the main thread?
For example, in the following code:
public static void main(String[] args) throws Exception {
    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
    Executor main_executor = MoreExecutors.directExecutor();

    Callable<String> asyncTask = () -> {
        Thread.sleep(1000);
        return "Task executed by " + Thread.currentThread().getName().toString();
    };

    ListenableFuture<String> listenableFuture = executor.submit(asyncTask);

    Futures.addCallback(listenableFuture, new FutureCallback<String>() {
        public void onSuccess(String result) {
            System.out.println(
                    "Callback executed by " + Thread.currentThread().getName() + " with return value " + result);
        }

        public void onFailure(Throwable thrown) {
            thrown.printStackTrace();
        }
    }, main_executor);

    Thread.sleep(2000);

    try {
        String result = listenableFuture.get();
        System.out.println("Future value was retrived by " + Thread.currentThread().getName().toString()
                + " with return value " + result);
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    Thread.sleep(1000);
    executor.shutdown();
}

The output is:
Callback executed by pool-1-thread-1 with return value Task executed by pool-1-thread-1
Future value was retrived by main with return value Task executed by pool-1-thread-1

which mean the callback was execute by a worker thread, even though I specified the main thread while adding the callback, what am Imissing?

A: You can't do this.  The main thread is busy running main.
directExecutor doesn't mean "the main thread," it means "run on whichever thread finished the last piece of work."

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does \newcommand{\°}{& \cmsi} not work? I have in my generated LaTeX Document
\newfont{\cmsi} {cmssqi10}

Then I have a first \newcommand which does not work
\newcommand{\°}{& \cmsi}

And I have a second command which works fine.
\newcommand{\0}{& \cmss}

If I change the \° by a \1 all works fine. BUT ...
The issue is that I would like to keep the \° as I do not like to change this in a larger porting project in DB's, DOKs (HeaderFiles) and CODE (LegacyCode) where the "°" is also used as separator sometimes.
If I replace the \° by a \1 all works fine and PDF is generated later.

! Misplaced alignment tab character &.
<argument> &
             \cmsi
l.20 \newcommand{\°}{& \cmsi}

This is pdfTeX, Version 3.14159265-2.6-1.40.16 (MiKTeX 2.9) entering
extended mode (DO_00012580_PA1_20151231.4.DOK LaTeX2e <2015/10/01>
patch level 2 Babel <3.9n> and hyphenation patterns for 69 languages
loaded. (E:\MiKTeXportable\tex\latex\base\article.cls Document Class:
article 2014/09/29 v1.4h Standard LaTeX document class
(E:\MiKTeXportable\tex\latex\base\size10.clo))
(E:\MiKTeXportable\tex\generic\german\german.sty v2.5e 1998-07-08)
(E:\MiKTeXportable\tex\latex\graphics\graphicx.sty
(E:\MiKTeXportable\tex\latex\graphics\keyval.sty)
(E:\MiKTeXportable\tex\latex\graphics\graphics.sty
(E:\MiKTeXportable\tex\latex\graphics\trig.sty)
(E:\MiKTeXportable\tex\latex\00miktex\graphics.cfg)
(E:\MiKTeXportable\tex\latex\graphics-def\pdftex.def
(E:\MiKTeXportable\tex\generic\oberdiek\infwarerr.sty)
(E:\MiKTeXportable\tex\generic\oberdiek\ltxcmds.sty))))
(DO_00012580_PA1_20151231.4.aux)
(E:\MiKTeXportable\tex\context\base\supp-pdf.mkii [Loading MPS to PDF
converter (version 2006.09.02).] )
(E:\MiKTeXportable\tex\generic\oberdiek\pdftexcmds.sty
(E:\MiKTeXportable\tex\generic\oberdiek\ifluatex.sty)
(E:\MiKTeXportable\tex\generic\oberdiek\ifpdf.sty))
(E:\MiKTeXportable\tex\latex\oberdiek\epstopdf-base.sty
(E:\MiKTeXportable\tex\latex\oberdiek\grfext.sty
(E:\MiKTeXportable\tex\generic\oberdiek\kvdefinekeys.sty))
(E:\MiKTeXportable\tex\latex\oberdiek\kvoptions.sty
(E:\MiKTeXportable\tex\generic\oberdiek\kvsetkeys.sty
(E:\MiKTeXportable\tex\generic\oberdiek\etexcmds.sty)))) ! Misplaced
alignment tab character &. <argument> &
             \cmsi  l.20 \newcommand{\°}{& \cmsi}
                               ?

AND THAT IS CREATING OUTPUT in PDF note: I changed only from \° to \1
\documentclass{article}
\usepackage{german}
\usepackage{graphicx}
\pagestyle{empty}
\topmargin=-22.0mm
\evensidemargin=-25.4mm
\oddsidemargin=-25.4mm
\textwidth=20.5cm
\textheight=28.0cm
\hoffset=0mm
\voffset=0mm

\begin{document}

\newfont{\cmf}{cmssqi8}
\newfont{\cmsi}{cmssqi10}
\newfont{\cssi}{cmssqi12}
\newfont{\cmss}{cmssqi10}

\newcommand{\1}{& \cmsi}
\newcommand{\0}{& \cmss}
\newcommand{\f}{& \cmf }
\newcommand{\T}{& \LARGE\bf}
\newcommand{\B}{& \large\bf}
\newcommand{\linie}{&& \multicolumn{3}{l}{\line(1,0){455}}\\}
\newcommand{\fettlinie}{&& \multicolumn{3}{l}{\rule{455pt}{0.6mm}}\\}
\def\vline#1{&& \multicolumn{#1}{l}{\line(1,0){455}}\\}

\def\stift#1#2#3#4#5#6{\vspace{20mm}\hspace{3.6cm} \cmss\parbox[t]{5.5cm}{#1\\#2\\#3\\#4\\#5\\#6}}
\def\firma#1#2#3{\hspace{3.3cm} \parbox[t]{5.5cm}{#1\\#2\\#3}}
\def\anschrift#1#2#3#4#5#6{\hspace{3.6cm} \cssi #1\\

                         \hspace{3.6cm} \cssi\parbox{5.5cm}{#2\\#3\\#4\\#5\\#6}}
\def\uca#1#2{\hspace{3.3cm} \cmsi\parbox[t]{5.5cm}{#1\\#2}}
\def\ucb#1#2{\hspace{12.2cm} \cmsi\parbox[t]{5.5cm}{#1\\#2}}
\def\grundlage#1#2#3#4{\vspace{18mm}\hspace{3.6cm} \line(1,0){455}

                       \hspace{3.6cm} \cmf\parbox[t]{8cm}{#1\\#2\\#3\\#4}
                       \vspace{-20mm}}

\begin{cmsi}

\end{cmsi}
\newpage
\begin{cmsi}
\stift{Pensionskasse der Stadt Gaga} {Postfach 660} {2540 Gaga} {""} {""} {""}
\vspace{1cm}

\ucb{Verwaltung} {""}
\vspace{19cm}

\grundlage{Grundlage dieser Berechnung bildet das Reglement Ihrer}
          {Pensionskasse.}
          {Erstellt am 25.08.2016 im Auftrag Ihrer Pensionskasse.}
          {}
\vspace{-20.5cm}

\begin{tabular}{p{0cm}p{2.7cm}p{8.6cm}p{5.0cm}r}\\
\1 \T  Pers"onlicher Ausweis\\ [ 4mm]
\fettlinie
\1 \0  Ausweis g"ultig ab 01.06.2015\1 Vertrag Nr. 1/19        \1 LKR \\
\1 \0  f"ur Rentenversicherung\\ [ 2mm]
\linie
\0 Versicherte\1 Axxxxxxx Daniel         \\
\0 Person\1 Geburtsdatum 30.05.1954\1 Vers. Nr. 109.55.201.133  A\\
\1 \1  Versicherungsbeginn 01.06.2013\\
\1 \1  Erreichen des Pensionsalters am 01.06.2018\1 \1  Franken
\\ \linie
\1 \1  J"ahrlicher versicherter Lohn\1 \1   39'994\\  \1 \1  Besch"aftigungsgrad in \%\1   90.000\\
\1 \1  Ihr Jahresbeitrag\1 \1    5'199\\  \linie
\0 Leistungen im\1 Voraussichtliche Altersrente                                                                                \1 im Alter 64\1   24'005\\
\0 Alter        \1 Rentensatz in \%\1   60.022\\
\1 \1  oder voraussichtliches Alterskapital\1 \1   384'080\\ \linie
\0 Leistungen bei\1 Invalidenrente        \1 nach 24 Monaten Wartefrist\1   23'996\makebox[0cm][l]{*}\\
\0 Invalidit"at\1 Invaliden-Kinderrente        \1 nach 24 Monaten Wartefrist\1    4'799\makebox[0cm][l]{*}
\\ \linie
\end{tabular}

\begin{tabular}{p{0cm}p{2.7cm}p{13.1cm}p{0.5cm}r}
\0 Leistungen im\1 Ehegatten- bzw. Lebenspartnerrente\1 \1    15'003\makebox[0cm][l]{*}\\
\0 Todesfall\1 Todesfallkapital wenn keine Ehegatten- bzw. Lebenspartnerrente f"allig wird\1 \1    79'988\\
\1 \1  Waisenrente\1 \1    4'799\makebox[0cm][l]{*}
\\ \linie
\0 Einkauf\1 M"ogliche Einmaleinlage zur Ausfinanzierung der Rente ab Alter 60 (nach Erwerb der vollen Versicherungsdauer)\1 \1    42'179\\  \linie
\end{tabular}

\begin{tabular}{p{0cm}p{2.7cm}p{16cm}}
\0 Hinweise          \1 Bei den vorgenannten Renten handelt es sich um Jahresrenten.        \\
\1 \1  *) Bei Unfall sind die Leistungen gem"ass den Bestimmungen im Reglement auf das gesetzliche Minimum beschr"ankt.\\
\end{tabular}
\end{cmsi}
\end{document}

A: If your files are utf8 encoded -- as would be normal nowadays -- then you can't define a command \° with \newcommand when using pdflatex as ° is no longer a single byte in utf8 but encoded as 0xC2 0xB0.
It would work with one of the utf8 engines like xelatex or lualatex.
You can also define your command by using the primitive \def as it will "eat" the 0xB0 as parameter, but you should then be carefull and not define another non-ascii char starting with 0xC2:
 %utf8 encoded file ...
\documentclass[]{article}
\begin{document}

%\newcommand\°{& abc} %doesn't work
\def\°{& abc} %works

%\def\±{blub} %<--- not allowed, starts with hex C2 too

\begin{tabular}{ll}
\°
\end{tabular}
\end{document}

On the whole you should better avoid non-ascii chars in command names when using pdflatex.


text:
Q: Tabular Forms Column Size Oracle Apex In Oracle Apex is it possible to change the size of the columns in a tabular form? I haven't been able to find a simple way to do it, and I'm not sure if I can manipulate the CSS or not.

A: In Apex when you click on the individual column in a tabular form there is a list of different things you can do to the column itself. Under the "Appearance" or under the section "Advanced" there are places to change the width of the column different ways.
Under Appearance there is a field for width
Under Advanced there is a field for cell width
Both of the above change the column width in different ways.
When I asked this question I must have been looking in the wrong place.


text:
Q: The trouble with Charting with Google Earth Engine In Google Earth Engine, I want to get the NDVI index from several images of the Sentinel 2 satellite with different dates, then I will estimate other parameters from this index. To do this, I need to convert the resulting NDVI images to an image collection. But to chart it, it gives the following error:
Error generating chart: No features contain non-null values of "system:time_start".
It seems that when converting to a collection image, the temporal information of the images is lost. with this condition, how can I fix it?
Link to the code:  https://code.earthengine.google.com/47cd9e7f65b143242ebb238d136bf760
Code:
var sentinel1 = ee.Image('COPERNICUS/S2_SR/20181214T072311_20181214T072733_T39SVV');
var sentinel2 = ee.Image('COPERNICUS/S2_SR/20181219T072319_20181219T072610_T39SVV');
var sentinel3 = ee.Image('COPERNICUS/S2_SR/20181224T072311_20181224T072313_T39SVV');

var ndvi1 = sentinel1.normalizedDifference(['B8','B4']);
var ndvi2 = sentinel2.normalizedDifference(['B8','B4']);
var ndvi3 = sentinel3.normalizedDifference(['B8','B4']);

var NDVI_COL = ee.ImageCollection.fromImages([ndvi1, ndvi2, ndvi3]);

var chart = ui.Chart.image.series(
NDVI_COL, geometry, ee.Reducer.mean(),10,'system:time_start');
print(chart);

A: Try this code
Make a collection of selected images, then plot
var sentinel1 = ee.Image('COPERNICUS/S2_SR/20181214T072311_20181214T072733_T39SVV');
var sentinel2 = ee.Image('COPERNICUS/S2_SR/20181219T072319_20181219T072610_T39SVV');
var sentinel3 = ee.Image('COPERNICUS/S2_SR/20181224T072311_20181224T072313_T39SVV');

var S2 = ee.ImageCollection([sentinel1, sentinel2, sentinel3])
                .filterBounds(geometry)
                .map(function(image){return image.clip(geometry)});

print('collection of Selected Images to plot: ', S2);

var addNDVI = function(image) {
  var ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI');
  return image.addBands(ndvi);
};

var S2_NDVI = S2.map(addNDVI);

var NDVI_S2 = ee.ImageCollection(S2_NDVI.select(["NDVI"], ["NDVI"]));

var chart =
    ui.Chart.image
        .seriesByRegion({
          imageCollection: NDVI_S2,
          band: 'NDVI',
          regions: geometry,
          reducer: ee.Reducer.mean(),
          scale: 10,
          xProperty: 'system:time_start'
        })
        .setOptions({
          title: 'Average NDVI Value by Date',
          hAxis: {title: 'Date', titleTextStyle: {italic: false, bold: true}},
          vAxis: {
            title: 'NDVI',
            titleTextStyle: {italic: false, bold: true}
          },
        });

print(chart);


text:
Q: How to implement SeekBar tooltip showing along thumb in Rigth to Left Direction in Arabic? I am implementing a SeekBar which has tooltip TextView below the Thumb. When I slide the Thumb, tooltip moves along the Thumb. My Application has multi language support. When I change the language to Arabic, Seekbar get Inverted from left to right but when i slide the thumb, tooltip doesn't moves from right to left But it moves from left To right same as in English. I want to move it from Right to left in Arabic.

       int width = seekBar.getWidth() - seekBar.getPaddingStart() - seekBar.getPaddingEnd();
       int thumbPos = seekBar.getPaddingStart() + width * seekBar.getProgress() / seekBar.getMax();
       txvSbContributionTooltipValue.measure(0, 0);
       int txtW = txvSbContributionTooltipValue.getMeasuredWidth();
       int delta = txtW / 2;
       txvSbContributionTooltipValue.setX(seekBar.getX() + thumbPos - delta);


text:
Q: There is a method in C# Distinct() to remove the duplicates, but its support Char datatype There is a method in C# Distinct() to remove the duplicates, but its support Char datatype.
how to use that in this code.
        {
            User allDepartment = new User();
            DataSet Department = allDepartment.GetAllDepartment();
            for (int i = 0; i < Department.Tables[0].Rows.Count; i++)
            {
                String deptName = Department.Tables[0].Rows[i]["Depatment"].ToString().Trim();
                Dept_CBox.Items.Add(deptName);
            }
        }

A: Enumerable.Distinct<T> is a generic method, it supports any type. But you probably used it on a string which implements IEnumerable<char>, that's why you thought that it just supports chars. You have to use it on a collection of strings.
With a DataSet you can use Linq-To-DataTable which is a subset of Linq-To-Objects:
List<string> distinctDepartments = Department.Tables[0].AsEnumerable()
    .Select(row => row.Field<string>("Depatment").Trim())
    .Distinct()
    .ToList();
distinctDepartments.ForEach(deptName => Dept_CBox.Items.Add(deptName))


text:
Q: Use REGEX only to group multiple key value pairs on line with anchoring text? TL;DR: How can I grab a series of key:value pairs that are comma separated, but only if they start with specific strings?
Hello,
I have a situation where I have a block of text with multiple lines, each that could have an arbitrary number of key value pairs on it.
The key and value are colon separated, and then each pair is comma separated.  The lines begin with a specific key value pair, some of which need to be captured, and others ignored.  Other lines do not have any key value pairs, but may have colons and commas which could confuse the Regex string.
Here are some the parameters/limitations of the task:

*

*The values will be comma separated and need to be captured, not just matched

*Each comma separated value will have a colon pair that needs to be grouped in KEY:VALUE format, where KEY is always group 1, VALUE is always group 2

*The regex must not cross a linefeed

*No PHP, SED, AWK, Python, PERL, etc. coding allowed, can only use PCRE2 regex

*There could be an arbitrary number of pairs, and an arbitrary number of lines that need to be captured

Here is the sample text:

Prompt: professional digital [airbrush:gouache:0.6] art of  (mythical:1.1) demon, wearing ragged jacket and pants, dynamic lighting, summer, Dutch Masters:0.6
Negative prompt: (child), (mangled hands), (badly drawn hands),( badly drawn fingers)
Steps: 70, Sampler: Euler a, CFG scale: 40, Seed: 351468770, Size: 340x512, Model hash: 2db4e932c1, Model: Comics_vimod, Denoising strength: 0.651,
Mirror Mode: 2, Mirror Style: 0, Mirroring Max Step Fraction: 0.1, X Pan: 0.02, Y Pan: 0.03
Template: professional digital [airbrush:gouache:0.{6|7|8}] art of  ({fantastical|mythical}:1.1) demon, wearing ragged jacket and {skirt|pants|breech cloth|tuxedo}, dynamic lighting, {winter|summer}, Dutch Masters:0.6

I need to capture and group the lines for Steps, Model, and Mirror Mode but ignore Prompt, Negative Prompt, and Template

Desired matching:
Prompt: Don't match

(Steps|70) (Sampler|Euler a) (CFG scale|40) (Seed|351468770) (Size|340x512)
(Model hash|2db4e932c1) (Model|Comics_vimod) (Denoising strength|0.651)
(Mirror Mode|2) (Mirror Style|0) (Mirroring Max Step Fraction|0.1) (X Pan|0.02) (Y Pan|0.03)

Template: Don't Match

Regex code tried:
(?:(?<=[,])|^)([^:,]+):([^,]+) ... matches what is needed, but also grabs matches from Template and Prompt and it crosses line feeds so that the last comma separated value in Template is grouped in with "Steps"
([^:\s]+):([^\s]+)  ... only matches key value pairs in Prompt and Template because of parentheses and brackets
(?<pair>(?<key>.+?)(?::)(?<value>[^:]+)(?:,|$)) ... grabs way too much, is not limited to the lines needed
Trying to capture with a string ahead of the main regex, like this: Mirror Mode: \d, (?<pair>(?<key>.+?)(?::)(?<value>[^:]+)(?:,|$)) results in only the first CSV key:value pair being grouped
I'd appreciate any assistance. Again, this is to be used in Regex only, no programming tools, no apps, etc. etc.

A: Here is a solution using PCRE2 flavour:
(^(?:Steps|Model|Mirror Mode)|\G(?!^).+?):\h*(.+?)(?:,\h*|$)

The key to match unknown number of matches is \G that restarts the match from the last match position.
Demo & explanation


text:
Q: django app with uwsgi taking long response with requests.post within the views I'm using uwsgi to serve my django application and within my views.py I use requests.post to connect to another server endpoint
Running on manage.py runserver, the views working fine but it takes forever when I use uwsgi
I'm pretty sure requests.post who causing this, as I comment my line that has requests.post, its working okay
Following are my uwsgi.ini
[uwsgi]
env = DJANGO_SETTINGS_MODUL=project.settings
harakiri = 1200 # respawn processes taking more than 20 seconds
max-requests = 5000
daemonize = ./backoffice.log
master = true
workers=16
vacuum=true

Is it possible this is because sort of thread locking between requests and uwsgi?

A: I don't think there is thread lock happening. Just to be sure do something like this:
post-buffering = 8192
processes = 4
no-orphans = 1
thunder-lock = true
enable-threads = true

If I understood correctly you are firing one request to your django view, and from this view you fire another to a third-party resource, right?


text:
Q: How can I read a checkbox state in blueprism i.e., whether it is checked or unchecked? I have 3 check boxes in my process and two of those need to be checked while the third checkbox needs to be unchecked. I am working with a browser based application and these check boxes are modeled as active accessibility elements in the application modeler. When I run my process there are cases(1 out of 5 times) when the process skips checking one of the check boxes and I would like to be able to read the checkbox to know whether they are in a checked or unchecked state so that my process throws an error and does not proceed further.
What I tried:
I tried adding a wait stage after the checkbox action in which I included the element but the only conditions I can see are "check exists" , "check window attribute" and "check AA attribute".

A: Use Read State, Use "Is Connected" Option. you will get the result as a flag,
keep a decision box, and go future

A: Use Read Box, "Get value" property.
It should return "true" or "false".


text:
Q: Geofence didEnterRegion and didExitRegion are not called on Testflight beta app. What am I missing? Updating existing and working native wrapper app to Swift 4, Xcode 9.2, and testing with iPhone 6s iOS 11.2.6 (from Swift 3, Xcode 7.2, iOS 9.2).
Geofence delegate (AppDelegate) fires/executes didEnterRegion and didExitRegion when I simulate location on local environment through Xcode using .gpx files.  When I deploy using fastlane to Testflight beta app the delegates do not fire when crossing geofence.  I've added alerts to verify that the delegates are not being called.  Per other stackoverflow questions I've made sure to include NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription in addition to NSLocationAlwaysUsageDescription key that's already in the Info.plist file.
I've turned on Background Capabilities for Location Updates and Remote Notifications I see them on the Info.plist file.  I can see in my database that a geotracking record was created with a geotoken when I grant/authorize location permissions (Authorized Always).
I'm using CLCircularRegion with a radius of 100 meters.  I've region.notifyOnEntry = true and region.notifyOnExit = true.
I'm deducing that the issue is that I'm missing something when I deploy using Fastlane (although I'm not getting any errors) or that I'm missing some configuration/setting.  Any ideas?  How can I debug this?  Is there a log in Testflight for my app?  What other information can I provide to help figure out the problem?

A: This hurts.  Apparently there is a little bit of precision rounding when we save latitude and longitude (or I was asleep at the wheel that day).  When I mapped the saved latitude and longitude I realized that it's nowhere near the needed fence.  I re-adjusted my latitude and longitude and everything works fine again.  Always check the input data for accuracy.  Hopefully this helps somebody else save time.


text:
Q: Calculate mean in Monte Carlo Simulation using python multiprocessing I have been reading about multiprocessing in Python (e.g. I have read this and this and this and this and so on; I have also read/watched different websites/videos such as this and this and this and so many more!) but I am still confused how I could apply multiprocessing to my specific problem. I have written a simple example code for calculating the avg value of randomly generated integers using Monte Carlo Simulation (I store the random integers in a variable called integers so I can finally calculate the mean; I am also generating random numpy.ndarrays and store them in  a variable called arrays as I need to do some post-processing on those arrays later too):
import numpy as np

nMCS = 10 ** 8

integers = []
arrays = []
for i in range(nMCS):
    a = np.random.randint(0,10)
    b = np.random.rand(10,2)

    integers.append(a)
    arrays.append(b)

mean_val = np.average(integers)
# I will do post-processing on 'arrays' later!!

Now I want to utilize all of the 16 cores on my machine, so the random numbers/arrays are not generated in sequence and I can speed up the process. Based on what I have learnt, I recognize I need to store the results of each Monte Carlo Simulation (i.e. the generated random integer and random numpy.ndarray) and then use Inter-process communication in order to later store all of the results in a list. I have written different codes but unfortunately non of them work. As an example, when I write something like this:
import numpy as np
import multiprocessing

nMCS = 10 ** 6

integers = []
arrays = []

def monte_carlo():
    a = np.random.randint(0,10)
    b = np.random.rand(10,2)

if __name__ == '__main__':
    __spec__ = "ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>)" # this is because I am using Spyder!

    p1 = multiprocessing.Process(target = monte_carlo)

    p1.start()

    p1.join()

    for i in range(nMCS):

        integers.append(a)
        arrays.append(b)

I get the error "name 'a' is not defined". So could anyone please help me with this and tell me how I could generate as many random integers/arrays as possible concurrently, and then add them all to a list for further processing?

A: Due to the fact that returning a lot of result causes time for propagation between process, I would suggest to divide the task in few part and process it before returning back.
n = 4
def monte_carlo():
    raw_result = []
    for j in range(10**4 / n):
        a = np.random.randint(0,10)
        b = np.random.rand(10,2)
        raw_result .append([a,b])
    result = processResult(raw_result)
    #Your method to reduce the result return,
    #let's assume the return value is [avg(a),reformed_array(b)]
    return result

if __name__ == '__main__':
    __spec__ = "ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>)" # this is because I am using Spyder!

    pool = Pool(processes=4)
    #you can control how many processes here, for example multiprocessing.cpu_count()-1 to avoid completely blocking

    multiple_results = [pool.apply_async(monte_carlo, (i,)) for i in range(n)]

    data = [res.get() for res in multiple_results]
    #OR
    data = pool.map(monte_carlo, [i for i in range(n)])
    #Both return you a list of [avg(a),reformed_array(b)]

A: Simple error.
a and b are created in your function
They do not exist in your main scope. you will need to return them back from your function
def monte_carlo():
    a = np.random.randint(0,10)
    b = np.random.rand(10,2)
    #create a return statement here. It may help if you put them into an array so you can return 2 value

if __name__ == '__main__':
__spec__ = "ModuleSpec(name='builtins', loader=<class
    '_frozen_importlib.BuiltinImporter'>)" # this is because I am using Spyder!

    p1 = multiprocessing.Process(target = monte_carlo)

    p1.start()

    p1.join()
    #Call your function here and save the return to something
    for i in range(nMCS):

      integers.append(a) # paste here
      arrays.append(b) # and here

Edit: tested code and found you were never calling your monte_carlo function. a and b are now working correctly but you have a new error to try and solve. Sorry but I wont be able to help with this error as I dont understand it myself, but here is my edit of your code.
import numpy as np
import multiprocessing

nMCS = 10 ** 6

integers = []
arrays = []

def monte_carlo():
    a = np.random.randint(0,10)
    b = np.random.rand(10,2)
    temp = [a,b]
    return temp

if __name__ == '__main__':
__spec__ = "ModuleSpec(name='builtins', loader=<class
'_frozen_importlib.BuiltinImporter'>)" # this is because I am using Spyder!

    p1 = multiprocessing.Process(target = monte_carlo())#added the extra brackets here

    p1.start()

    p1.join()

    for i in range(nMCS):
        array = monte_carlo()
        integers.append(array[0])
        arrays.append(array[1])

and here is the error I got with this edit. I am still learning multi processing myself so other people may be better suited to help with this
Process Process-6:
Traceback (most recent call last):
  File"c:\users\lunar\appdata\local\continuum\anaconda3\lib\multiprocessing\process.py", line 252, in _bootstrap
    self.run()
  File "c:\users\lunar\appdata\local\continuum\anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
TypeError: 'list' object is not callable


text:
Q: python-openid doesn't provide ax or sreg attributes I've been able to finally get python-openid to authenticate a user, but I'm not able to create a sreg.SRegResponse or ax.FetchResponse as they come back as None.  This is coming from a Google Apps account and I'm trying to follow the example from https://github.com/openid/python-openid/tree/master/examples/djopenid.  I've heard Google's OpenID system can be a little funky and require some tweaks like Retrieve OpenID AX attributes from Google / Yahoo in Rails
    response = c.complete(request_args, return_to)

    sreg_response = sreg.SRegResponse.fromSuccessResponse(response)
    ax_response = ax.FetchResponse.fromSuccessResponse(response)

The response is definitely coming back as a SUCCESS, but I see the following error message, which may be related:
Generated checkid_setup request to https://www.google.com/accounts/o8/ud with assocication AOQobUdVBCrd-GZRcasn9tD-yOUF0Y8pJLAQrYXODqLxUUjN62G1BXR1
Error attempting to use stored discovery information: <openid.consumer.consumer.TypeURIMismatch: Required type http://specs.openid.net/auth/2.0/signon not found in ['http://specs.openid.net/auth/2.0/server', 'http://openid.net/srv/ax/1.0', 'http://specs.openid.net/extensions/ui/1.0/mode/popup', 'http://specs.openid.net/extensions/ui/1.0/icon', 'http://specs.openid.net/extensions/pape/1.0'] for endpoint <openid.consumer.discover.OpenIDServiceEndpoint server_url='https://www.google.com/accounts/o8/ud' claimed_id=None local_id=None canonicalID=None used_yadis=True >>
Attempting discovery to verify endpoint
Performing discovery on https://www.google.com/accounts/o8/id?id=AItOawkKU4uzJV9Q_FGMECNGsbiXG2caISYMyCw
Received id_res response from https://www.google.com/accounts/o8/ud using association AOQobUdVBCrd-GZRcasn9tD-yOUF0Y8pJLAQrYXODqLxUUjN62G1BXR1

Here's my setup.
           sreg_request = sreg.SRegRequest(optional=['email', 'nickname'],
                                        required=['dob'])
            auth_request.addExtension(sreg_request)

            # Add Attribute Exchange request information.
            ax_request = ax.FetchRequest()
            # XXX - uses myOpenID-compatible schema values, which are
            # not those listed at axschema.org.
            ax_request.add(ax.AttrInfo('http://schema.openid.net/namePerson',
                                       required=True))
            ax_request.add(ax.AttrInfo('http://schema.openid.net/contact/web/default',
                                       required=False, count=ax.UNLIMITED_VALUES))
            auth_request.addExtension(ax_request)

A: I was having problems with Google returning not the schema.openid.net values for AttributeExchange. It was returning None just like you mentioned, and the worst part is that it used to work when I first wrote my OpenID handlers.
Once I switched over to the axschema values in my implementation, it worked like a charm. ex:
    URLS = {
      'ax_email': 'http://axschema.org/contact/email',
      'ax_first': 'http://axschema.org/namePerson/first',
    }

    ...

    ax_request = ax.FetchRequest()
    ax_request.add(ax.AttrInfo(URLS['ax_email'], required = True))
    ax_request.add(ax.AttrInfo(URLS['ax_first'], required = True))

    auth_request.addExtension(ax_request)


text:
Q: Visual Studio 2015 - arbitrary cursor position on empty line Initial note: I'm not getting any responses over on superuser to my question, so please allow me to ask this here:
I inherited a VS solution with a bunch of unorthodox settings. I'm not at liberty to wipe out all those settings and start over. So there is 1 setting I want to change back to VS default but cannot find it.
In a normal/default VS c# environment, when you click the mouse on a line of code that hasn't been written yet (empty, no spaces, no code, no tabs), the cursor automatically positions to the beginning of where the line of code should begin. If it's just inside a foreach, if, or etc, it will indent a bit from the left edge according to tab rules, etc.
But in the weird VS settings I have, wherever I click, the cursor positions at that exact spot. So if I click on col 20 of the next line, the cursor remains at col 20 rather than auto-repositioning to col 5 or wherever it should be. This is SO annoying because I can't always eyeball where the cursor should be and I end up clicking at the end of the previous line, then hitting ENTER, at which time it goes to the next line and positions the cursor at the right place.
How can I fix this?

A: It is controlled by the Enable virtual space option. See Visual Studio options - Text Editor - C#. By default it is off/unchecked.

A: I resolved this issue by applying Sergey's suggested change (Visual Studio options -> Text Editor -> C# -> Enable Virtual Space [check]), but also enabled (Options -> Text Editor -> C# -> Tabs -> Smart).


text:
Q: Action items/icons not displaying on action bar in Android App I am trying to have a search action on my action bar. I have set an icon and have showAsAction set to always but it is still always displayed in the overflow menu. How can I make it display on the action bar itself? Thanks!
Activity
public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    setTitle("Add");
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        Toast.makeText(getApplicationContext(), "Settings",
                   Toast.LENGTH_LONG).show();
        return true;
    }
    if (id == R.id.action_search) {
        Toast.makeText(getApplicationContext(), "Search",
                   Toast.LENGTH_LONG).show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

Menu XML file
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.testtabs.MainActivity" >

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never"/>
<item
    android:id="@+id/action_search"
    android:actionViewClass="android.support.v7.widget.SearchView"
    android:icon="@drawable/ic_search"
    android:showAsAction="always"
    android:title="@string/title_search"/>

</menu>

A: Either remove
android:actionViewClass="android.support.v7.widget.SearchView"

or delete your case statement for action_search in onOptionsItemSelected. Doing either of those will display the icon.
If you want to use SearchView the callback is handled differently than onOptionsItemSelected.
Documentation here: http://developer.android.com/guide/topics/ui/actionbar.html#ActionView

A: Just change app:showAsAction instead of android:showAsAction
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.testtabs.MainActivity" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"`enter code here`
        android:title="@string/action_settings"
        app:showAsAction="never"/>
    <item
        android:id="@+id/action_search"
        android:actionViewClass="android.support.v7.widget.SearchView"
        android:icon="@drawable/ic_search"
        app:showAsAction="always"
        android:title="@string/title_search"/>

    </menu>


text:
Q: assign specific characters to rows in a data frame I have huge data frame that looks like this in R
    scan_id       sample
1  s8w_00001.sed      1
2  s8w_00001.sed      1
3  s9w_00001.sed      1
4 s10w_00001.sed      1
5 s11d_00002.sed      1
6 s12w_00004.sed      1
7 s13w_00001.sed      1
8 s14w_00001.sed      1

The column labelled sample should have values that correspond with the column labelled scan_id. So for an observation where I have scan_id= s8w_00001.sed, sample should be 8. Because there is an 8 in that line of characters. I should have something that looks like this.
 scan_id          sample
1  s8w_00001.sed      8
2  s8w_00002.sed      8
3  s9w_00001.sed      9
4 s10w_00001.sed     10
5 s11d_00002.sed     11
6 s12w_00004.sed     12
7 s13w_00001.sed     13
8 s14w_00001.sed     14

Can anyone help?

A: You can use gsub, i.e
gsub('s([0-9]+)[a-z]+_.*$', '\\1', df$scan_id)
#[1] "8"  "8"  "9"  "10" "11" "12" "13" "14"

A: If you just want to extract the first digit(s) from your scan_id column, you can use mutate(data, sample = str_extract(scan_id, "[:digit:]+")) from the tidyverse. In this case the first set of digits is extracted.
If you want to specifiy the pattern before your digits, use mutate(data, sample = str_extract(scan_id, "(?<=[:alpha:]+)[:digit:]+")). In this case the first set of digits that is preceded by a set of letters is extracted.

A: One option would be to use the stri_extract_first_regex from stringi package
library(stringi)
# Extract the one occurance of a digit [0-9]+ ('+' matches 1 or more digits)
df$samples <- stri_extract_first_regex(df$scan_id, "[0-9]+")

And the output
> df
         scan_id sample samples
1  s8w_00001.sed      1       8
2  s8w_00001.sed      1       8
3  s9w_00001.sed      1       9
4 s10w_00001.sed      1      10
5 s11d_00002.sed      1      11
6 s12w_00004.sed      1      12
7 s13w_00001.sed      1      13
8 s14w_00001.sed      1      14

Where df is:
df <- read.table(text = "scan_id       sample
  s8w_00001.sed      1
  s8w_00001.sed      1
  s9w_00001.sed      1
 s10w_00001.sed      1
 s11d_00002.sed      1
 s12w_00004.sed      1
 s13w_00001.sed      1
 s14w_00001.sed      1", header = TRUE)

A: You can also do:
df$sample <- gsub("\\D", "", sapply(strsplit(df$scan_id, "_"), function(x) x[1]))

         scan_id sample
1  s8w_00001.sed      8
2  s8w_00001.sed      8
3  s9w_00001.sed      9
4 s10w_00001.sed     10
5 s11d_00002.sed     11
6 s12w_00004.sed     12
7 s13w_00001.sed     13
8 s14w_00001.sed     14

Here it splits the "scan_id" on _ and then extracts the numbers from the first element after split.


text:
Q: Groovy Script - Logback configuration unawaited behaviour I want to use Logback as my logging framework within Grails. therefore I set up everything in place to work but my implementation fails on the configuration file itself. the reason is, as I guess, somewhere whithin the scoping of Groovy Script but I'm not able to figure it out...
if I define my String properties without any identifier which I want to use later I get a warning that it may not be accessed. For example:
LOG_DIR = 'c:/temp/myproject/logs/'
BACKUP_DIR = LOG_DIR + 'backup/'

appender('F_MAIN', RollingFileAppender) {
  file = LOG_DIR + 'test.log'
  rollingPolicy(FixedWindowRollingPolicy) {
    fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
    // .... and so on
  }
}

I get the following error message from Logback, which I'm pretty sure is indicating that both LOG_DIR and BACKUP_DIR can not be reached:
13:33:32,036 |-ERROR in ch.qos.logback.classic.gaffer.AppenderDelegate@6fd00b - Appender [F_MAIN] of type [ch.qos.logback.core.rolling.RollingFileAppender] has no appplicable [LOG_DIR] property
13:33:32,068 |-ERROR in ch.qos.logback.classic.gaffer.ComponentDelegate@788ac3 - Component  of type [ch.qos.logback.core.rolling.FixedWindowRollingPolicy] has no appplicable [BACKUP_DIR] property

I also tried the following approach by declaring both variables with the @Field tag, but it still does not work:
@Field String LOG_DIR = 'c:/temp/myproject/logs/'
@Field String BACKUP_DIR = LOG_DIR + 'backup/'

appender('F_MAIN', RollingFileAppender) {
  file = LOG_DIR + 'test.log'
  rollingPolicy(FixedWindowRollingPolicy) {
    fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
    // .... and so on
  }
}

what am I doing wrong here?

A: oh my!
after searching and a lot of trial/error I found the solution and it was so close and definitely seems obvious now: I had to declare both variables with def, so now they are visible throughout the whole script ;)
For example, this is working code:
def LOG_DIR = 'c:/temp/myproject/logs/'
def BACKUP_DIR = LOG_DIR + 'backup/'

appender('F_MAIN', RollingFileAppender) {
  file = LOG_DIR + 'test.log'
  rollingPolicy(FixedWindowRollingPolicy) {
    fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
    // .... and so on
  }
}

now, I'm also able to use a function like this within my script:
def createFilename(String directory, String name, boolean isBackupFile) {
  String filename = ''
  if(isBackupFile) {
    filename = "${directory}backup/MyProject-${name}.%d{yyyy-MM-dd}.%i.log.zip"
  } else {
    filename = "${directory}MyProject-${name}.log"
  }
  return filename
}

def fileAppenderLog = createFilename(LOG_DIR, 'output', false)
def fileAppenderLogBackup = createFilename(LOG_DIR, 'output', true)

appender('F_MAIN', RollingFileAppender) {
  file = fileAppenderLog
  rollingPoliciy(FixedWindowRollingPolicy) {
    fileNamePattern = fileAppenderLogBackup
    // .... and so on
  }
}

which is pretty useful, I think :), especially if you want to declare a bunch of different logfiles and even if you want to declare temporary logfiles which are created when Logback is rescanning this file ...


text:
Q: Exclude contained php-code in javascript in minifier.org I'm using https://www.minifier.org/ (https://github.com/matthiasmullie/minify/) to minify my javascript prior to uploading it on the live-server. This works fine.
Now I need to minify a file which contains mixed JavaScript- and PHP-Code (the PHP-Code is echoing Javascript-Code dynamically). My problem is that minifier.org of course thinks the PHP-Code is JavaScript and minifies it, resulting in PHP-errors. Is there a way to tell the Minifier to just exclude everything between ?


text:
Q: How can I make the script continue to open the links in web pages with Python and Selenium? I have a script that reads the links that are in excel file, it opens each link fine, but when it encounters an error in automatic it marks error and closes the script. How can I make the script continue to open the links without stopping on the page that has an error?
I accept any suggestion or improvement for script in general. It's just a part of my code.
for url in mylist:
    driver.get(url)
    driver.maximize_window()
    driver.implicitly_wait(val)
    timestamp = datetime.datetime.now().strftime('%d_%m_%Y')
    driver.save_screenshot(str(shark)+"/"+str(cont)+'_'+timestamp+'.png')
    cont += 1

A: Wrap up your code block in a try-except{} block as follows:
for url in mylist:
    try:
        driver.get(url)
        driver.maximize_window()
        driver.implicitly_wait(val)
        timestamp = datetime.datetime.now().strftime('%d_%m_%Y')
        driver.save_screenshot(str(shark)+"/"+str(cont)+'_'+timestamp+'.png')
        cont += 1
    except:
        continue


text:
Q: PhantomJS build with video features I use Windows 8.1 and my computer has a 64-bit processor. I'm trying to build PhantomJS so it can support video/audio features, but when I am building it I get this error.
I tried phantomjs doesn't support html5 video tag.
python build.py

c:\strawberry\c\bin\../lib/gcc/i686-w64-mingw32/4.4.3/../../../../i686-w64-mingw
32/include/dvec.h:837: error: '_mm_cvtpd_ps' was not declared in this scope
c:\strawberry\c\bin\../lib/gcc/i686-w64-mingw32/4.4.3/../../../../i686-w64-mingw
32/include/dvec.h: In function 'F64vec2 IntToF64vec2(const F64vec2&, int)':
c:\strawberry\c\bin\../lib/gcc/i686-w64-mingw32/4.4.3/../../../../i686-w64-mingw
32/include/dvec.h:838: error: '_mm_cvtsi32_sd' was not declared in this scope
mingw32-make: *** [qhash.o] Error 1

ERROR: Failed to build PhantomJS! Configuration of Qt Base failed.


text:
Q: pandas - apply a function on column, using a second dataframe as an input for the function? Look for the fastest and most pandas centric way of doing the following:
support=

Values Confidence R/S
10      3          S
20      6          S
40      10         S
35      12         S

df =

name    strike
xyz      12
dfg      6
ghf      40

Aim: Get the closest greater than 0 row from support to df.
Excpected output:
df =

name    strike   support
xyz      12      [10, 3, S, 2]
dfg      6       [0, 0, S, 0]   # as there is no > 0 value when subtracting strike from support
ghf      40      [35, 12, S, 5]

Bonus: expand the columns into the relevant columns.
I can do this by looping through the strikes, wondering if there is a better/faster way to achieve what I am thinking of doing.

A: Use merge_asof
pd.merge_asof(df.sort_values('strike'),       # must be sorted by key
              support.sort_values('Values'),  # must be sorted by key
              left_on='strike',
              right_on='Values',
              direction='backward',           # default, so `Values <= strike`
              allow_exact_matches=False       # so that `Values != strike`
             )

Output:
  name  strike  Values  Confidence  R/S
0  dfg       6     NaN         NaN  NaN
1  xyz      12    10.0         3.0    S
2  ghf      40    35.0        12.0    S


text:
Q: How to Auto scale y and x axis of a graph in real time python I modified the code of this tutorial to create my own real time plot:
https://learn.sparkfun.com/tutorials/graph-sensor-data-with-python-and-matplotlib/speeding-up-the-plot-animation
I needed to plot the data from a proximity sensor in real time, the data is sent through USB cable to the computer and I read it with the serial port, so the code is already working how I wanted to, but I also want to modify the y-axis and x-axis, not let it static, because sometimes the peaks are 3000 and sometimes 2000 and when the sensor is not being touched, the peaks are at around 200 because it also detects the ambient light. any clue how can I make it?
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import serial

# Data from serial port
port = 'COM8'
baudrate = 9600
tout = 0.01  # Miliseconds

# Time to update the data of the sensor signal real time Rs=9600baud T=1/Rs
tiempo = (1 / baudrate) * 1000

# Parameters
x_len = 200         # Number of points to display
y_range = [20000, 40000]  # Range of Y values to display

# Create figure for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = list(range(0, x_len))
ys = [0] * x_len
ax.set_ylim(y_range)

# Create a blank line. We will update the line in animate
line, = ax.plot(xs, ys)

# Markers
startMarker = 60  # Start marker "<"
endMarker = 62  # End marker ">"

# Begin Arduino communication, Port COM8, speed 9600
serialPort = serial.Serial(port, baudrate, timeout=tout)

# Begin to save the arduino data
def arduinodata():

    global startMarker, endMarker

    ck = ""
    x = "z"  # any value that is not an end- or startMarker
    bytecount = -1  # to allow for the fact that the last increment will be one too many

    # wait for the start character
    while ord(x) != startMarker:
        x = serialPort.read()

    # save data until the end marker is found
    while ord(x) != endMarker:
        if ord(x) != startMarker:
            ck = ck + x.decode()
            bytecount += 1
        x = serialPort.read()

    return ck

def readarduino():

    # Wait until the Arduino sends '<Arduino Ready>' - allows time for Arduino reset
    # It also ensures that any bytes left over from a previous message are discarded

    msg = ""

    while msg.find("<Arduino is ready>") == -1:

        while serialPort.inWaiting() == 0:
            pass
        # delete for example the "\r\n" that may contain the message
        msg = arduinodata()
        msg = msg.split("\r\n")
        msg = ''.join(msg)

        # If the sensor send very big numbers over 90000 they will be deleted
        if msg and len(msg) <= 5:
            msg = int(msg)
            return msg

        elif msg and len(msg) >= 4:
            msg = int(msg)
            return msg

# This function is called periodically from FuncAnimation
def animate(i, ys):

    # Read pulse from PALS2
    pulse = readarduino()

    # Add y to list
    ys.append(pulse)

    # Limit x and y lists to set number of items
    ys = ys[-x_len:]

    # Update line with new Y values
    line.set_ydata(ys)
    return line,

# Plot labels
plt.title('Heart frequency vs Time')
plt.ylabel('frequency ')
plt.xlabel('Samples')

# Set up plot to call animate() function periodically
ani = animation.FuncAnimation(fig, animate, fargs=(ys,), interval=tiempo, blit=True)
plt.show()
plt.close()
serialPort.close()

This is how the graph looks like, the x and y axis are always the same:

A: If you want to autoscale the y-axis, then you can simply adjust the y-axis limits in your animate() function:
def animate(i, ys):

    # Read pulse from PALS2
    pulse = readarduino()

    # Add y to list
    ys.append(pulse)

    # Limit x and y lists to set number of items
    ys = ys[-x_len:]
    ymin = np.min(ys)
    ymax = np.max(ys)
    ax.set_ylim(ymin, ymax)

    # Update line with new Y values
    line.set_ydata(ys)
    return line,

HOWEVER, the result will not be what you expect if you use blit=True. This is because blitting is attempting to only draw the parts of the graphs that have changed, and the ticks on the axes are excluded from that. If you need to change the limits and therefore the ticks, you should use blit=False in your call to FuncAnimation. Note that you will encounter a performance hit since matplotlib will have to redraw the whole plot at every frame, but if you want to change the limits, there is no way around that.

A: So I made some changes to the last code of this link https://www.learnpyqt.com/courses/graphics-plotting/plotting-pyqtgraph/
and I could solve the problem. x and Y axis are now autoscaling
import PyQt5
from PyQt5 import QtWidgets, QtCore
from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg
import sys  # We need sys so that we can pass argv to QApplication
import os
from random import randint
import serial

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.graphWidget = pg.PlotWidget()
        self.setCentralWidget(self.graphWidget)

        # Data from serial port
        self.port = 'COM8'
        self.baudrate = 9600
        self.tout = 0.01  # Miliseconds

        # Time to update the data of the sensor signal Rs=9600baud T=1/Rs
        self.tiempo = (1 / self.baudrate) * 1000

        self.x_len = 200
        self.x = list(range(0, self.x_len))  # 100 time points
        self.y = [0] * self.x_len # 100 data points

        self.graphWidget.setBackground('w')

        # Markers
        self.startMarker = 60  # Start marker "<"
        self.endMarker = 62  # End marker ">"

        # Begin Arduino communication, Port COM8, speed 9600
        self.serialPort = serial.Serial(self.port, self.baudrate, timeout=self.tout)

        pen = pg.mkPen(color=(255, 0, 0))
        self.data_line = self.graphWidget.plot(self.x, self.y, pen=pen)

        self.timer = QtCore.QTimer()
        self.timer.setInterval(self.tiempo)
        self.timer.timeout.connect(self.update_plot_data)
        self.timer.start()

    # Begin to save the arduino data
    def arduinodata(self):

        ck = ""
        x = "z"  # any value that is not an end- or startMarker
        bytecount = -1  # to allow for the fact that the last increment will be one too many

        # wait for the start character
        while ord(x) != self.startMarker:
            x = self.serialPort.read()

        # save data until the end marker is found
        while ord(x) != self.endMarker:
            if ord(x) != self.startMarker:
                ck = ck + x.decode()
                bytecount += 1
            x = self.serialPort.read()

        return ck

    def readarduino(self):

        # Wait until the Arduino sends '<Arduino Ready>' - allows time for Arduino reset
        # It also ensures that any bytes left over from a previous message are discarded

        msg = ""

        while msg.find("<Arduino is ready>") == -1:

            while self.serialPort.inWaiting() == 0:
                pass
            # delete for example the "\r\n" that may contain the message
            msg = self.arduinodata()
            msg = msg.split("\r\n")
            msg = ''.join(msg)

            # If the sensor send very big numbers over 90000 they will be deleted
            if msg and len(msg) <= 5:
                msg = int(msg)
                return msg

            elif msg and len(msg) >= 4:
                msg = int(msg)
                return msg

    def update_plot_data(self):
        pulse = self.readarduino()
        self.x = self.x[1:]  # Remove the first y element.
        self.x.append(self.x[-1] + 1)  # Add a new value 1 higher than the last.

        self.y = self.y[1:]  # Remove the first
        self.y.append(pulse)  # Add a new random value.

        self.data_line.setData(self.x, self.y)  # Update the data.

app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())


text:
Q: Parse.com iOS [pod Parse] error I'm building a simple app, as it is described on this tutorial: Instagram like app
However, I've made all the steps correctly, to the "Run the app" part, but when I ran it, the Xcode 7 (swift2) outputs this error every time I launch the app or pull to refresh:

2015-09-20 00:46:41.224 Paws2[1196:393571] [Error]: unauthorized (Code: 0, Version: 1.8.5)

I'm using the latest pod available and I don't know how to  bypass this issue.
Note that I've made an exactly app as described in the tutorial with the version 1.7.5 and the error was the same, so I updated the pos version to the latest.
I've names the app Paws2 on purpose, it wasn't a error, as it says in the Tutorial to name it 'Paws'.
Thanks in advance
- Regards, Ivan.
EDIT 1: I've updated cocoapods and everything else related and the error continues.

A: I had a same error too.
My case was silly. I put wrong Application ID / Client Key in didFinishLaunchingWithOptions method on AppDelegate.
[Parse setApplicationId:@"Your Application ID"
              clientKey:@"Your Client Key"];

Make sure you put right keys.


text:
Q: Two-shot generator How can you make a 2-shot generator in python?
My attempt (doesn't work):
>>> def g():
...     try:
...         yield 1
...         raise StopIteration('Shot 1 exhausted')
...     finally:
...         yield 2
...         # 'Shot 2 exhausted'
...
>>> x = g()
>>> list(x), list(x)
([1, 2], [])
# expected output ([1], [2])

A: The iterator protocol specifically forbids this:

The intention of the protocol is that once an iterator's next() method
  raises StopIteration, it will continue to do so on subsequent calls.
  Implementations that do not obey this property are deemed broken.

For this reason, the generator syntax does not offer a way to make a 2-shot iterator.
If you really want to do it anyway, you can't use a generator:
class BrokenIterator(object):
    def __init__(self):
        self.callcount = 0
    def __iter__(self):
        return self
    def next(self):
        self.callcount += 1
        if self.callcount == 1:
            return 1
        elif self.callcount == 3:
            return 2
        else:
            raise StopIteration


text:
Q: Parse file saving error,""Unable to encode an unsaved parsefile in User I am trying to sign up a user with a picture and I keep getting the error "Unable to encode an unsaved parsefile", And when I click save again it says a user is already signing up but it never gets to parse.
My code is as follows
imageToBeSent = ((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageToBeSent.compress(Bitmap.CompressFormat.PNG,5, stream);
byte[] imageRec = stream.toByteArray();
ParseFile file = new ParseFile("profile.png", imageRec);

file.saveInBackground();

Intent fromFirstSignup = getIntent();
ParseUser user = new ParseUser();
user.put("Name", fromFirstSignup.getStringExtra("Name"));
user.put("Surname", fromFirstSignup.getStringExtra("Surname"));
user.put("Department", fromFirstSignup.getStringExtra("Department"));
user.put("JobTitle", fromFirstSignup.getStringExtra("JobTitle"));
user.setEmail(fromFirstSignup.getStringExtra("EmailAddress"));
user.put("ProfilePictures", file);
user.setUsername(usernametxt);
user.setPassword(passwordtxt);

user.signUpInBackground(new SignUpCallback() {
    public void done(ParseException e) {
        if (e == null) {
        }
    }
}

The initializing of other variables may not show. I did look at the other questions similar to this but none helped with my problem.

A: You're getting this error because you cannot attach an unsaved PFFile in a PFObject/PFUser/PFWhatever.
You have to wait until the file.saveInBackground finishes and then save your User later.
I suggest that you implement the file.saveInBackgroundWithBlock, and put your Sign Up code inside the completion blocks.


text:
Q: How to asynchronously await an Akka.Actor event? I am using akka.NET. In most cases we use akka like this:
class ActorA : UntypedActor
{
    public delegate void EventHandler(object arg1, object arg2, ...);
    public static event EventHandler Event;
}
actorA.Event += some_function;

In this case we execute some_function(arg1, arg2) whenever Event.Invoke(arg1, arg2) is called. Now assume that we have an asynchrounous HTTP server, and I am trying to let the server asynchronously await actorA.Event to happen, after a client calls the server. I do not need to run some_function when Event happens, but I have to ensure that the runtime context is switched back into the functions of the HTTP server. That is:
// in the methods of the HTTP server...
public async void AwaitAnEvent()
{
    await ReturnOnEvent(actorA.Event);
}

Is it possible to efficiently implement ReturnOnEvent which returns immediately when the next actorA.Event.Invoke(arg1, arg2) is called?

A: This case smells a bit.
inside the web controller just ask your actor and that will trigger it to generate response.
When asking it will await in the controller to get response.
var response =  myActor.Ask<ResponseType>(new GiveMySomeFoodMsg());
-- in the actor
Sender.Tell(new ResponseType(some data here))


text:
Q: Selecting customer IDs who have purchased from a certain channel I'm trying to pull a list of customer IDs who have purchased online only and another list of those who have purchased both online and in-store (no customers for in-store only). I currently have a table that looks like this:
-------------------------------------------------------
**customerid**        **shipped_dt**        **channel**
1                       2018-10-31            online
1                       2018-11-01            store
2                       2018-11-01            store
3                       2018-11-01            online
3                       2018-11-02            online

In this case, for the list with those who have purchased both online and in-store, I was customerid 1. For the list of customers that are online only, I want customerid 3. How exactly would I go about writing a code for this? I'm still learning SQL so I'm not too knowledgeable about the proper syntax and abilities within SQL.
I only want a return of customerid and the channel that they purchased through.
Thank you!

A: Just a minor alternative
Example
Select customerid
      ,Channel  = min(Channel)
 From  YourTable
 Group By customerid
 Having min(Channel)=max(channel)
    and min(Channel)='online'

Note: If you remove and min(Channel)='online' you would see customers who purchased through only one channel
Returns
customerid  Channel
3           online

A: If you have a separate list of customers, you might want to use exists:
For example, to get customers who have purchased in both places:
select c.*
from customers c
where exists (select 1 from t where t.customer_id = c.customer_id and t.channel = 'online'
             ) and
      exists (select 1 from t where t.customer_id = c.customer_id and t.channel = 'store'
             ) ;

This can have some advantages over aggregation:

*

*exists and not exists can make direct use of an index on (customer_id, store).

*You can get customers who purchased in neither channel.

*You can get additional information about the customer, if that is desirable.

A: For the case of 'online' only customers use not exists to exclude those who have purchased in 'store':
select distinct customerid
from tablename t
where not exists (
  select 1 from tablename where customerid = t.customerid and channel = 'store'
)

For the case of 'online' and 'store':
select distinct customerid
from tablename t
where
  (select count(distinct channel) from tablename where customerid = t.customerid) = 2

You can combine the above queries into this:
select distinct customerid, 'online' channel
from tablename t
where not exists (
  select 1 from tablename where customerid = t.customerid and channel = 'store'
)
union all
select distinct customerid, 'both' channel
from tablename t
where
  (select count(distinct channel) from tablename where customerid = t.customerid) = 2

See the demo


text:
Q: How to prevent calendar invite responses from being blocked between two Google Workspace accounts? My company has two separate Google Workspace accounts, each associated with a separate domain (lets call them domainA and domainB).
Employees have email addresses assigned to them for both domains.
If alice@domainA.com sends bob@domainB.com a calendar invite, and bob@domainB.com replies to that calendar invite email through the Gmail web client, he receives an auto-response saying:

Message blocked
Your message to alice@domainA.com has been blocked. See technical
details below for more information.
The response was:
Unauthenticated email from domainB.com is not accepted due to domain's
DMARC policy. Please contact the administrator of domainB.com domain
if this was a legitimate mail. Please visit
https://support.google.com/mail/answer/2451690 to learn about the
DMARC initiative.

I've read the information at the link provided, which suggests that we need to create and publish a DMARC policy. However, given that these are both Google Workspace accounts, it seems like there would be a simpler solution –– and preferably one with a smaller blast radius than broadly changing our email authentication logic.
Is there a simple solution I'm missing, before I go down this rabbit hole?

A: TL,DR:

*

*Make sure you have DKIM setup on both domain, using the DKIM selector record provided by Google at Google Workspace > Settings for Gmail > Authenticate email

*Enable signing with your domain on the same page above

Long answer

Unauthenticated email from domainB.com is not accepted due to domain's DMARC policy. Please contact the administrator of domainB.com domain if this was a legitimate mail. Please visit https://support.google.com/mail/answer/2451690 to learn about the DMARC initiative.

The message above indicates that domainB.com indeed has already a DMARC record. And its policy is set to reject emails that don't pass DMARC checks.
You can check that by using a local DNS tool to query the TXT record at _dmarc.domainB.com (e.g. dig _dmarc.domainB.com txt). You can also use https://toolbox.googleapps.com/apps/dig/#TXT/ for that.
Now, emails from domainA.com to domainB.com are being rejected because neither SPF nor DKIM are passing and in alignment, from a DMARC POV. To be in alignment means that either SPF or DKIM pass, and the domain that pass checks is domainA.com (perhaps subdomains of that, depending on how you configured DMARC).
Having said that, Google Calendar invitation replies by default are sent with envelope from a Google domain. This will not pass DMARC, because SPF will not be in alignment with your domain. AFAIK there's no option on Google Workspace to change that.
DKIM, on the other hand, can be set up on Google Workspace to sign emails and use your domain. This setting will be used by Google apps, and it will make DKIM signatures align with "From" headers. This will make DMARC pass.
Therefore, to solve this you need to:

*

*Make sure that a DKIM record is set up on domainA.com's DNS, with the value provided by Google. The record must be at the address shown in the page (google._domainkeys.domainA.com).

*Make sure that you actually enable DKIM signing. You do this by clicking the "Start Authentication" button, otherwise some Google apps won't issue DKIM signatures using your domain. This is not totally obvious, and people seem to forget this last step. Emails sent using Gmail and other Google apps will still work without starting auhtentication (see Google Calendar invites failing DMARC checks if you want to know why), and this helps masking the issue. Enabling signing using your domain (i.e. the "Start" button) changes that.


text:
Q: ZXing not working on first page of the Navigation Page I'm trying to implement ZXing scanner in my application by using it in a page

It worked when I tried to use in the first time, but, after some hours into the project, I went back to test it, it was not working anymore. I assume it is some problem with some configuration, because I tried it with the same code in a brand new application and it works normally.
I'm using a webcam to scan the barcode.
EDIT
Found out that the problem is with the Navigation Page, I am using the Scanner inside the first* page on the navigation page.
*In the second page it works properly.


text:
Q: How to create the column in pandas based on values of another column I have created a new column, by adding values from one column, to the index of the column from which I have created this new column. However, my problem is the code works fine when I implement on sample column, but when I pass the already existing dataframe, it throws the error, "can only perform ops with scalar values". As per what I found is the code expects dist and that is why it is throwing error.
I tried converting the dataframe to dictionary or to a list, but no luck.
 df = pd.DataFrame({'Name': ['Sam', 'Andrea', 'Alex', 'Robin', 'Kia',    'Sia'], 'Age':[14,25,55,8,21,43], 'd_id_max':[2,1,1,2,0,0]})`

df['Expected_new_col'] = df.loc[df.index + df['d_id_max'].to_list, 'Age'].to_numpy()

print(df)

error: can only perform ops with scalar values.

This is the dataframe I want to implement this code:
      Weight   Name     Age     1     2   abs_max d_id_max
  0     45     Sam      14     11.0  41.0   41.0    2
  1     88     Andrea   25     30.0 -17.0   30.0    1
  2     56     Alex     55    -47.0 -34.0   47.0    1
  3     15     Robin    8      13.0  35.0   35.0    2
  4     71     Kia      21     22.0  24.0   24.0    2
  5     44     Sia      43     2.0   22.0   22.0    2
  6     54     Ryan     45     20.0  0.0    20.0    1

A: Writing your new column like this will not return an error:
df.loc[df.index + df['d_id_max'], 'Age'].to_numpy()

EDIT:
You should first format d_id_max as int (or float):
df['d_id_max'] = df['d_id_max'].astype(int)

A: The solution was very simple, I was getting the error because the data type of the column d_id_max was object type, which should be either float or integer, so i change the data type and it worked fine.


text:
Q: Error 403 when posting on Facebook a Joomla URL for multilingual site I have a multilingual Joomla3 website
www.mekako.fr
the server redirects to french language by default (or Italian/English it detects those lagnuages)
The problem arises when I try to posto to a Facebook wall/page a link to www.mekako.fr, it gives a "403 access denied", if I post www.mekako.fr/fr or www.mekako.fr/it it is ok...
We are on Windows Hosting, no .htaccess, but web.config is used...
Any explanation? is the "root url" unavailable because it redirects to the correct language?

A: Thanks, following the links you provided I found a hint about GZIP compression...
Disabled GZIP compression in Joomla and everything is working perfectly now...
see:
Facebook Open Graph, required property 'og:title' of type 'string' was not provided


text:
Q: weak duality theorem Studying duality theory I have not found clear this point

considering the primal a minimize problem, if $x$ and $p$ are feasible solution to the primal and to the dual then $p^tb \leq c^tx$

for any vector $x$ and $p$ we define
$u_i=p_i(a^t_ix-b_i)$
$v_j=x_j(c_j-p^tA_j)$
for the definition of the dual problem the sign of $p_i $  must be the same of the sign of   $(a^t_ix-b_i)$ and the sign of $ x_j$ must be the same of the sign of $(c_j-p^tA_j)$ so $u_i$ and $v_j$ are both $\ge 0$ ... etc
I don't understand why the sign must be the same and what these amounts mean.

A: In order for you to understand, I'll first type out the primal and dual problem first in vector form, then prove the weak duality theorem, and finally explain what $u_i$ and $v_j$ mean, so as to clear your doubts.
\begin{array}{ll}
\text{min} & c^t x \\
\text{s.t.} & Ax \ge b \\
& x \ge 0
\tag{P}
\end{array}
\begin{array}{ll}
\text{max} & b^t p \\
\text{s.t.} & A^t p \le c \\
& p \ge 0
\tag{D}
\end{array}
If you think of $u_i$ and $v_j$ as components of vectors, from the RHS of these two equations, it's not hard to see that the scalar $x^t A^t p$ is the "man in the middle".
$$b^t p \le x^t A^t p \le c^t x \tag{1}\label{pf}$$
The first half of the above inequality is from the primal constraint $Ax \ge b$ and the second half is from $A^t p \le c$.  We've finished the proof the weak duality theorem.  From the above inequality, we have
\begin{array}{r@{}c@{}l}
0 &{}\le (x^t A^t - b^t) p &{}= p^t (Ax - b) \\
0 &{}\le c^t x - x^t A^t p &{}= x^t (c - A^t p)
\tag{2}
\label{eq2}
\end{array}
Therefore, comparing these two inequality with $u_i=p_i(\color{red}{A^t_i} x-b_i)$ and $v_j=x_j(c_j-p^tA_j)$, we know that

*

*To calculate $Ax - b$, we need to multiply the $i$-th row of $A$ by $x$.  (i.e. The $i$-th column of $A^t$, which is denoted by $A_i^t$.  $p_i$ is simply the $i$-th component of $p$, and $u_i$ is the $i$-th term of the sum $p^t (Ax - b)$.

*To calculate $c - A^t p$, we need to multiply the $j$-th row of $A^t$ by $p$.  (i.e. The $j$-th column of $A$, which is denoted by $A_j$.  $x_j$ is simply the $j$-th component of $x$, and $v_j$ is the $j$-th term of the sum $x^t (c - A^t p)$.

*

*$p_i,x_j$ are due to $x,p \ge 0$

*$\color{red}{A^t_i} x-b_i \ge 0$ and $c_j-p^tA_j \ge 0$ are due to $Ax \ge b$ and $A^t p \le c$.

*i.e. We have $u_i=p_i(\color{red}{A^t_i} x-b_i) \ge 0$ and $v_j=x_j(c_j-p^tA_j) \ge 0$

The importance of $u_i$ and $v_j$ is that they allow us to get \eqref{eq2}, which implies \eqref{pf}.


text:
Q: Style PHP variable in JavaScript <?php
...
$name = trim($_POST["username"]);
...
echo '';

?>

Why the style isn't working?
When I erase the style and span the code is working fine.

A: Your need to escape the quotes around 'color:red;', that's invalid:
echo ''

A: Your need to escape style=\'color:red;\'
<?php
echo '

            ';
?>


text:
Q: MocMVC giving HttpMessageNotReadableException I'm still learning my way around testing and I'm trying to get a MockMvc test to work for me. It's a simple REST controller that at this point is only doing some authentication using information from json in the post. I've actually implemented the code, so I know it's working because I get back both the correct response with the correct input and the error messages I've put together, both in a json format. My problem is that the test keeps failing with a HttpMessageNotReadableException, even though the actual code works, so I'm assuming I don't have my test set up right. Any help you guys can give would be great.
Here's my controller
@Controller
public class RequestPaymentController {
protected final Log logger = LogFactory.getLog(getClass());
private PaymentService paymentService;
private LoginService loginService;

@Autowired
public void setPaymentService(PaymentService paymentService){
    this.paymentService =  paymentService;
}
@Autowired
public void setLoginService(LoginService loginService){
    this.loginService =  loginService;
}

@RequestMapping(value = "/requestpayment", method = RequestMethod.POST, headers="Accept=application/json")
@ResponseBody
public ResponseEntity<PaymentResult> handleRequestPayment(@RequestBody PaymentRequest paymentRequest, HttpServletRequest request, HttpServletResponse response, BindingResult result) throws Exception{
    ResponseEntity<PaymentResult> responseEntity = null;
    new LoginValidator().validate(paymentRequest, result);
    boolean valid = loginService.isLoginValid(paymentRequest, result);
    if (valid){
      responseEntity = setValidResponse(paymentRequest);
    }else {
        throw new TumsException("exception message");

    }
    return responseEntity;
}

private ResponseEntity<PaymentResult> setValidResponse(PaymentRequest paymentRequest){
    PaymentResult paymentResult = paymentService.getResults(paymentRequest);

    return new ResponseEntity<PaymentResult>(paymentResult, HttpStatus.OK);
}

}

And here's my test code:
public class RequestPaymentControllerTest {

PaymentService mockPaymentService;
RequestPaymentController requestPaymentController;
HttpServletRequest mockHttpServletRequest;
HttpServletResponse mockHttpServletResponse;
PaymentRequest mockPaymentRequest;
BindingResult mockBindingResult;
LoginService mockLoginService;
PaymentResult mockPaymentResult;
MockMvc mockMvc;

@Before
public void setUp() throws Exception {
    mockPaymentService = createMock(PaymentService.class);
    mockHttpServletRequest = createMock(HttpServletRequest.class);
    mockHttpServletResponse = createMock(HttpServletResponse.class);
    mockPaymentRequest = createMock(PaymentRequest.class);
    requestPaymentController = new RequestPaymentController();
    mockBindingResult = createMock(BindingResult.class);
    mockLoginService = createMock(LoginService.class);
    requestPaymentController.setPaymentService(mockPaymentService);
    mockPaymentResult = createMock(PaymentResult.class);
    mockMvc = MockMvcBuilders.standaloneSetup(new RequestPaymentController()).build();

}

@After
public void tearDown() throws Exception {
    mockPaymentService = null;
    mockHttpServletRequest = null;
    mockHttpServletResponse = null;
    mockPaymentRequest = null;
    requestPaymentController = null;
    mockBindingResult = null;
    mockLoginService = null;
    mockPaymentResult = null;
    mockMvc = null;
}

@Test
public void testHandleRequestPayment() throws Exception{
    initializeStateForHandleRequestPayment();
    createExpectationsForHandleRequestPayment();
    replayAndVerifyExpectationsForHandleRequestPayment();

}

private void initializeStateForHandleRequestPayment(){

}

private void createExpectationsForHandleRequestPayment(){
    mockPaymentRequest.getServiceUsername();
    expectLastCall().andReturn("testuser");
    mockPaymentRequest.getServicePassword();
    expectLastCall().andReturn("password1!");
    mockLoginService.isLoginValid(mockPaymentRequest,mockBindingResult);
    expectLastCall().andReturn(true);
    mockPaymentService.getResults(mockPaymentRequest);
    expectLastCall().andReturn(mockPaymentResult);
}

private void replayAndVerifyExpectationsForHandleRequestPayment() throws Exception{
    replay(mockPaymentService, mockBindingResult, mockHttpServletRequest, mockHttpServletResponse, mockPaymentRequest, mockLoginService);
    requestPaymentController.setLoginService(mockLoginService);
    requestPaymentController.handleRequestPayment(mockPaymentRequest, mockHttpServletRequest, mockHttpServletResponse, mockBindingResult);
    mockMvc.perform(post("/requestpayment")
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON))
            .andDo(print())
            .andExpect(status().isBadRequest());
    verify(mockPaymentService, mockBindingResult, mockHttpServletRequest, mockHttpServletResponse, mockPaymentRequest, mockLoginService);

}
}

The results of the andDo(print()) are:
MockHttpServletRequest:
     HTTP Method = POST
     Request URI = /requestpayment
      Parameters = {}
         Headers = {Content-Type=[application/json], Accept=[application/json]}

         Handler:
            Type = portal.echecks.controller.RequestPaymentController
          Method = public org.springframework.http.ResponseEntity<portal.echecks.model.PaymentResult> portal.echecks.controller.RequestPaymentController.handleRequestPayment(portal.echecks.model.PaymentRequest,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,org.springframework.validation.BindingResult) throws java.lang.Exception

  Resolved Exception:
            Type = org.springframework.http.converter.HttpMessageNotReadableException

    ModelAndView:
       View name = null
            View = null
           Model = null

        FlashMap:

MockHttpServletResponse:
          Status = 400
   Error message = null
         Headers = {}
    Content type = null
            Body =
   Forwarded URL = null
  Redirected URL = null
         Cookies = []

Process finished with exit code 0

As you can see, the test passes when I'm expecting a bad request status, but I've put in logging and I know that the ResponseBody I'm sending back has a 200 status. Like I said, this is my first time with MockMvc, so I assume I've not set something up right. Any suggestions?

A: An HttpMessageNotReadableException is

Thrown by HttpMessageConverter implementations when the read method
  fails.

You also get a 400 Bad Request in your response. This should all tell you that you are not sending what your server is expecting. What is your server expecting?
@RequestMapping(value = "/requestpayment", method = RequestMethod.POST, headers="Accept=application/json")
@ResponseBody
public ResponseEntity<PaymentResult> handleRequestPayment(@RequestBody PaymentRequest paymentRequest, HttpServletRequest request, HttpServletResponse response, BindingResult result) throws Exception{

The main thing here is the @RequestBody annotated parameter. So you are telling your server to try and deserialize a PaymentRequest instance from the body of the HTTP POST request.
So let's see the request you are making
mockMvc.perform(post("/requestpayment")
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON))
        .andDo(print())
        .andExpect(status().isBadRequest());

I don't see you providing a body to the request. There should be a content(String) call somewhere in there to set the content of the POST request. This content should be a JSON serialization of a PaymentRequest.
Note that because you are using the StandaloneMockMvcBuilder, you might need to set the HttpMessageConverter instances yourself, ie. a MappingJackson2HttpMessageConverter to serialize and deserialize JSON.

Note that the BindingResult parameter should come immediately after the parameter to which it's related. Like so
@RequestMapping(value = "/requestpayment", method = RequestMethod.POST, headers="Accept=application/json")
@ResponseBody
public ResponseEntity<PaymentResult> handleRequestPayment(@Valid @RequestBody PaymentRequest paymentRequest, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception{

Don't forget the @Valid.
Note that this
requestPaymentController.setLoginService(mockLoginService);
requestPaymentController.handleRequestPayment(mockPaymentRequest, mockHttpServletRequest, mockHttpServletResponse, mockBindingResult);

is completely unrelated to the MockMvc test you are doing.

A: In my case, as sprint mvc w/ jackson (jackson-mapper-asl, v-1.9.10) deserialization requires JSON parser. And jackson requires a default constructor for http request message deserialization, if there's no default constructor, jackson will have a problem w/ reflection and throws HttpMessageNotReadableException exception.
This is to say, all the classes/sub-classes which used as Request body, (in this case) requires a default constructor. This costed me a few moments after I tried adding custom converter and other suggestions I got in stackoverflow in vain.
Or you can add Custom Deserializer or Mixin annotation to avoid adding default constructor hierachically everywhere. as described here: http://blogs.jbisht.com/blogs/2016/09/12/Deserialize-json-with-Java-parameterized-constructor. Check this if you're interested.

Seems duplicated here > Spring HttpMessageNotReadableException.

A: Make sure of the following:

*

*return object implements Serializable

*@ResponseBody annotation used on the controller method

*On your unit test
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {....})
@WebMvcTest
@AutoConfigureMockMvc

A: Probably too late to answer but just in case someone is still looking at this page.
As @Sotirios Delimanolis mentions, the problem is due to a bad request - a '@RequestBody' is specified in the parameter but never supplied in the request body. So, if you add that to request using 'content(someRequestString)' as below, it should work.
PaymentRequest  paymentRequest  = new PaymentRequest(...);
String requestBody = new ObjectMapper().valueToTree(paymentRequest).toString();
mockMvc.perform(post("/requestpayment")
                .content(requestBody)
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.status").value("SUCCESS"))
                .andExpect(jsonPath("$.paymentAmount", is(20)));

jsonPath may be used to verify the attributes on the response. In the above example, say PaymentResponse has attributes status and paymentAmount in the json response. These parts can be verified easily.
You may run into errors like -

NoClassDefFoundError: com/jayway/jsonpath/Predicate

while using jsonPath. So, make sure it is added to classpath explicitly as it is an optional dependency in spring-test and will not be available transitively. If using maven, do this:
<dependency>
  <groupId>com.jayway.jsonpath</groupId>
  <artifactId>json-path</artifactId>
  <version>2.4.0</version>
  <scope>test</scope>
</dependency>


text:
Q: Are non-generic collections in .NET obsolete? Put differently:
Is there a good reason to choose a loosely-typed collection over a type-safe one (HashTable vs. Dictionary)? Are they still there only for compatibility?
As far as I understand, generic collections not only are type-safe, but their performance is better.

Here's a comprehensive article on the topic: An Extensive Examination of Data Structures Using C# 2.0.

A: With regard to using non-generic collections for storing heterogeneous collections of stuff, you can always use List<object> to accomplish the same thing.  For this reason alone, I'd say there's almost no reason at all to touch the non-generic collections ever again.
The exception to this would be to maintain compatibility with systems written in other languages, or against previous versions of the .NET framework, but that's a pretty "edgy" case if you ask me.

A: The non-generic collections are so obsolete that they've been removed from the CoreCLR used in Silverlight and Live Mesh.

A: I can tell you that XAML serialization of collections rely on them implementing either IList or IDictionary, so non-generic collections are going to be with us for some time to come.

A: There are also issues with COM visibility - COM interop can't be used with generics

A: Going forward only generic collections should be used. There is also the benefit of avoiding boxing/unboxing of types in the collection. This is ineffecient, especially when you have a collection of value types that are converted to System.Object when stored on the collection, hence storing the values on the heap instead of the callstack.

A: There might be instances where you need to store objects of unknown types, or objects of multiple different types, but if you do indeed know the type of the objects that you want to store then I cannot see a reason not to use the generic version.
Edit: As commented you can just use List<Object> - doh!

A: I wouldn't jump and say that are obsolete or are going to be removed anytime soon.
It's true that you should avoid using non-generic collections unless you have a reason not not use a generic version. Thousands of lines of legacy (not so legacy) code is still floating around (and will be for years) that support non-generic collections such as ArrayLists. Since these were the only collections in .NET 1.0 and 1.1, it has been widely used (and abused) throughout the year.
I still occasionally have to interact with an old O/R mapper written in .NET 1.1 that returns IList objects. I have a method that does the conversion to a generic List<>, which is not efficient, but that's the way it is.
And if you need to store different objects in the same array (weird but possible) you will need a non-generic collection. The penalty of Boxing and Unboxing is something you'll have to pay anyway.
Don't be afraid to use them if you feel that you have to.

A: Yes, as far as I understand they are only there for compatibility with existing products. You should always use the type safe version (i.e. use System.Collections.Generic over System.Collections).
http://msdn.microsoft.com/en-us/library/ms379564.aspx

A: It's almost 2022, and I'm having to write a COM Visible Non-Generic collection class for consumption by a large front end commercially used program written in VB6 - the prime example of such a consumer for non generic collection classes.  So I don't see the need for these types of class disappearing any time soon, as there is still a lot of active VB6 code out there.
Meanwhile, use ArrayList and IList to underpin the custom collection class, and check that the individual items are of the type you expect before processing them, e.g.
[ComVisible(true)]
public class MyNonGenericCollection : ArrayList, IList
{
private ArrayList myList = new ArrayList();
...
public int Add(object myItem)
{
    if (!(myItem is MyItemClass))
        throw new ArgumentException(nameof(myItem));

    // code to add to the ArrayList

}


text:
Q: Shortest way to generate randomly "-1" or "+1" in C# What is the shortest way to generate "-1" or "+1" in C#? I need it to give a random direction to a vector.

A: If you want an even distributions of -1 and 1, you can use:
Random rand = new Random();

while({condition})
{
    int next = rand.Next(2) == 0 ? -1 : 1;
}

A: There's :
var r=new Random();
int direction = (r.Next(2) == 1 ? 1 : -1);

r.Next(2) will produce either a 0 or a 1 on each call.
or:
int directions[] = {1, -1};
int direction = directions[r.Next(2)];


text:
Q: React Native:call a function component within the same class I am converting a function component to class component in React Native 0.62.2 app. There are a few function components are defined within the function component. After converting to class component, there is error with those function components defined. The error is:
[ReferenceError: Can't find variable: GridImage]

Here is the code example:
export default DisplayImg extends React.Component {

   GridImage = () => {
     //component detail
   };

   render() {
     return (
     <GridImage .../>
     );
   }

}
I probably can convert GridImage to a function and call it in the same class. But is there a way to call function component defined within the same class?

A: The problem here is that Funcional (or class) components cannot be created inside other components. Just move them to the same file or to its own one.
Remember, functions always start with lower case and you can create them inside components, or outside of course. Components, instead, start with upper case and can't be created inside other components (if they only have sense or will be used in this unique component then declare it in the same file and do not export it).
And a recommendation (a good pattern from the book React Patterns from Packt) is to declare functional components as follow:
   function Component(props) {...}

and not as an arrow function.

A: You need to reference the function using this
render() {
 return (
  <this.GridImage .../>
 );
}

or just call the function in your render
render() {
 return (
   // this's better than the above approach
  {this.GridImage()}
 );
}


text:
Q: Pytest collection warning due to __init__ constructor I've been teaching myself test automation with Pytest and Selenium web driver.  All my test functions were in a single file called test_web.py, which is in a directory named tests.  I split all the functions up and placed them in their own files in a separate directory called TestCases.  For example, this is what TestCase_AddStar.py looks like:
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class Tags:
    starSysButton = '//li[button][1]'
    addStarButton = "//button[contains(text(), 'Add Star')]"
    starNameField = "//input[1]"
    modalAddButton = f"(//button[contains(text(), 'Add')])[2]"
    starPath = f"//td[contains(text(),'Bob')]"
    modalClose = "//button[@class='btn-close']"

class TestCase_AddStar():

    URL = 'http://localhost:4200'

    def __init__(self, browser):
        self.browser = browser

    def load(self):
        self.browser(self.URL)

    def test_addStar(self, browser):

        starElement = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, Tags.starSysButton)))
        starElement.click()

        newStarElement = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, Tags.addStarButton)))
        newStarElement.click()

        enterStarName = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, Tags.starNameField)))
        enterStarName.send_keys("Bob")

        clickAddButton = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, Tags.modalAddButton)))
        clickAddButton.click()

        WebDriverWait(browser, 5).until(EC.alert_is_present())
        alert = Alert(browser)
        alert.accept()

        closeModal = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, Tags.modalClose)))
        closeModal.click()

        results = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, Tags.starPath)))

        if results:
            assert results

And this is what the driver, test_web.py. looks like now:
import pytest
from TestCases.TestCase_AddStar import TestCase_AddStar
from selenium.webdriver import Firefox

@pytest.fixture
def browser():
    driver = Firefox()
    driver.implicitly_wait(10)
    yield driver
    driver.quit()

def basic_test(browser):

    add_star = TestCase_AddStar(browser)
    add_star.load()

When I run the test, I get a collection warning:

PytestCollectionWarning: cannot collect test class 'TestCase_AddStar' because it has a init constructor (from: tests/test_web.py)
class TestCase_AddStar():

I've tried adding the line "test = False" to the class TestCase_AddStar, I've tried renaming the file so that it doesn't have the word "test" in its filename, and I've tried to do away with the init constructor altogether.  Nothing has worked.  I either get a collection warning, the test is skipped outright, or the test times out because the browser doesn't load.
Does anyone have any advice?
Edit 1
TestCase_AddStar.py
class TestCase_AddStar():

    URL = 'http://localhost:4200'

    @pytest.fixture
    def load_browser(self, browser):
        browser(self.URL)
        yield

    def test_addStar(self, load_browser):

        starElement = WebDriverWait(load_browser, 10).until(EC.element_to_be_clickable((By.XPATH, Tags.starSysButton)))
        starElement.click()

        newStarElement = WebDriverWait(load_browser, 10).until(EC.element_to_be_clickable((By.XPATH, Tags.addStarButton)))
        newStarElement.click()

        enterStarName = WebDriverWait(load_browser, 10).until(EC.element_to_be_clickable((By.XPATH, Tags.starNameField)))
        enterStarName.send_keys("Bob")

        clickAddButton = WebDriverWait(load_browser, 10).until(EC.element_to_be_clickable((By.XPATH, Tags.modalAddButton)))
        clickAddButton.click()

        WebDriverWait(load_browser, 5).until(EC.alert_is_present())
        alert = Alert(load_browser)
        alert.accept()

        closeModal = WebDriverWait(load_browser, 10).until(EC.element_to_be_clickable((By.XPATH, Tags.modalClose)))
        closeModal.click()

        results = WebDriverWait(load_browser, 10).until(EC.presence_of_element_located((By.XPATH, Tags.starPath)))

        if results:
            assert results

test_web.py
import pytest
from TestCases.TestCase_AddStar import TestCase_AddStar
from selenium.webdriver import Firefox

@pytest.fixture
def browser():
    driver = Firefox()
    driver.implicitly_wait(10)
    yield driver
    driver.quit()

TestCase_AddStar()

I get the following error in traceback:
@pytest.fixture
def load_browser(self, browser):
browser(self.URL)
E       TypeError: 'WebDriver' object is not callable

Edit 2
Added .get() as recommended below. But I've got a new error now.

A: As you have noticed, a test cannot have an argument in __init__ because it is created by pytest automatically. As far as I understand, you just want to load a specific URL in your specific test class - this is something that can be done in a fixture, too. Just derive the fixture from your browser fixture and add the load function:
class TestCase_AddStar:

    URL = 'http://localhost:4200'

    @pytest.fixture
    def load_browser(self, browser):
        browser.get(self.URL)
        yield browser

    def test_addStar(self, load_browser):
        ...

Note that you don't need the __init__ method and the basic_test function (which will not work with pytest anyway). You can add a similar derived fixture into each test class with another URL parameter.
Your derived fixture will be equivalent to:
@pytest.fixture
def load_browser(self):
    driver = Firefox()
    driver.implicitly_wait(10)
    driver.get(self.url)
    yield driver
    driver.quit()

(this is just for illustration how the derived fixture would work)


text:
Q: detecting new content in an iFrame So I have an iFrame on my page. It is not loaded dynamically. It is part of the html.
I am uploading images and displaying them in the iFrame.
Is there a way to detect when the content of an iFrame has changed.
I want to call a function() once the iFrame get new content.
I've searched around, and the answers seem to deal with loading a new iFrame or changing the 'src'. I don't want to do either of those things.
The iframe has no 'src', and must be part of the starting html.
I've tried 'onchange', 'onhaschange' etc...
Thanks guys.

A: There is a event fired when the iframe loads new content, jQuery makes listening to it painless:
$('iframe#yourId').load(function() {
    yourFunction();
});

Source: iframe contents change event?


text:
Q: Regex to remove the first 2 lines of a text file I am trying to delete only the first 2 lines of a text file.
I tried using \A.*, but this gets the first line and deletes the rest.
Is there a way to do the inverse?

A: It is maybe not the most convenient way, but it is possible with Regex:
^.*\n.*\n([\s\S]*)$

With default settings (neither single-line nor multi-line modifiers) the '.' captures everything, except newline. Therfore, .*\n captures one line, including the new line character. Repeat it twice, and we are at the beginning of the third line. Now capture all characters, including the new line character ([\s\S] is a nice workaround for this behavior) until the end of the file $.
Then substitute by the first capturing group
\1

and you have everything but the first 2 lines.
The details depend on your regex engine, how you give the substitute string. And depending on the platform or the used new line character of the file, you might need to exchange the \n with \r\n or \r or the one that matches it all (\r\n?|\n).
Here is a working Demo.