text:
Q: How to pipe Picamera video to FFMPEG with subprocess (Python) I see a ton of info about piping a raspivid stream directly to FFMPEG for encoding, muxing, and restreaming but these use cases are mostly from bash; similar to:
raspivid -n -w 480 -h 320 -b 300000 -fps 15 -t 0 -o - | ffmpeg -i - -f mpegts udp://192.168.1.2:8090ffmpeg
I'm hoping to utilize the functionality of the Picamera library so I can do concurrent processing with OpenCV and similar while still streaming with FFMPEG. But I can't figure out how to properly open FFMPEG as subprocess and pipe video data to it. I have seen plenty of attempts, unanswered posts, and people claiming to have done it, but none of it seems to work on my Pi.
Should I create a video buffer with Picamera and pipe that raw video to FFMPEG? Can I use camera.capture_continuous() and pass FFMPEG the bgr24 images I'm using for my OpenCV calculation?
I've tried all sorts of variations and I'm not sure if I'm just misunderstanding how to use the subprocess module, FFMPEG, or I'm simply missing a few settings. I understand the raw stream won't have any metadata, but I'm not completely sure what settings I need to give FFMPEG for it to understand what I'm giving it.
I have a Wowza server I'll eventually be streaming to, but I'm currently testing by streaming to a VLC server on my laptop. I've currently tried this:
import subprocess as sp
import picamera
import picamera.array
import numpy as np

npimage = np.empty(
        (480, 640, 3),
        dtype=np.uint8)
with picamera.PiCamera() as camera:
    camera.resolution = (640, 480)
    camera.framerate = 24

    camera.start_recording('/dev/null', format='h264')
    command = [
        'ffmpeg',
        '-y',
        '-f', 'rawvideo',
        '-video_size', '640x480',
        '-pix_fmt', 'bgr24',
        '-framerate', '24',
        '-an',
        '-i', '-',
        '-f', 'mpegts', 'udp://192.168.1.54:1234']
    pipe = sp.Popen(command, stdin=sp.PIPE,
                    stdout=sp.PIPE, stderr=sp.PIPE, bufsize=10**8)
    if pipe.returncode != 0:
        output, error = pipe.communicate()
        print('Pipe failed: %d %s %s' % (pipe.returncode, output, error))
        raise sp.CalledProcessError(pipe.returncode, command)

    while True:
        camera.wait_recording(0)
        for i, image in enumerate(
                        camera.capture_continuous(
                            npimage,
                            format='bgr24',
                            use_video_port=True)):
            pipe.stdout.write(npimage.tostring())
    camera.stop_recording()

I've also tried writing the stream to a file-like object that simply creates the FFMPEG subprocess and writes to the stdin of it (camera.start_recording() can be given an object like this when you initialize the picam):
class PipeClass():
    """Start pipes and load ffmpeg."""

    def __init__(self):
        """Create FFMPEG subprocess."""
        self.size = 0
        command = [
            'ffmpeg',
            '-f', 'rawvideo',
            '-s', '640x480',
            '-r', '24',
            '-i', '-',
            '-an',
            '-f', 'mpegts', 'udp://192.168.1.54:1234']

        self.pipe = sp.Popen(command, stdin=sp.PIPE,
                         stdout=sp.PIPE, stderr=sp.PIPE)

        if self.pipe.returncode != 0:
            raise sp.CalledProcessError(self.pipe.returncode, command)

    def write(self, s):
        """Write to the pipe."""
        self.pipe.stdin.write(s)

    def flush(self):
        """Flush pipe."""
        print("Flushed")

usage:
(...)
with picamera.PiCamera() as camera:
    p = PipeClass()
    camera.start_recording(p, format='h264')
(...)

Any assistance with this would be amazing!

A: I have been able to stream PiCamera output to ffmpeg with something like the following:
import picamera
import subprocess

# start the ffmpeg process with a pipe for stdin
# I'm just copying to a file, but you could stream to somewhere else
ffmpeg = subprocess.Popen([
    'ffmpeg', '-i', '-',
    '-vcodec', 'copy',
    '-an', '/home/pi/test.mpg',
    ], stdin=subprocess.PIPE)

# initialize the camera
camera = picamera.PiCamera(resolution=(800, 480), framerate=25)

# start recording to ffmpeg's stdin
camera.start_recording(ffmpeg.stdin, format='h264', bitrate=2000000)

Or is that not what you're looking for?

A: Two problems that I see at first glance:

*

*In your first example, you're writing your data into the subprocess's stdout instead of its stdin. That definitely doesn't work, and probably causes a hang.

*In both examples, you're starting the process with stdin=sp.PIPE, stderr=sp.PIPE and then never reading from those pipes. That means that as soon as ffmpeg writes enough output to fill the pipe buffer, it will block and you'll have a deadlock. Use the default stdout=None, stderr=None to let ffmpeg's output go to your process's stdout and stderr, or connect them to a filehandle opened to /dev/null to discard the output. Or use the communicate method to get the output each time you write some input, and do something useful with it (like monitor the status of the streaming).

A: Hi you can use opencv & ffmpeg & restream it to wowza or else .
Here is a sample with opencv && ffmpeg
    int main(int argc, char* argv[])
{
    if (argc < 4){
        cout << "eksik parametre" << endl;
        return -1;
    }
    int fps = 1;                        //fps degeri varsayilan 1
    char *input_adress = argv[1];       //goruntunun alinacagi dosya yada adres bilgisi
    char *output_adress = argv[3];      //ciktinin gonderilecegi dosya yada adres bilgisi
    sscanf(argv[2], "%d", &fps);        //fps degeri okundu
    VideoCapture video(input_adress);   //kamera acildi
    if (!video.isOpened()){
        cout << "Yayin acilamadi!!!" << endl;
        getchar();
        return -1;
    }
    Mat frame;//frame ornegi
    FILE *pipe;//pipe icin acilan process in input streami
    char *cmd = (char*)calloc(100 + sizeof(output_adress), sizeof(char));//komut icin alan alindi
    sprintf(cmd, "ffmpeg -y -f image2pipe -vcodec mjpeg -r %d -i -  -r %d -vcodec libx264 -f flv %s", fps, fps, output_adress);//ffmpeg komutu
    //ffmpeg komutu aciliyor
    if (!(pipe = _popen(cmd, "wb"))){
        cout << "Acilamadi!!!" << endl;
        return 1;
    }
    float wait_time = 1000.0f / (float)fps;//kac milisaniye bekletilecek
    while (true)
    {
        try {
            //videodan siradaki frame okunuyor
            video >> frame;
            if (frame.empty())              //eger bos frame ise video bitmis demektir
                break;
            adjust_brightness(frame);       //parlaklik ayarlamasini yapıyoruz
            write_jpeg(frame, pipe);        //jpeg formatina cevirip pipe a yazıyoruz
            if (waitKey(wait_time) >= 0) break;
        }
        catch (Exception ex){
        }
    }
    video.release();
    return 0;
}

in write_jpeg moethod fwrite and fflush calling.
This will call with
testOutput.exe ORIGINAL_SOURCE RTMP_OUTPUT


text:
Q: PHP - convert coordinates / position to standard latitude and longitude format I've got coordinates like this: 48°22´5.901240 10°53´49.81379
First I thought just remove all the crap like ° and then you get 48.225901 latitude and 10,53498 longitude, but no it's about 30 kilometers wrong and actually 48.3683059 latitude and 10.89717 longitude smh..
How do I convert the coordinates with all the °´ bs to the proper format?
Thanks in advance

A: You can find functions to do that here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hyphenation of bold font I am getting unexpected hyphenation behavior when using bold font. Below is the output using normal font.

Below is when using bold font. Note that font is not justified on the right side.

Source code for the above in Lyx:
#LyX 2.3 created this file. For more info see http://www.lyx.org/
\lyxformat 544
\begin_document
\begin_header
\save_transient_properties true
\origin unavailable
\textclass report
\options a4paper,12pt,twoside
\use_default_options true
\maintain_unincluded_children false
\language english
\language_package default
\inputencoding auto
\fontencoding global
\font_roman "default" "default"
\font_sans "default" "default"
\font_typewriter "default" "default"
\font_math "auto" "auto"
\font_default_family default
\use_non_tex_fonts false
\font_sc false
\font_osf false
\font_sf_scale 100 100
\font_tt_scale 100 100
\use_microtype false
\use_dash_ligatures true
\graphics default
\default_output_format default
\output_sync 0
\bibtex_command default
\index_command default
\paperfontsize default
\spacing single
\use_hyperref false
\papersize default
\use_geometry false
\use_package amsmath 1
\use_package amssymb 1
\use_package cancel 1
\use_package esint 1
\use_package mathdots 1
\use_package mathtools 1
\use_package mhchem 1
\use_package stackrel 1
\use_package stmaryrd 1
\use_package undertilde 1
\cite_engine basic
\cite_engine_type default
\biblio_style plain
\use_bibtopic false
\use_indices false
\paperorientation portrait
\suppress_date false
\justification true
\use_refstyle 1
\use_minted 0
\branch Run from Main
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch Run from Here
\selected 0
\filename_suffix 0
\color #faf0e6
\end_branch
\branch a
\selected 0
\filename_suffix 0
\color #faf0e6
\end_branch
\branch b
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch c
\selected 0
\filename_suffix 0
\color #faf0e6
\end_branch
\branch PrivateInfo
\selected 0
\filename_suffix 0
\color #faf0e6
\end_branch
\branch Private Info
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch Prematter
\selected 0
\filename_suffix 0
\color #faf0e6
\end_branch
\branch blocked.sty
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch boxit.sty
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch uhead.sty
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch icthesis.sty
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch mathchars.sty
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\index Index
\shortcut idx
\color #008000
\end_index
\secnumdepth 2
\tocdepth 2
\paragraph_separation indent
\paragraph_indentation default
\is_math_indent 0
\math_numbering_side default
\quotes_style english
\dynamic_quotes 0
\papercolumns 1
\papersides 1
\paperpagestyle default
\tracking_changes false
\output_changes false
\html_math_output 0
\html_css_as_file 0
\html_be_strict false
\end_header

\begin_body

\begin_layout Standard

\series bold
something something something something something something something something
 something something something something something something something something
 something something something something something something something something
 something something something something something something
\end_layout

\end_body
\end_document

Below is when using mixed normal and bold font. I don't what is the basis for hyphenation.

Source code for the above in Lyx :
#LyX 2.3 created this file. For more info see http://www.lyx.org/
\lyxformat 544
\begin_document
\begin_header
\save_transient_properties true
\origin unavailable
\textclass report
\options a4paper,12pt,twoside
\use_default_options true
\maintain_unincluded_children false
\language english
\language_package default
\inputencoding auto
\fontencoding global
\font_roman "default" "default"
\font_sans "default" "default"
\font_typewriter "default" "default"
\font_math "auto" "auto"
\font_default_family default
\use_non_tex_fonts false
\font_sc false
\font_osf false
\font_sf_scale 100 100
\font_tt_scale 100 100
\use_microtype false
\use_dash_ligatures true
\graphics default
\default_output_format default
\output_sync 0
\bibtex_command default
\index_command default
\paperfontsize default
\spacing single
\use_hyperref false
\papersize default
\use_geometry false
\use_package amsmath 1
\use_package amssymb 1
\use_package cancel 1
\use_package esint 1
\use_package mathdots 1
\use_package mathtools 1
\use_package mhchem 1
\use_package stackrel 1
\use_package stmaryrd 1
\use_package undertilde 1
\cite_engine basic
\cite_engine_type default
\biblio_style plain
\use_bibtopic false
\use_indices false
\paperorientation portrait
\suppress_date false
\justification true
\use_refstyle 1
\use_minted 0
\branch Run from Main
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch Run from Here
\selected 0
\filename_suffix 0
\color #faf0e6
\end_branch
\branch a
\selected 0
\filename_suffix 0
\color #faf0e6
\end_branch
\branch b
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch c
\selected 0
\filename_suffix 0
\color #faf0e6
\end_branch
\branch PrivateInfo
\selected 0
\filename_suffix 0
\color #faf0e6
\end_branch
\branch Private Info
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch Prematter
\selected 0
\filename_suffix 0
\color #faf0e6
\end_branch
\branch blocked.sty
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch boxit.sty
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch uhead.sty
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch icthesis.sty
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\branch mathchars.sty
\selected 1
\filename_suffix 0
\color #faf0e6
\end_branch
\index Index
\shortcut idx
\color #008000
\end_index
\secnumdepth 2
\tocdepth 2
\paragraph_separation indent
\paragraph_indentation default
\is_math_indent 0
\math_numbering_side default
\quotes_style english
\dynamic_quotes 0
\papercolumns 1
\papersides 1
\paperpagestyle default
\tracking_changes false
\output_changes false
\html_math_output 0
\html_css_as_file 0
\html_be_strict false
\end_header

\begin_body

\begin_layout Standard
\align block
something something something
\series bold
something something something something something something something something
 something something
\series default
something something something
\series bold
something something something something something something something
\series default
something something something
\series bold
something something something something
\end_layout

\end_body
\end_document

This is affecting my report. Below is a screenshot from my report.

There is also another issue I am facing with hyphenation. Text that is already hyphenated is not hyphenated again which makes a bit sense but breaks the paragraph alignment.

By the way, I am using Lyx. Please advise.
Regards,
Meshaal


text:
Q: Prove that $S(x) = \sum\limits_{n=1}^\infty \frac{\sin nx}{n\sqrt n}$ is convergent and can be differentiated on $x\in(0, 2\pi)$ my task is to prove that $$S(x) = \sum\limits_{n=1}^\infty \frac{\sin nx}{n\sqrt n}$$ is convergent and is continuous on $(0, 2\pi)$.
I did the following:
$$S(x) = \int\limits_{n=1}^\infty \frac{\sin nx}{n\sqrt n}\mathrm{d}x =\frac{\cos(nx)}{\sqrt{n}}
$$
Applying Dirichlet Theorem, observe two series:
$$a_n = \cos(nx), \quad b_n=\frac{1}{\sqrt{n}}$$ $a_n$ is bounded, $b_n$ approaches zero, therefore the initial series is convergent.
Is it the right way to prove the convergence? And how shall I prove that it is continuous and differentiated on the given interval?

A: It's unclear what you mean by your line "$S(x)=\int_{n=1}^\infty\ldots$".
Note that
$$\left|{\sin(nx)\over n \sqrt{n}}\right|\leq{1\over n^{3/2}}\ .$$
As ${3\over2}>1$ the given series is a uniformly convergent series of continuous functions. Therefore $x\mapsto S(x)$ is a continuous $2\pi$-periodic function.
With differentiation it is different.The derived series
$$\sum_{n=1}^\infty{\cos(nx)\over\sqrt{n}}$$
is divergent at $x=0$ (since ${1\over2}<1$), but is convergent at all $x\in\ ]0,2\pi[\ $. To show the latter you need Abel's theorem. Looking at a proof of this theorem you can verify that the derived series is uniformly convergent on every interval $[\delta,\>2\pi-\delta]$, $\delta>0$. This does   guarantee that the derived series represents $S'(x)$ for all $x\in\ ]0,2\pi[\ $. The following is a plot of $S(x)$; it corroborates that $S(x)$ is differentiable at all $x\in\ ]0,2\pi[\ $.

A: $S(x)$ is not differentiable at the origin: let $x=\frac{1}{N}$ for some large $N$. We have
$$ \sum_{n=1}^{2N}\frac{\sin(nx)}{n\sqrt{n}}\geq \frac{4}{5N}\sum_{n=1}^{2N}\frac{1}{\sqrt{n}}\geq \sqrt{\frac2N} $$
while the partial sums of $\sin(n x)$ are bounded by $\frac{1}{2}\cot\frac{x}{4}\leq 2N$, so by summation by parts
$$ \left|\sum_{n>2N}\frac{\sin(nx)}{n\sqrt{n}}\right|\leq 2N\sum_{n>2N}\left(\frac{1}{n\sqrt{n}}-\frac{1}{(n+1)\sqrt{n+1}}\right)\leq \sqrt{\frac1N} $$
and $\frac{S(x)}{x}$ is unbounded as $x\to 0^+$. This implies that $S$ is not differentiable at the origin.


text:
Q: Pandas, data monotonic behavior I have a pd.DataFrame similar to the one below:
   C1       C2
    A  B  C  A  B  C
0 -10 -9 -8 -8 -7 -9
1  -9 -9 -9 -9 -9 -9
2  -8  0 -1 -8  0  0
3   0  1  1  2  3  1

In this dataframe I need to know the monotonicity for each condition (C1, C2) in each row. Basically, I am looking for a way to generate the following mask:
      0     1
0  True  True
1  True  True
2  True  True
3  True  True

The best I have managed, uses apply.
import pandas as pd

dfConcat = []
df = pd.DataFrame({
    ('C1','A'): [-10, -9, -8, 0],
    ('C1','B'): [ -9, -9,  0, 1],
    ('C1','C'): [ -8, -9, -1, 1],
    ('C2','A'): [ -8, -9, -8, 2],
    ('C2','B'): [ -7, -9,  0, 3],
    ('C2','C'): [ -9, -9,  0, 1],
})

idx = pd.IndexSlice
for c in df.columns.unique(0):
    dfConcat.append(df.loc[:,idx[c,:]].apply(lambda x: x.is_monotonic_increasing, axis=1))

mask = pd.concat(dfConcat, axis=1)

print(df)
print('')
print(mask)

I wonder if there is a way to avoid using apply here.

A: If test monotonic values per rows by Series.is_monotonic_increasing, need apply. Your solution should be simplify:
mask = (df.groupby(axis=1, level=0)
          .apply(lambda x: x.apply(lambda x: x.is_monotonic_increasing, axis=1)))
print(mask)
      C1     C2
0   True  False
1   True   True
2  False   True
3   True  False

Alternative with test imonotonic increasing in numpy:
f = lambda x: pd.Series(np.all(np.diff(x, axis=1) >= 0, axis=1))
mask = df.groupby(axis=1, level=0).apply(f)
print(mask)
      C1     C2
0   True  False
1   True   True
2  False   True
3   True  False


text:
Q: Error: You made a reference to a non-existent script @php artisan package:discover I am getting error at running composer dump-autoload at laravel project
composer dump-autoload
Generating autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
You made a reference to a non-existent script @php artisan package:discover

Then executing php artisan package:discover returns
Discovered Package: barryvdh/laravel-ide-helper
Discovered Package: cartalyst/sentinel
Discovered Package: laravelcollective/html
Discovered Package: laracasts/generators
Package manifest generated successfully.

Then again getting the same error
composer dump-autoload
Generating autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
You made a reference to a non-existent script @php artisan package:discover

What may be wrong? composer self-update or composer global update not helping.

A: You may also try to update your global composer package with this command.
composer self-update

I was having this error because I had an old version of composer that wasn't reading the @ symbols.

A: Okay, I think that composer dump-autoload is working even with that warning. (thanks to the user:Sohel0415 comments) composer was not able to run
 script with @ symbol in composer.json file.
If you want to get rid of this warning simply do
composer dump-autoload --no-scripts
or
you may delete the script with @ "post-autoload-dump": [] from you "scripts": {} in the composer.json file temporarily, and it should be all good.

A: For myself, I found that in composer.json I had the wrong references to the php command: I changed the lines that specified a location for php, for example:
"@/usr/local/bin/php artisan key:generate"

to:
"@php artisan key:generate"

After those changes, I was able to execute the command "composer update" with no error.

A: I have changed
 "scripts": {
    "post-autoload-dump": [
        "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
        "@/usr/local/bin/php artisan package:discover --ansi"
    ],
    "post-root-package-install": [
        "@/usr/local/bin/php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
        "@/usr/local/bin/php artisan key:generate --ansi"
    ]
}

to
"scripts": {
    "post-autoload-dump": [
        "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
        "@php artisan package:discover --ansi"
    ],
    "post-root-package-install": [
        "@/usr/local/bin/php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
        "@php artisan key:generate --ansi"
    ]
}

in composer.json

A: I just had this issue trying to add composer native cache-clear command to a custom script I made called composer nuke. I was using it as @clear-cache and got the message, "You made a reference to a non-existent script @clear-cache".
I guess the @ symbol is only for custom commands. I had to put composer cache-clear inside the custom command and the error was resolved and the command ran as expected then.


text:
Q: Let $f: [0,1] \to R$ be Riemann integrable, and let $a > 0$ be a real number. Show that $ f({x\over a})$ is Riemann integrable on $[0,a]$ My attempt:
Define $g: [0,a] \to R$ as $g(x) = f({x\over a})$. Moreover, let P = {$0,1$} and Q = {$0,a$}. Since $f$ is integrable, it follows that for any $\epsilon >0 \space $ $U(f, P) - L(f,P) < {\epsilon\over a}$. Notice that $\forall x \in [0,a] \exists y\in[0,1] g(x) = f(x)$. Hence, $sup_{x\in [0,a]} g(x) = sup_{x\in [0,1]} f(x)$ and $inf_{x\in [0,a]} g(x) = inf_{x\in [0,1]} f(x)$. So, we have that $U(g,Q) - L(g,Q) = (U(f,P) - L(f,P))a < {\epsilon \over a}a = \epsilon$.
Is this proof correct? Particularly, am I allowed to pick an explicit partition for $f$?
EDIT: If this proof is correct, can someone show a better way to prove this result?
Thanks.

A: Before starting a formal proof you have to be aware that the claim is completely obvious: For every partition $P$ of $[0,1]$ which is "good" for $f$ the appropriately scaled partition $P_a$ of $[0,a]$ is "good" for the function $g(y):=f\bigl({y\over a}\bigr)$ $(0\leq y\leq a)$. The rest is "going through the motions".

A: No, your proof is not correct. Given $\varepsilon>0$, you have no reason to assert that, if you take $P=\{0,1\}$, then $U(f,P)-L(f,P)<\frac\varepsilon a$. For instance, take $f(x)=x$, $a=1$ and $\varepsilon=\frac1{10}$.

A: We just need to prove that $f(x/a)$ is continious $\forall x \in [0,a]$
let $x_0\in (0,a)$ then $lim{x\to x_0}(f(x/a))$ we set $u =x/a$ with $u\to \frac{x_0}{a}=u_0<1$ as $x\to x_0$
so  $lim{x\to x_0}(f(x/a))=lim{u\to u_0}(f(u))=f(u_0)=f(\frac{x_0}{a})$
we do tha same for $x\to 0^+ $  and  $x\to a^-$
so  f(x/a) is continious thus Riemann integrable in $[0,a]$

A: The simple change that was made slows down (or speed up) $f$ by a constant factor as a function of the NEW $x$, and in turn stretches the "new" domain by the same constant factor.
This is just a change of variable. Or a composition of a linear function with the original function $f$.
Use Riemann partitions and sums with the new function, and taking care of the simple substitution, you will get the same sums as for the original $f$.


text:
Q: How do I use my mobile input results in another scripts if statement? C# Unity I'm using this script
http://www.thegamecontriver.com/2014/08/unity3d-swipe-input-for-touch-screen.html
which basically detects swipes on my android device.
How do I use this script in my character controller's if statement?
For example:
if(**swipescript detects swipe right** && character is idle)
{
    move character right
}

The part in asterisk is what I need help with.

A: Assuming that the script you posted link to is named SwipeControl, you can add a public boolean variable called swipedRight. Each time player swipes right, set it to true.
Then in your main script where you are suppose to check for that condition, set it to false when it is true.
In SwipeControl:
    public bool swipedRight = false;
//Check if drag distance is greater than 20% of the screen height
        if (Mathf.Abs(lp.x - fp.x) > dragDistance || Mathf.Abs(lp.y - fp.y) > dragDistance)
        {//It's a drag
              //check if the drag is vertical or horizontal
              if (Mathf.Abs(lp.x - fp.x) > Mathf.Abs(lp.y - fp.y))
              {   //If the horizontal movement is greater than the vertical movement...
                  if ((lp.x>fp.x))  //If the movement was to the right)
                  {   //Right swipe
                      //Set Swiped Right to true
                      swipedRight  = true;
                      Debug.Log("Right Swipe");
                  }
                  else
                  {   //Left swipe
                      Debug.Log("Left Swipe");
                  }
              }
            else
            {   //the vertical movement is greater than the horizontal movement
                 if (lp.y>fp.y)  //If the movement was up
                 {   //Up swipe
                     Debug.Log("Up Swipe");
                 }
                 else
                 {   //Down swipe
                     Debug.Log("Down Swipe");
                 }
            }
        }

Then from the other Script:
public CharacterController cController;
Rigidbody ccRigidBody;

SwipeControl swipeControl;

void Start()
{
        //Get reference to SwipeControl script
        swipeControl = GameObject.Find("GameObjectSwipeControlIsAttachedTo").GetComponent<SwipeControl>();

        //Get reference to the Rigidbody in the CharacterController
        ccRigidBody = ccRigidBody.GetComponent<Rigidbody>();
}

void Update()
{
        if (swipeControl.swipedRight && ccRigidBody.velocity==Vector3.zero)
        {
            //Do your stuff here

            //Then set swipedRight to false
            swipeControl.swipedRight = false;
        }else if(swipeControl.swipedRight){
            swipeControl.swipedRight = false;
        }
}

So your if(**swipescript detects swipe right** && character is idle) code is translated to if (swipeControl.swipedRight && ccRigidBody.velocity==Vector3.zero) in the code above.


text:
Q: Animate parent widget on event to fit child's size First of all, the solution could be obvious given that I'm a newbie in Flutter, but I've searched for many hours to no avail, so on to the issue.
I'm trying to have a markdown description in Flutter, which should be able to be expanded when tapping a chevron.
I have tried AnimatedContainer, AnimatedSize, Flex with Expanded and also tried looking into the warning "It should only be called from paint callbacks or interaction event handlers (e.g. gesture callbacks)."
 Flutter gives me if I try to get the size of the child before it's painted.
I've taken a look to several places, including StackOverflow questions that I'll link right here:

*

*Flutter Layout Row / Column - share width, expand height

*https://github.com/flutter/flutter/issues/16061

*How to get a height of a Widget?
The next bit of code is where I'm trying to get the animation of expanding/collapsing going.
The variable isExpanded is just a boolean and the function _onPressed just toggles a change in that boolean.
Based on it I should get the markdown body in its total height or just show a bit of it.
@override
Widget build(BuildContext context) {
  markdown = Markdown(body);
  var icon = (isExpanded) ? Icons.expand_less : Icons.expand_more;
  var iconButton = IconButton(icon: Icon(icon), onPressed: _onPressed);

  return Container(
    child: Column(children: <Widget>[
      AnimatedContainer(
        // constraints: BoxConstraints(), this is where I'd like to set the change from 30% to infinity
        child: SingleChildScrollView(child: markdown),
        curve: Curves.bounceIn,
        duration: Duration(milliseconds: 300),
      ),
      iconButton
    ]),
  );
}

What I'm trying to do is a Trello-like animation. In the phone app, the description of a card is expandable and collapsable. When expanded, it takes just the height it needs, even overflowing the screen. This means the scrollable part is the Widget that contains the description and whatever other widgets there are, not the description itself.
What actually happens is:

*

*If I try to set a height (in BoxConstraints) in with MediaQuery and then expand to Size.infinity animation can't be actually handled because it goes from bounded to unbounded.

*If I try to set the parameter height in the AnimatedContainer to 30% of the screen and then to infinity, when it's infinity the content just disappears.

A: Maybe use SizeTransition or ScaleTransition. Here is an answer that take use of the following widgets to collapse and expand a widget.


text:
Q: Is "for any" needed in "We dont want to stay here for any longer than we have to."?
"We don't want to stay here for any longer than we have to."

Is this sentence correct? And does it mean the same as "We don't want to stay here any longer than necessary." ? I am unsure about the need of "for" and "any" maybe they can or should be left out to simply

"We don't want to stay here longer than we have to."

A: We don't want to stay here for any longer than we have to.
There's nothing wrong with the sentence; it's grammatical.
The word "long" also mean a long time or for a long time.  The preposition "for" in the sentence is optional, but we usually drop it when it's used in the said sense.
So the sentence will be more idiomatic without the preposition.
As for the use of the adverb "any" with  not in the sentence,  it's been used to emphasize the word "longer" in the sense of "not even a little bit".
If you don't want to emphasize the longer, you can drop the any.


text:
Q: Resources for astrostatistics Being an astrophysic grad student with mathematical background, I have recently become interested in the field of astrostatistics. I know that this is a quite new field that combines astrophysics, statistics and data mining due to the huge amount of data that our telescopes are able to generate. We need sophisticated tools to be able to process it.
I want to learn more about this topic, so I want to ask for some good books or resources on this subject. I have a course on general statistics and I am not at all afraid of abstract mathematical reasoning.
Could you please recommend something in this line?

A: Profs. Eric Feigelson and Jogesh Babu at Penn State are widely seen as "Godfathers" of astrostatistics. Every year, they run the Summer School in Statistics for Astronomers which I attended in 2014.
The summer school's web page is publically accessible, and lecture slides and materials for exercise sessions in R with code and instructions. These sessions are connected thematically to some of the lectures, and all exercises consist of functioning code which can be run at home in e.g. RStudio. The lectures are a great introduction to a wide variety of techniques in astrostatistics, and it is easy to get one's hands on the gears in the exercises, but of course lecture slides are a bit superficial.
If one wants to go more in depth, the course materials also contain a long suggested reading list. Feigelseon & Babu are also the authors of a graduate-level astrostatistics textbook, which is built around real-life examples often encountered in astronomy, and which also contains a number of exercises in R.

EDIT: If you are more interested in the data mining/machine learning side of things, try AstroML, a combination of software module, text book and online resources like Jupyter notebooks etc. - the book costs what books cost, but many online resources are free.


text:
Q: java 8 nested null check list of objects I am trying to do a nested null check and then clear the values in map in the nested object if the map is not null.
The following is my hypothetical code. I am wondering if this is the right way to do it or is there a more elegant solution to this.
package exp.myJavaLab.Experiments;

    import java.util.*;

    public class OptionalTest {

        public Inner inner;

        public static void main(String[] args) {

            OptionalTest testObj = new OptionalTest();
            Pojo pojo1 = new Pojo();
            pojo1.id = 1;
            Map<String, String> dataMap = new HashMap<>();
            dataMap.put("a","b");
            pojo1.dataMap = dataMap;
            Pojo pojo2 = new Pojo();
            pojo2.id = 2;

            Inner inner = new Inner();
            inner.pojoList = Arrays.asList(pojo1, pojo2);

            testObj.inner = inner;

            System.out.println(testObj);

            Optional.ofNullable(testObj.inner)
            .map(Inner::getPojoList)
            .ifPresent(pojos -> pojos.forEach(pojo -> {
                    if (pojo.getDataMap() != null) {
                        pojo.getDataMap().clear();
                    }
                }));

            System.out.println(testObj);

        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("OptionalTest{");
            sb.append("inner=").append(inner);
            sb.append('}');
            return sb.toString();
        }
    }

    class Inner {
        public List<Pojo> pojoList;

        public List<Pojo> getPojoList() {
            return pojoList;
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("Inner{");
            sb.append("pojoList=").append(pojoList);
            sb.append('}');
            return sb.toString();
        }
    }

    class Pojo {

        public Map<String, String> dataMap;
        public int id;

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("Pojo{");
            sb.append("dataMap=").append(dataMap);
            sb.append(", id=").append(id);
            sb.append('}');
            return sb.toString();
        }

        public Map<String, String> getDataMap() {
            return dataMap;
        }

        public int getId() {
            return id;
        }
    }

A: In my opinion Collections should never be null.
You could declare your pojoList and dataMap as private and instantiate them.
Your class then needs some add-methods. So you are sure getDataMap() never returns null:
class Pojo {
    private Map<String, String> dataMap = new HashMap<>();

    public Map<String, String> getDataMap() {
        return dataMap;
    }

    public void add(String key, String value) {
        dataMap.put(key, value);
    }
}

Then you don't need to check for null:
Optional.ofNullable(testObj.inner)
.map(Inner::getPojoList)
.ifPresent(pojos -> pojos.forEach(pojo -> { pojo.getDataMap().clear(); }));


text:
Q: Why classes that implement variant interfaces remain invariant? C# 4.0 has extended the co and contravariance further for generic types and interfaces. Some interfaces (like IEnumerable<T>) are covariants, so I can do things like:
IEnumerable<object> ie = new List<string>();

but what about this line? I got a compile-time error
List<Object> list = new List<String>();
//Cannot implicitly convert type List<string>' to List<object>'

I mean, if List<T> implement IEnumerable<T> why List<T> is still invariant? Is out there a good counterexample that explain why this should not be allowed in C#?

A: Firstly, classes are always invariant in C#. You can't declare a class like this:
// Invalid
public class Foo<out T>

Secondly - and more importantly for the example you've given - List<T> couldn't be declared to be covariant or contravariant in T anyway, as it has members both accepting and returning values of type T.
Imagine if it were covariant. Then you could write this (for the obvious Fruit class hierarchy):
List<Banana> bunchOfBananas = new List<Banana>();
// This would be valid if List<T> were covariant in T
List<Fruit> fruitBowl = bunchOfBananas;
fruitBowl.Add(new Apple());
Banana banana = bunchOfBananas[0];

What would you expect that last line to do? Fundamentally, you shouldn't be able to add an Apple reference to an object whose actual execution-time type is List<Banana>. If you add an apple to a bunch of bananas, it falls off. Believe me, I've tried.
The last line should be safe in terms of types - the only values within a List<Banana> should be null or references to instances of Banana or a subclass.
Now as for why classes can't be covariant even when they could logically be... I believe that introduces problems at the implementation level, and would also be very restrictive at the programming level as well. For example, consider this:
public class Foo<out T> // Imagine if this were valid
{
    private T value;

    public T Value { get { return value; } }

    public Foo(T value)
    {
        this.value = value;
    }
}

That would still probably have to be invalid - the variable is still writable, meaning it counts as an "in" slot. You'd have to make every variable of type T read-only... and that's just for starters. I strongly suspect that there would be deeper problems.
In terms of pure pragmatism, the CLR has supported delegate and interface variance from v2 - C# 4 just introduced the syntax to expose the feature. I don't believe the CLR has ever supported generic class variance.

A: If we want to discuss adding (accepting) something (T) to List, we must talk about CONTRAVARIANCE (COVARIANCE doesn't allow accepting), so:
List<Fruit> bunchOfFruits = new List<Fruit>();
// This would be valid if List<T> were contravariant in T
List<Banana> bunchOfBananas = bunchOfFruits;
bunchOfBananas.Add(new Apple()); // not possible! We have compile error, coz in spite of Apple is a Fruit it is not ancestor of Banana. No logical mistakes.
bunchOfBananas.Add(new BigBanana()); // possible coz of rules of C#! we deal with a descendant of Banana
bunchOfBananas.Add(new Fruit()); // possible, coz CONTRAVARIANCE of List. We deal with the ancestor of Banana. No logical mistakes.

So as we can see VARIANCE should work either for classes too as for interfaces and delegates (classes in general, not only for collections). And I think it can be implemented in future versions of .NET.


text:
Q: Statistical tests for comparing (black box) model performance on two datasets Introduction
I have two datasets, dataA (real images) and dataB (generated images). I also have a model that has been trained on dataC. dataC might have some overlap with dataA but for certain does not have any overlap with dataB. The model is a black box to me (in fact, it sits behind an API), I know nothing about it or about its training dataset and procedure, I only receive the model outputs.
I want to know if the model "behaves" the same way on dataA as on dataB, i.e. test the hypothesis that the distribution of dataB is similar to the distribution of dataA (with respect to the task performed by the model).
Regression model
If the model is a regression model, e.g. detects some landmarks in the image, I can calculate some real-numbered error, e.g. the euclidean distance between the actual landmark position and the one predicted by the model. Applying the model to dataA as well as dataB gives me two collections of errors: errorsA and errorsB. The errors are not necessarily normal distributed (depends on the model I am testing).
Which statistical tests can I use to compare errorsA and errorsB? I have considered:

*

*Calculating confidence intervals on errorsA and errorsB, respectively and check if they overlap.

*Use a statistical test to check the hypothesis that errorsA and errorsB follow the same distribution. I have been using a two-sided KS test.

Classification model
Same question, but now I do not have errors, but instead some metric such as accuracy or F1. Use Chi-Square test as proposed here?

A: You say that you have access only to the model output (predictions, or rather errors), and you want to compare these for two different data sets A and B to check if they return similar results. The question now is what do you want to compare. If a mean is enough - that is comparing whether the two data sets return the same mean error - then a t-test could be used.
If the residuals from the t-test are not normally distributed then a non-parametric version can be used such as Mann-Whitney, which has no assumptions on the distribution, but also doesn't compare the means. The null hypothesis is that the distributions of both populations are equal.
However, if you plan to make a lot of predictions, then such tests will be mostly useless (difference between statistical and practical significance) and you may as well just use a standard predictive metric to compare the differences in model performance, such as accuracy, F1,... or a proper scoring rule if you want to be correct, such as logarithmic scoring rule.


text:
Q: Use Google Sign In cookies to open an already signed in page (puppeteer) What I want is to get a cookie and re-use it whenever I want to open an already signed in puppeteer instance. I tried this, but it didn't work:
Function which would get cookies:
async function writeCookies(page, cookiesPath) {
    const client = await page.target().createCDPSession();
    // This gets all cookies from all URLs, not just the current URL
    const cookies = (await client.send("Network.getAllCookies"))["cookies"];
    console.log(cookies)
    console.log("Saving", cookies.length, "cookies");
    // fs.writeFileSync(cookiesPath, JSON.stringify(cookies));
    console.log(cookiesPath)
    console.log(cookies)
    // await fs.writeJSON(cookiesPath, cookies);
  }

How I implemented it:
const page = await browser.newPage();
time = new Date()
await page.goto("https://accounts.google.com/ServiceLogin/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=AddSession")
await page.$eval('#identifierId', (el) => (el.value = "test@gmail.com"));
await page.click("#identifierNext > div > button > div.VfPpkd-RLmnJb");
await page.waitForSelector('#password > div.aCsJod.oJeWuf > div > div.Xb9hP > input', { visible: true });
await page.$eval('#password > div.aCsJod.oJeWuf > div > div.Xb9hP > input', (el) => (el.value = "Tester"));
await page.waitForSelector('#passwordNext > div > button > div.VfPpkd-RLmnJb', { visible: true });
await sleep(1000)
await page.click("#passwordNext > div > button > div.VfPpkd-RLmnJb");
writeCookies(page,"./WebHook.js")

How I would send the cookies:
await page.setExtraHTTPHeaders({cookies :`${cookies}`})

I also tried this way:
async function restoreCookies(page, cookiesPath) {
  try {
    // const cookies = await fs.readJSON(cookiesPath);
    let buf = fs.readFileSync(cookiesPath);
    let cookies = JSON.parse(buf);
    console.log("Loading", cookies.length, "cookies into browser");
    await page.setCookie(...cookies);
  } catch (err) {
    console.log("restore cookie error", err);
  }
}

Maybe I am retrieving the wrong cookies.


text:
Q: joins on multiple keys in linq How to write this query in Linq?
SELECT e.STARTDATE,
       e.REASON,
       s.DESCRIPTION
  FROM E_JOURNAL j inner join
       E_ABSENCE e on j.JOURNALID = e.JOURNALID AND
               e.ABSENCEHISTORYID = (SELECT MAX(ABSENCEHISTORYID)
                                       FROM E_ABSENCE
                                      WHERE JOURNALID = j.JOURNALID) INNER JOIN
       E_STATUS s on j.CURRENTITEMSTATUSID = s.ITEMSTATUSID INNER JOIN
       E_NATURE n on j.ITEMNATUREID = n.ITEMNATUREID
 WHERE j.EMPLOYEEID = 113

A: Try code like this
using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication57
{
    class Program
    {
        static void Main(string[] args)
        {
            int employeeId = 113;

            List<E_JOURNAL> employee = E_JOURNAL.journals.Where(x => x.JOURNALID == employeeId).ToList();

            var results = (from j in employee
                           join s in E_ABSENCE.absenses on j.JOURNALID equals s.JOURNALID
                           orderby s.ABSENCEHISTORYID descending
                           select new {
                               startDate = s.STARTDATE,
                               reason = s.REASON,
                                description = E_STATUS.statuses.Where(x => x.CURRENTITEMSTATUSID == j.CURRENTITEMSTATUSID).Select(x => x.DESCRIPTION).FirstOrDefault()
                           }).FirstOrDefault();
        }

    }
    public class E_JOURNAL
    {
        public static List<E_JOURNAL> journals = new List<E_JOURNAL>();

        public int JOURNALID { get; set; }
        public int ITEMNATUREID { get; set; }
        public int EMPLOYEEID { get; set; }
        public int CURRENTITEMSTATUSID { get; set; }

    }
    public class E_STATUS
    {
        public static List<E_STATUS > statuses = new List<E_STATUS>();

        public string DESCRIPTION { get; set; }
        public int CURRENTITEMSTATUSID { get; set; }

    }
    public class E_ABSENCE
    {
        public static List<E_ABSENCE> absenses = new List<E_ABSENCE>();

        public int JOURNALID { get; set; }
        public DateTime STARTDATE { get; set; }
        public string REASON { get; set; }
        public int ABSENCEHISTORYID { get; set; }
    }
    public class E_NATURE
    {
        public static List<E_NATURE> natures = new List<E_NATURE>();

        public int ITEMNATUREID { get; set; }
    }

}


text:
Q: Does modifying files dates trigger time Machine backups? I'm having glitches with my photos library (300 GB) that could be solved by using the "touch" command, which modifies the modify-date of files.
My question :
Will this trigger a Time Machine backup, for every file which date has been modified ?
Conversely, if I modify a modify-date (for example using the touch command) and set it back to its former value afterwards, will the file still being back-upped ?
More generally, does modifying the creation date and the modification date of a file trigger a backup ? (I would like to change the creation date of the pics to the date when they were shot)
Thanks


text:
Q: Trying to use Zelory compressor in fragment with Kotlin I am trying to implement image compression for my file upload to Firebase Storage. Normal image choosing and upload works perfectly, but i would now like to implement image compression. I came across Zelory compressor and i am trying to implement but i can't seem to use the code correctly.
I am using this within a fragment and when i am trying to load the bitmap into the compressor line its seems to be giving an error on context:

My code before this is taking the ImageUri and converts it to a file path as needed by compressor.
val image_file_path = File(mImageUri.path)
val ctx = activity!!.applicationContext

val tempBitmap = Compressor.compress(ctx, image_file_path)

mImageUri is what i was using when just choosing and uploading as normal to firebase.
I have had a look at many examples of people trying to use this code and i can't to see what i am doing wrong. is it something to do with the fact that i am using it in a fragment? If so i would not mind changing my layout to just upload in the normal layout rather than a fragment.
I initially had the ctx input as just activity thinking that was the problem but this doesnt take away the error. any help?

A: I resolved this by not using the Zelory Tool. It is complicated and found a more "standard" library to  achieve the same.
The way to achieve the compression is to take your image, convert to Bitmap and follow the instructions in this link I found:
https://android--code.blogspot.com/2018/04/android-kotlin-compress-bitmap-example.html
It's honestly self explanatory, and the only difference i had to the code was that they use a static drawable whereas i had to convert my URI to Bitmap. i did this by using the following line:
val bitmap = MediaStore.Images.Media.getBitmap(activity?.contentResolver,mImageUri)

In the above, I use activity? because I was performing this operation in a fragment. Also, mImageUri is a companion object to which I assign the URI after selecting from the phones gallery.
The rest is as per the link.
Good luck to anyone else trying this. to give you a sense of the compression. going this route, I was able to compress a 8MB photo to 350kb using WEBP. Very efficient!
PS: When using WEBP, I managed to apply a 1% quality as per the above compression stated without much loss of quality. Even when downloading the compressed image on a PC, you would not say it was compressed.


text:
Q: Why does margin not work WPF? <StackPanel Grid.Column="1" Orientation="Horizontal" Margin="0,0,0,0" VerticalAlignment="Top" HorizontalAlignment="Right">
    <StackPanel.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Margin" Value="2,0,0,0"/>
        </Style>
    </StackPanel.Resources>
    <Button Padding="5" x:Name="btnUnlock" Click="btnUserMenu_Click_1" Style="{DynamicResource ButtonStyleBasic}">
            <Image Stretch="None" Source="/WpfApplication1;component/Images/view_text.png" ImageFailed="Image_ImageFailed"/>
    </Button>
    <Button Padding="5"  Margin="2,0,0,0" x:Name="btnUserMenu" Click="btnUserMenu_Click_1" Style="{DynamicResource ButtonStyleBasic}"  >
        <Image Stretch="None" Source="/WpfApplication1;component/Images/personal.png" ImageFailed="Image_ImageFailed"/>
    </Button>
    <Button Padding="5" x:Name="btnQuit"   Margin="2,0,0,0" Click="btnQuit_Click" Style="{DynamicResource ButtonStyleBasic}">
            <Image Stretch="None" Source="/WpfApplication1;component/Images/exit.png" UseLayoutRounding="True"/>
    </Button>
    </StackPanel>

If i remove margin inside <Button ... no margin is applied.This is the case when i apply custom template.. Here is the template...
<Style x:Key="ButtonStyleBasic" TargetType="{x:Type Button}">

            <Setter Property="FocusVisualStyle" Value="{StaticResource ButtonFocusVisual}"/>
            <Setter Property="Background" Value="{StaticResource ButtonNormalBackground}"/>
            <Setter Property="BorderBrush" Value="{StaticResource ButtonNormalBorder}"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="Padding" Value="1"/>

            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                    <Border BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true" CornerRadius="2" BorderThickness="{TemplateBinding BorderThickness}">
                            <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsKeyboardFocused" Value="true">

                            </Trigger>
                            <Trigger Property="ToggleButton.IsChecked" Value="true">

                            </Trigger>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Foreground" Value="#ADADAD"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

A: The template in your style does not bind to the Margin using a TemplateBinding, hence the margin properties on Buttons with this style will be disregarded.


text:
Q: Object array property adds index when loading with an array Objects are somewhat new to me.
I have an object property which is an array...  $obj->something[].
I have a multidimensional associative array...  $schedule[$year][$month][$day][$event].
When I load the array into the object property the object adds an index.
$obj->something[] = $schedule;

So when I pull the data out of the object I get the extra index...
[0][$year][$month][$day][$event]

I tried array_replace but that didn't seem to do anything.  How do I avoid getting the extra leading index?

A: Assign the array directly to the property without the square brackets.
$obj->something = $schedule;

using [] at the end of the left-hand side of an assignment statement appends the assigned value to an array (creating the array if it doesn't exist yet).
If you have initialized the something property to an empty array, but it's supposed to hold your schedule array, you want $schedule to replace the empty array, but the way your doing it puts $schedule into that array instead.

A: You could try array_merge. http://php.net/manual/en/function.array-merge.php
class Foo {
   private $something = [];

   function mergeEm(array $somethingElse) {
      $this->something = array_merge($this->something, $somethingElse);
   }
}


text:
Q: Practical way of keeping up-to-date backup servers? What is the approach generally used when you want to have backup physical servers?
Currently I have a Linux server running a database, a samba share, a webapp and some scripts; and a Windows Server, running some third-party software. What I would like was to be able to have a ready backup server to enter in production in case of failure, but how to keep them up-to-date? I've seen some expensive solutions for Windows; for Linux I've wondered if I really have to build an array of scripts.

A: You are talking about a general cold-standby solution. This is a very broad topic with several possible solutions. The following are just a few of them.
For the database I would really recommend looking into a standby server. MySQL got a good slave-replication, other databases got that too.
For files the easiest thing would be using rsync in daemon mode. You could also look into block level replication tools like DRBD or distributed file systems, but those might hurt performance.
You can also create images using a combination of LVM and snapshots. Or you could use a tool like Image for Linux(which is commercial software, but pretty cheap for what it can do).
For configurations you can either use some sync-scripts or rsync or even some configuration management like Puppet.


text:
Q: Angular 7: snapshot.params id comes undefined Im working with this fake api 'jsonplaceholder' getting and sending data with one model: Users. My goal is to display a list of Users and on each click I navigate to other component where I can see it's Id. But so far I can only display the list; the id comes undefined and I can't do nothing more. I tried to follow this post but it didnt work. Can someone help?
The Service:
getUsers(): Observable<Users> {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      })
    };
    return this.http.get<Users>(this.urlUsers, httpOptions).pipe(
      retry(3),
      catchError(this.handleError));
  }

Home.TS
  users: Users;
  id: string;
  constructor(private router: Router,
    private dataService: DataService,
    private route: ActivatedRoute) {
    this.id =  this.route.snapshot.params['id'];
    console.log(this.id); -----> undefined
  }

  ngOnInit() {
    this.getUsers();
 }

  getUsers() {
    this.dataService.getUsers().subscribe(data => {
      this.users = data;
      console.log(this.users);

    });
  }

getById(){
  this.dataService.getById(this.id).subscribe(data => {
    this.users=data['id'];
    this.router.navigate(['/second, users.id'])
  })
}

HOME HTML

{{user.name}}
 ---->backend returns 404

EDIT:My Routes
const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'second',
    component: SecondComponent
  },
  {
    path: '**',
    redirectTo: '/'
  },
  {
    path: '',
    component: HomeComponent
  },
];

And paramsMap don't work either...

A: You have forgotten to add second/:id to your routes. That is the reason backend could not find the route.
const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'second',
    component: SecondComponent
  },
  {
    path: 'second/:id',
    component: SecondComponent
  },
  {
    path: '**',
    redirectTo: '/'
  },
  {
    path: '',
    component: HomeComponent
  },
];

A: You need to get paramMap check documentation
this.route.paramMap['id'];


text:
Q: Flutter project not picking up local flutter package updates Flutter 3.3.9
I created a flutter project and I reference it as a dependency in another flutter project like so:
      dev_dependencies:
          flutter_test:
            sdk: flutter
          my_utils:
            path: ../my_utils

When I added the local package to my project initially, I could see and debug the referenced local package just fine. I made updates to the my_utils package, did a "flutter pub get" in the project referencing my_utils, and the changes are not being picked up.
I added a new class to my_utils and it is not finding it in the other project.
I have this in analysis_options.yaml:
include: package:flutter_lints/flutter.yaml

linter:
  rules:
     depend_on_referenced_packages: false

Setting depend_on_referenced_packages to true didn't help.
How do I make my changes/updates in my_utils show in my referencing project?
Thanks

A: did you export the files properly ? e.g files inside src/?
my_utils file structure should be like the following:
lib/
...src/
......my_impl.dart
...my_utils.dart

and in your my_utils.dart should contain the following:
export 'src/my_impl.dart';

I recommend you use melos for managing multi-package projects. it might solve your problem. Also with melos bootstrap, you get flutter pub get running in all packages with one command.
you can follow the installation from here


text:
Q: Syslogd: hardware error The machine has been sending these messages to the terminal, paired with beeps from the speaker on the motherboard. These messages appear every 5 minutes, sometimes naming CPU2, sometimes CPU3.

Message from syslogd@pc at Mar 25 17:52:20 ...
kernel:[ 7200.792043] [Hardware Error]: CPU:2 MC0_STATUS[-|CE|-|-|AddrV|CECC]: 0x9467400000000136
Message from syslogd@pc at Mar 25 17:52:20 ...
kernel:[ 7200.792059] [Hardware Error]:   MC0_ADDR: 0x00000001f5925200
Message from syslogd@pc at Mar 25 17:52:20 ...
kernel:[ 7200.792065] [Hardware Error]: Data Cache Error: during L1 linefill from L2.
Message from syslogd@pc at Mar 25 17:52:20 ...
kernel:[ 7200.792073] [Hardware Error]: cache level: L2, tx: DATA, mem-tx: DRD
Message from syslogd@pc at Mar 25 17:52:20 ...
kernel:[ 7200.792085] [Hardware Error]: CPU:2 MC1_STATUS[-|CE|-|-|AddrV]: 0x9400000000000151
Message from syslogd@pc at Mar 25 17:52:20 ...
kernel:[ 7200.792093] [Hardware Error]:   MC1_ADDR: 0x00000000004aa210
Message from syslogd@pc at Mar 25 17:52:20 ...
kernel:[ 7200.792098] [Hardware Error]: Instruction Cache Error: Parity error during data load.
Message from syslogd@pc at Mar 25 17:52:20 ...
kernel:[ 7200.792105] [Hardware Error]: cache level: L1, tx: INSN, mem-tx: IRD
Message from syslogd@pc at Mar 25 17:52:20 ...
kernel:[ 7200.792115] [Hardware Error]: CPU:2 MC2_STATUS[Over|CE|-|-|AddrV|CECC]: 0xd40041000000010a
Message from syslogd@pc at Mar 25 17:52:20 ...
kernel:[ 7200.792124] [Hardware Error]:   MC2_ADDR: 0x00000001d4fe5200
Message from syslogd@pc at Mar 25 17:52:20 ...
kernel:[ 7200.792129] [Hardware Error]: Bus Unit Error: GEN parity/ECC error during data access from L2.
Message from syslogd@pc at Mar 25 17:52:20 ...
kernel:[ 7200.792137] [Hardware Error]: cache level: L2, tx: GEN, mem-tx: GEN

System has an AMD Phenom II x4 955, standard clock speed. BIOS is up to date (except for a beta version). System runs on the newest version of Linux Mint Debian Edition. Temps are on the high end, but still acceptable (~45 degrees idle).
I have tested the system with memtest86+ for 15 hours (5 passes), as well as prime95 for in total over 24 hours. No errors were reported by either, and the system is stable. Strangely enough no syslogd messages appeared during prime95's run. Windows does not report errors in event log, but I have not been in windows long enough to be too sure of this. I understand that CPUs rarely break, but maybe this is one of the rare cases?
Is there a problem in just disabling the messages from syslogd, as there are no problems I can detect? If not, what is next?


text:
Q: Testing normality for residuals I have an Randomized block design experimental set up and a data consisting of species abundance. I would like to test for normality of the residuals, as in unexplained variance due tot the blocks.
I am new to statitstics. To find the resisuals I understand I need to create a linear model (lm()). But from the examples I have found online, it only works with one parameter/column (like an environmental variable), right? How do I deal with my data? Do I need to use the diversity function?

A: To test the normality assumption I would recommend to use the Shapiro-Wilk test in your case. (if you have more than 30 observations)
shapiro.test(ins(data.lm))

In order to check the homoskedasticity assumption the Bartlett and Levene test are appropriate tools.
bartlett.test(count ~ spray, data = InsectSprays)
leveneTest(count ~ spray, data = InsectSprays)


text:
Q: How do you modify an Abstract Data Type(ADT) stack? Using the stack interface definition, what string is at the top of the stack and what string is at the bottom?
I know the .push method just adds the selected item to the top of the stack, but what I'm having trouble with is when there is a pop method within a push method or when there is a peek method within a push method.
I also need help on the line that says String name = stringStack.pop();
StackInterface<String> stringStack = new MyStack<>();

stringStack.push( "Jane" );
stringStack.push( "Jess" );
stringStack.push( "Jill" );
stringStack.push( stringStack.pop());
stringStack.push( stringStack.peek());
stringStack.push( "Jim" );
String name = stringStack.pop();
stringStack.push( stringStack.peek());

I expect the order to be:
TOP Jim Jim Jill Jill Jess Jane BOTTOM

A: In a situation like this:
stringStack.push( stringStack.pop());

You just have to keep in mind that push has to know what value to push, before the value is pushed. How does it know what value to push? Evaluating pop(), of course! So an item is popped first, then push knows what item to push, and pushes to back. In other words, A pop inside a push overall does nothing to the stack.
What about:
stringStack.push( stringStack.peek());

Instead of popping the top item off and then pushing it, this will only look at the top item, and then pushes it onto the stack. So overall this is just "copying" the top item.
Here is what the stack looks like after each line (left is the top):
stringStack.push( "Jane" );
// Jane
stringStack.push( "Jess" );
// Jess Jane
stringStack.push( "Jill" );
// Jill Jess Jane
stringStack.push( stringStack.pop());
// Jill Jess Jane
stringStack.push( stringStack.peek());
// Jill Jill Jess Jane
stringStack.push( "Jim" );
// Jim Jill Jill Jess Jane
String name = stringStack.pop();
// Jill Jill Jess Jane
stringStack.push( stringStack.peek());
// Jill Jill Jill Jess Jane


text:
Q: Is there a way of updating a field on a table and affecting another field on another table? I have two tables in my database. So what i typically do is insert into tableOne (id, names) values (valueOneInt, valueOneVarChar) but i also want valueOneVarChar to be inserted into another table. Typically I do this separately, is there a shortcut for it?

A: You could do this with a trigger. E.g.:
delimiter //

CREATE OR REPLACE TRIGGER table_one_insert_tr
BEFORE INSERT ON table_one
FOR EACH ROW
BEGIN
    INSERT INTO table_two (varchar_col)
    VALUES (NEW.table_one_varchar);
END;

delimiter ;


text:
Q: Connections between conditional expectations and equality in distributions Let $X\in L^2(\Omega,\mathcal{F},P)$ and $\mathcal{G}\subset\mathcal{F}$ be sub-$\sigma$ fields and define the random variable $Y=E(X\mid\mathcal{G})$, which is to say $Y$ is a $\mathcal{G}$-measurable random variable $\int_{A}YdP\mid_{\mathcal{G}}=\int_{A}XdP\mid_{\mathcal{G}},\forall A\in \mathcal{G}$.
If $X\overset{d}{=}Y$, is it true that $X\overset{a.s.P}{=}Y$?
What if $X\in L^1(\Omega,\mathcal{F},P)$?
What if $X\in L^q(\Omega,\mathcal{F},P)$ for general $q$?

A: Assuming only that $X\in L^1(\mathcal F)$, there is an even, strictly convex, function $\Phi:\Bbb R\to(0,\infty)$ such that $\Bbb E[\Phi(X)]<\infty$. [This is a special case of a uniform integrability criterion due to Ch. de la Vallée-Poussin.] By the conditional form of Jensen's inequality,
$$
\Bbb E[\Phi(X)|\mathcal G]\ge \Phi\left(\Bbb E[X|\mathcal G]\right)=\Phi(Y),
$$
almost surely. Taking expectations and using the fact that $Y$ has the same distribution as $X$:
$$
\Bbb E[\Phi(X)]=\Bbb E[\Bbb E[\Phi(X)|\mathcal G]]\ge\Bbb E[\Phi(Y)]=\Bbb E[\Phi(X)],
$$
forcing $\Bbb E[\Phi(X)|\mathcal G]=\Phi(Y)$ a.s.
Because $\Phi$ is strictly convex, we must have $\Bbb P[X=Y|\mathcal G]=1$ a.s., hence $\Bbb P[X=Y]=1$.

A: Hint for the  $L^2$ case: Because $Y$ is orthogonal to $X-Y$, you have $E[X^2] = E[Y^2]+E[(X-Y)^2]$.


text:
Q: Regular Expression for username I need help on regular expression on the condition (4) below:

*

*Begin with a-z

*End with a-z0-9

*allow 3 special characters like ._-

*The characters in (3) must be followed by alphanumeric characters, and it cannot be followed by any characters in (3) themselves.

Not sure how to do this. Any help is appreciated, with the sample and some explanations.

A: You can try this:
^(?=.{5,10}$)(?!.*[._-]{2})[a-z][a-z0-9._-]*[a-z0-9]$

This uses lookaheads to enforce that username must have between 5 and 10 characters (?=.{5,10}$), and that none of the 3 special characters appear twice in a row (?!.*[._-]{2}), but overall they can appear any number of times (Konrad interprets it differently, in that the 3 special characters can appear up to 3 times).
Here's a test harness in Java:
    String[] test = {
        "abc",
        "abcde",
        "acd_e",
        "_abcd",
        "abcd_",
        "a__bc",
        "a_.bc",
        "a_b.c-d",
        "a_b_c_d_e",
        "this-is-too-long",
    };
    for (String s : test) {
        System.out.format("%s %B %n", s,
            s.matches("^(?=.{5,10}$)(?!.*[._-]{2})[a-z][a-z0-9._-]*[a-z0-9]$")
        );
    }

This prints:
abc FALSE
abcde TRUE
acd_e TRUE
_abcd FALSE
abcd_ FALSE
a__bc FALSE
a_.bc FALSE
a_b.c-d TRUE
a_b_c_d_e TRUE
this-is-too-long FALSE

See also

*

*regular-expressions.info/Lookarounds, limiting repetitions, and anchors

A: So basically:

*

*Start with [a-z].

*Allow a first serving of [a-z0-9], several times. 1)

*Allow

*

*at most one of [._-], followed by

*at least one of [a-z0-9]

*three times or less.

*End with [a-z0-9] (implied in the above).

Which yields:
^[a-z][a-z0-9]*([._-][a-z0-9]+){0,3}$

But beware that this may result in user names with only one character.

1) (posted by @codeka)

A: try that:
^[a-zA-Z](([\._\-][a-zA-Z0-9])|[a-zA-Z0-9])*[a-z0-9]$

1) ^[a-zA-Z]: beginning
2) (([._-][a-zA-Z0-9])|[a-zA-Z0-9])*: any number of either alphanum, or special char followed by alphanum
3) [a-z0-9]$

A: Well, because I feel like being ... me. One Regex does not need to rule them all -- and for one of the Nine, see nqueens. (However, in this case there are some nice answers already; I'm just pointing out a slightly different approach.)
function valid(n) {
  return (n.length > 3
    && n.match(/^[a-z]/i)
    && n.match(/[a-z0-9]$/i)
    && !n.match(/[._-]{2}/)
}

Now imagine that you only allow one ., _ or - total (perhaps I misread the initial requirements shrug); that's easy to add (and visualize):
&& n.replace(/[^._-]/g, "").length <= 1

And before anyone says "that's less efficient", go profile it in the intended usage. Also note, I didn't give up using regular expressions entirely, they are a wonderful thing.


text:
Q: Pass JWT to rabbitmq over websockets This is my current RabbitMQ / Stomp setup which works fine with username and password authentication.
My end goal is to pass a JWT instead of username and password. I already have access to the token on the front-end and I do not want to conduct a UAA server. I have added this plugin to RabbitMQ and tried doing what step 3 of the Authorization flow says with no luck.

Client passes the token as password when connecting to a RabbitMQ
node. The username field is ignored.

I get the following error:
<<< ERROR
content-length:16
version:1.0,1.1,1.2
content-type:text/plain
message:Processing error
content-length:16

Edit
Another observation is that after adding "Authorization: Bearer" in front of the token I get the a new error.
<<< ERROR
content-length:33
version:1.0,1.1,1.2
content-type:text/plain
message:Bad CONNECT
content-length:33

Access refused for user 'rabbit'

RabbitMQ Setup
Docker
FROM rabbitmq

RUN rabbitmq-plugins enable --offline rabbitmq_management
RUN rabbitmq-plugins enable --offline rabbitmq_stomp
RUN rabbitmq-plugins enable --offline rabbitmq_web_stomp
RUN rabbitmq-plugins enable --offline rabbitmq_auth_backend_oauth2

COPY ./advanced.config /etc/rabbitmq/advanced.config
COPY ./rabbitmq.conf /etc/rabbitmq/rabbitmq.conf

EXPOSE 15671 15672 15674 61613

advanced.config
[
  {rabbit, [
    {default_user, <<"admin">>},
    {default_pass, <<"guest">>},
    {auth_backends, [rabbit_auth_backend_oauth2, rabbit_auth_backend_internal]}
  ]},
  {rabbitmq_management, [
    {enable_uaa, false}
  ]},
  {rabbitmq_auth_backend_oauth2, [
    {resource_server_id, <<"rabbitmq">>},
    {key_config, [
      {default_key, <<"key-1">>},
      {signing_keys,
        #{<<"key-1">> => {pem, <<"-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAr8xZBLjW7yMZJobc/IFo
6New9jlCvSx8I6aSBrU+EU+TN6iXF13Tqqp62L/TWlTrYlErsu2yvLknhN4VU7qX
g38/2wZn9/kKFYCkeaDe3lDxl+4rNGq1TSEXCzndIDfVzgxZvKZ0Vt5+mvr1cxR7
7V6MFcJvIHMv4MdIqAUwABFFHvonp56yzh7g/UsAk6XlaqhoZQ1NrPyWpG6YgHwg
hFibyh0ZI3gD7H0UshpR9VVPLTgrAUnf3qWMpEXKO2ePmrTVwwDpL25n5DdhaBz6
e+YSonTT7KigxeklRPrKc7km29l0frml+8jOsQsx7L2WCD/HqR6J5iVDZ5mDfeKN
vcixi+nkLTCyV1jsHEzteSmGgmAE6SrSMXV+oPz2xLGKEGJJQWS+Ll1l5BD1MmZE
6DqLoe8FHew54M7zniCxkhDIHcpVY3IYcv2gohhaxm9MHkSHaj6bwAGQcORwgGho
ETVr7RXyvCD5Vsr6VqDqknjleP1tLi/gnlzP099SLmGiB6y/v1mW1s3tDpI/F7b7
WWDyHRqW9YfGEPYOmNdELcizW9UxY2MFvK4LlacRaXzzDEXmiP/FK84Qse14Nmyi
6tfqIYe+PRWbA7ztOaBlmDnkhxHcLufB48t4dleUWmj+6VOXQGXef10p4rQNeOo5
N5dJoYqveUJ6Lfln3C25NJcCAwEAAQ==
-----END PUBLIC KEY-----">>}
         }
      }]
    }
  ]}
].

rabbitmq.conf
loopback_users.guest = false
total_memory_available_override_value = 2684354560
listeners.tcp.default = 5672
management.tcp.port = 15672
web_stomp.ws_frame = binary

Current Stomp client setup
      var client = new StompJs.Client({
        brokerURL: 'ws://localhost:5900/ws',
        connectHeaders: {
          login: 'admin',
          passcode: 'guest'
        },
        debug: log => (
          console.log(
            log
          )
        ),
        reconnectDelay: 5 * 1000,
        heartbeatIncoming: 4 * 1000,
        heartbeatOutgoing: 4 * 1000,
      });

Ideal JWT setup
      var client = new StompJs.Client({
        brokerURL: 'ws://localhost:5900/ws',
        connectHeaders: {
          login: 'rabbit',
          passcode: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc0FjdGl2ZSI6dHJ1ZSwiX2lkIjoiNWZkNzc0MDY4NzE3NTU2OWFlMTIxNmRmIiwiY29kZSI6IjIwMDAwMDEwNiIsInVzZXJuYW1lIjoiYW50b25pc2NvZGV1cCIsImVtYWlsIjoiYW50b25pc0Bjb2RldXAuc29mdHdhcmUiLCJmaXJzdE5hbWUiOiJBbnRvbmlzIiwibGFzdE5hbWUiOiJQaXNoaWFzIiwib3JnYW5pc2F0aW9uIjoiQ29kZVVwIFNvZnR3YXJlIEx0ZCIsInJvbGUiOnsiX2lkIjoiNWZkMmEyM2VjOTJmOTFjNTFkOTIzMTZiIiwibmFtZSI6ImN1c3RvbWVyIiwicmVhZCI6W3siX2lkIjoiNWZkMmEyM2VjOTJmOTFjNTFkOTIzMTViIiwibmFtZSI6ImFjY291bnRzIn0seyJfaWQiOiI1ZmQyYTIzZWM5MmY5MWM1MWQ5MjMxNWMiLCJuYW1lIjoiY3JtIn0seyJfaWQiOiI1ZmQyYTIzZWM5MmY5MWM1MWQ5MjMxNWQiLCJuYW1lIjoid2FyZWhvdXNlIn1dLCJjcmVhdGUiOltdLCJ1cGRhdGUiOltdLCJtb3ZlIjpbXSwiX192IjowfSwiX192Ijo3LCJzY29wZXMiOlsicmFiYml0bXEuY29uZmlndXJlOiovKiIsInJhYmJpdG1xLndyaXRlOiovKiIsInJhYmJpdG1xLnJlYWQ6Ki8qIl0sImlhdCI6MTYwNzk1NjkzNCwiZXhwIjoxNjA4NTYxNzM0LCJhdWQiOlsiaHR0cHM6Ly9iaXpjb3VyaWVyLmV1IiwicmFiYml0bXEiXSwiaXNzIjoiaHR0cHM6Ly9yZXN0LmJpemNvdXJpZXIuZXUifQ.Ypqa16YuqH3rfwxAQZ_RdJRF21h6jYX07r-zaB3AP_qshU_xBiP9RpFvFkws13i0_X3Ou-qKxSdAF51T1t-Ob5V4LiXLJKsesmZIeIGXs-Dhc79u5UqhOdGIzPgRTlieOIUmrFKsPBWf7FnoR-lgd9gH8ge3Wp2f2vOqU24JsEjkvtlTGLS1aId27UVz0d2qxMLWf-9kLxW4mmuM2UCeRsnznpPaZbAfhq2tHHIy3EtGeIIiOsAE0lM9BfJRF36kjZcpcMZSnhTrkZjiDsrUuiVd-W27MVJRYFVpULkGrpa5RkkDG5ZbwNNSn0VUMZB2PiQTchtNyoffutPzhktxieDO5T0OzrSXl5VAtgZFHi5oPLWtPGVejNiWMFsY9u1ale6NRDSReeQjPPEqzpH-tfnugkwyv_jhL6WnfmoeEBgcuyK7eBvrg7uJbQFdwMrRQXkGn_ATn0XhJWI-Hia3muNbNbvdL0jgkZBv0HFPsx84n3-IEx672_6Wy2qtLtFcnUgGr4ThRVp8PE0ro21JdvjFbwgq9k5Qhv5MA6wgB6nt7vtuP1SZ17ekIPE6izwHUPZsWsqJg6v108H1B13J2yxK5LcdsCb8Z8uRhiRSKt4Cs6MHsZg0GCOjym2YHXyN21Wpw3behq0GxUiSrU4qkADujDb6nNzaLq2_ecn5bOI'
        },
        debug: log => (
          console.log(
            log
          )
        ),
        reconnectDelay: 5 * 1000,
        heartbeatIncoming: 4 * 1000,
        heartbeatOutgoing: 4 * 1000,
      });

You can decode the JWT here

A: I think that you are missing a scope in your JWT
See the documentation here:
https://github.com/rabbitmq/rabbitmq-server/tree/master/deps/rabbitmq_auth_backend_oauth2
It says:

Token scope returned by OAuth 2.0 provider must include RabbitMQ resource scopes that follow a convention used by this plugin: configure:%2F/foo means "configure permissions for 'foo' in vhost '/'") (scope field can be changed using extra_scopes_source in advanced.config file.

(BTW: I coudn't find the "extra_scopes_source" in your advanced.config as well)
Although I didn't test it, failing to provide the scope would logically result in an access denied error.


text:
Q: Does encrypted MongoDB data Stay encrypted in MiniMongo? I'm working on an application following HIPAA guidelines. One of the requirements is that all data stored on any device must follow encryption standards. That being said, any device with names or sensitive personal information (ePHI) must be encrypted in case of malicious intent.
Does MongoDB data remain encrypted in MiniMongo, or is it possible to encrypt MiniMongo data itself?

A: I received additional details answering this question via contacting Abigail Watson as per Dan's suggestion.
The short answer is yes, the data comes in encrypted to MiniMongo and the browser has the ability to see the decrypted information.
The longer answer is that Meteor is almost HIPAA compliant out of the box. Since the regulations were made in 1996, they are a little nebulous when it comes to what you can get in trouble for due to its age. As long as the data is encrypted and secure on the server with SSL/TLS certified encryption, has unique user ids/roles/passwords, and an HIPAA audit log we are following the conventions.
Playing it safe and doing data wipes on local servers and making the data intelligently encrypted should help protect us and ePHI.

A: MongoDB data will be transmitted as is to the client over the wire (that is, encrypted). Once on the client though, it has to be decrypted in order to be displayed to the user. So I think you're within the guidelines.
For more information,

*

*ping Abigail Watson, who's working on HIPAA applications developed with Meteor.

*check out Mylar, an encrpytion layer for Meteor developed at MIT


text:
Q: EditText numperPassword with right-to-left languages I'm writing an app in persian language (it's a right to left language). Everything is ok with EditText with inputType "text" and "number", but those EditTexts that have inputType="numberPassword", show the entered number in the starting position of the text (android:gravity set to "left"), but the numbers are always left to right no matter what language is. This makes the user confuse. It's a problem mostly in new android versions (api 15 and above). I made a trick for this, I renamed layout-fa to to layout-fr and values-fa to values-fr (cause farsi is right to left language and france is left to right) and there's layout-en & values-en folder for switch the language to english in the app.
It's working now but is there a better solution? Did anybody faced this problem?
thanks in advance...

A: problem solved with this tag in widget :
android:layoutDirection="ltr"


text:
Q: asp.net calender control problem iam using calender control in asp.net 2.0
as it is using master pages.. iam opening a window form content pages..
on window.close it is giving me null object as its not getting form name
you help will be appreciated
code on content page:

<input ID="Text1" runat="server" readonly="readOnly" type="text" />

function openwindow() {
    window.open('/Calender.aspx', 'calendar_window','width=154,height=188');
}

code on opened window from content page
protected void Calender1_SelectionChanged(object sender, EventArgs e)
    {
        string strjscript = "";
        Literal1.Text = strjscript;
    }

    protected void Calendar1_dayrender(object sender, DayRenderEventArgs e)
    {
          if(e.Day.Date==DateTime.Now)
        {
            e.Cell.BackColor = System.Drawing.Color.LightGray;
        }

    }

A: Looks like you are not following this tutorial but not exactly what it is doing.
Points to note:
1: Make sure you are naming your form
2: Pass textbox reference via querystring i.e. Calender.aspx?formname=frmCalendar.txtDate
3: Path to your calender.aspx is correct.
You are close to solution but may be you need to share your main page code as well for us.
Edit 1
Ok I see now what you are saying. Add this script block to your content page:

Although if possible try using jquery datepicker and you can post your code and issue if you want to go that route.


text:
Q: Can subclasses (not using inheritance) have it's creator reference? I don't know how to exactly write a title for this, so let me explain my problem. I'm using Python 3 to implement a bot on Slack, but my doubt is about how classes can be used to solve it.
I'm using Slack's API to create a bot to send messages. When you use the API to send a message, it returns some parameters that indentifies this message (like an id). With this "id" I can change the message's text or delete it, for example.
I created a main class that will be used to handle the API requests and therefore, send messages. I also have another class called SlackMessage that keeps the message's "id" and will have some methods, like change it's text or delete itself, for example. So, when I send a message through the main class, an instance of SlackMessage class will be returned.
As the first class is handling the requests to the API, the SlackMessage class should use it when changing it's text. Would be right the SlackMessage class have the main class as reference when it's being created and use it to update itself?
Here's some code to explain what I mean:
class Slack:
    def __init__(self, token):
        self._token = token

    def send_message(self, message):
        result = requests.post(...)

        #Get message's reference
        ts = result["ts"]
        channel = result["channel"]
        text = result["text"]

        reference = {"ts": ts, "channel": channel, "text": text}

        return SlackMessage(self, reference)

    def update_message(self, message_reference):
        result = requests.post(...)

    class SlackMessage:
        def __init__(self, slack_client, reference):
            self._slack_client = slack_client
            self._reference = reference

        def change_text(self, text):
            self._reference["text"] = text
            self._slack_client.update_message(self._reference)

And how would be the best method to create a way to delete the message? Should I do it the same way?
Sorry if this question is a duplicate, I searched for an answer but didn't know how to explain the problem with a few words.


text:
Q: Rename FileNames Using Concatenation I currently have an excel spreadsheet that has the following output
Old_Name               PlayerID        PlayerName
20190324181982.MTS      1               Jake Smith
20190324181963.MTS      2               Greg Johnson
20190324181923.MTS      3               Jake De Maria

The "Old Name" Column keeps track of the video files I upload to my computer. I have attempted VBA code (see below) that identifies the "Old Name" in the stored folder and changes it to playerid + playername. For example, 1Jake Smith.
Sub autofilename()
    Dim dca As Workbook
    Dim checklist As Worksheet
    Dim oldfilepath As String
    Dim old_name As String
    Dim playerid As String
    Dim playername As String
    Dim lastrow As Integer

    Set dca = ActiveWorkbook
    Set checklist = dca.Sheets("Venezuela_list")
    lastrow = checklist.Cells(Rows.Count, "A").End(xlUp).Row
    oldfilepath = "C:\Users\nhwal\Docs\Practice"

    For a = 2 To lastrow
        old_name = checklist.Cells(a, 1).Value
        playerid = checklist.Cells(a, 2).Value
        playername = checklist.Cells(a, 3).Value

        On Error Resume Next
        Name old_name & old_name As old_name & playerid & playername & " MTS.url"
    Next a
End Sub

Unfortunately, the code I tried does not change the names of my files. Does anyone know how to adjust my code to get the files to change names? Thanks in advance!

A: You could t try:
Option Explicit

Sub trst()

    Dim Row As Long, LastRow As Long
    Dim FileLocation As String

    With ThisWorkbook.Worksheets("Sheet1") '<- Change Workbook / Sheet names

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        FileLocation = "C:\Users\nhwal\Docs\Practice\"

        For Row = 2 To LastRow
            Name FileLocation & .Range("A" & Row).Value As FileLocation & .Range("A" & Row).Value & " " & .Range("B" & Row).Value & " " & .Range("C" & Row).Value & " MTS.url"
        Next Row

    End With

End Sub


text:
Q: Nesting columns under a new header column in a DataFrame I have a time series DataFrame df1 with prices in a ticker column, from which a new DataFrame df2 is created by concatenating df1 with 3 other columns sharing the same DateTimeIndex, as shown:

Now I need to set up the ticker name "Equity(42950 [FB])" to become the new header and to nest the 3 other columns under it, and to have the ticker's prices replaced by the values in the "closePrice" column.
How to achieve this in Python?

A: pd.MultiIndex:
d = pd.DataFrame(np.arange(20).reshape(5,4), columns=['Equity', 'closePrice', 'mMb', 'mMv'])

arrays = [['Equity','Equity','Equity'],['closePrice', 'mMb','mMv']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)

df = pd.DataFrame(d.values[:, 1:], columns=index)
df

    Equity
    closePrice  mMb mMv
0   1           2   3
1   5           6   7
2   9           10  11
3   13          14  15
4   17          18  19


text:
Q: Why would a company decide to develop in Ruby on Linux and not on Windows? I would like to know if anyone meet a similar situation.
What are the reasons for a company to decide that you must develop using Linux environment (virtual machine) and not Windows environment?
Here there's no workstations with Linux at all - all computers have Windows installed. There's one production Linux server.
Is it possible to develop ruby in Windows and deploy your application on Linux?
What would be the advantages of not using Windows just for development? Is it just better performance?
thank you

A: Apart from the obvious reason, possible problems with compatibility of certain gems, database servers etc., there is another, perhaps more subtle one:
There is a cultural difference between Windows folks and *nix folks, reflected in many ways, from the way we perform everyday tasks (such as searching for files on disk, or searching for a string in files), the way we set up and administer the system, to what do we picture when someone mentions "an application".
Ruby comes from the second camp, and while it runs perfectly on Windows as well, it somehow reflects the world it's been born and maintained within. A banal example would be irb. To someone used to a command line interface, irb is absolutely natural and comfortable tool. Command line does exist in Windows world as well, but it's really pretty hidden and usually the interface for the last resort. Whole set of Perl-isms was borrowed by Ruby, and Perl was created as a Unix scripting language.
So, in my opinion, picking Linux as a development platform could make you a better Ruby programmer, simply by forcing you to adopt the cultural guidelines of *nix world.

A: My work environment uses Linux too. We develop mostly in Java, but it's a similar story.
The company's Windows laptops are severely hobbled by anti-virus software (which is very necessary, as in a large company any security hole will eventually be exploited by viruses inadvertently dragged into the company).
Our Linux boxes are locked down to the extent that we can't do major configuration changes, but no virus scanner/intrusion detector is necessary. Relative to the company standard, our Linux machines are a joy to work with! Our memory and CPU are mostly available for the tasks at hand.
This setup has also proven easier and cheaper for our admins to manage.

A: I have developed a substantial and complex web site with Ruby on Rails using Windows for development and two different flavors of Linux for production. There were a couple of hiccups related to libraries that must be compiled, like ImageMagick.
When I got a new laptop that came with Vista, I was unable to get MySQL to run on it, and I switched to using Linux inside VirtualBox. While I doubt that I will ever be converted to the Linux user experience, I did find that it was somewhat easier to get all of the components working together properly on Linux. Now, I do almost all of my dev work inside VirtualBox, as it allows me to keep all of my client work compartmentalized, and I am easily able to spin up new development environments that have specific requirements that might not play well with my preferred desktop setup.
So, yeah, it can be done, but don't disregard the potential of working inside VirtualBox. It's a wonderful environment.

A: I would think the main advantage is that your development environment is similar to your target deployment environment, so when you finally deploy, you hopefully have fewer issues related to a different environment. This might be more relevant for desktop apps than for server-based web apps, though in both cases you'd have to make sure your dependencies (UI widgets or server process) are available and similar enough on both platforms.
Other advantages? Developing on Linux is probably cheaper. Can't say the performance is always going to be better though.

A:
What are the reasons for a company to decide that you must develop using Linux environment (virtual machine) and not Windows environment?

*

*Other than some technical issue i think windows need license and Linux doesn't

*Mostly Ruby is used by small companies so using linux benificial for them

Is it possible to develop ruby in Windows and deploy your application on Linux?

YES. But it is good practise to have a same Development & Production enviorment

What would be the advantages of not using Windows just for development? Is it just better performance?

Most of the Servers run on Linux and it's always good to have a same Development & Production enviorment

A: As others have noted, there's a big advantage in having your deployment and development environments be at least reasonably similar.
I have to disagree with those who have said that compatibility is not a big deal.  We have a pretty big site and use a lot of gems, and we've run into problems with the sole Windows-based developer on the team.  There are certain gems he just can't use properly or at all (e.g. json, gitjour, mechanize, hpricot), which means there are features to which he can't contribute.  We've encountered zero platform differences between Mac OS X and Linux.
The fact of the matter is that Windows is a distinctly second-class platform in the Ruby and especially the Rails world.  You can do it, but I wouldn't recommend it.

A: It is certainly possible to develop Ruby on windows that is deployable to Linux.
There may be some difference with Gems if they were written in low level C, but this is pretty rare.

A: reformat a harddisk and install ubuntu, boot from a flash disk, run as a vm through virtual box or the like, there are many ways to run linux in your situation, and it will be an easier development solution for you. its always better to develop in the os environment you plan to deploy on. also, you could check out jruby. if you still decide to develop on windows, checkout

*

*help.github.com for how to install
git and cygwin on windows

*ruby-lang.org to install ruby for
windows

*and rubygems.org to install rubygems
for windows

heh, the last best reason: a terminal shell in linux isn't limited to 80 columns wide ;)