text:
Q: Propagating a "volatile" property I put "volatile" because it's only vaguely so.
I have a class which has a property called StopRequested.  This flag can be set by other threads at any time, and needs to indicate to my code that it should stop what it's doing and exit (this is a Windows Service based process, and when Stop is called, all processing needs to clean up and stop).
I wish to create some other classes to do the actual brunt of the processing work, however these classes also have to be aware of the "stop" flag.  You can't just pass the flag because it will pass a copy, and you can't pass properties as ref types.
So how do you propagate a property that might change at any time into other classes?
The only thing I can think of is to pass a reference to the parent class, but I dislike coupling the worker classes to the parent for one flag.  Any suggestions would be appreciated.
EDIT:
Here's a basic example:
public class A
{
    public bool StopRequested { get; set; }

    private Worker = new Worker();

    public void DoWork();
    {
        worker.DoWork();
    }
}

public class Worker
{
    public void DoWork()
    {
        while(!StopRequested)
        {
            ....
        }
    }
}

A: You could have each of your worker classes have their own StopRequest property and then just set that whenever StopRequest is flagged.
private List<IStopable> WorkerClasses = new List< IStopable > ()

public Bool StopRequest{
    get
    {
          return _stopRequest;
    }
    set
    {
        _stopReqest = value;

        foreach (var child in WorkerClasses)
            child.StopRequest = value;
    }
}

A: Like Rubens said, use an event. What you described basically defines event to a T:
Propagate a property change to other classes.
There is actually a facility in .NET that provides this already, albeit in a generic way: INotifyPropertyChanged. This interface provides a single event, PropertyChanged, that allows a class to notify any listeners of any property change.
In your case, you could easily provide your own interface that is more specific:
interface IStopNotifier
{
    event EventHandler StopRequested;
}

This interface would be implemented by your main work manager (whatever it is), and could propagate itself like so:
class WorkManager: IStopNotifier
{
    public event EventHandler StopRequested;

    protected void OnStopRequested()
    {
        if (StopRequested != null) StopRequested(this, new EventArgs());
    }

    public void StopAllWorkers()
    {
        OnStopRequested();
    }

    public Worker CreateWorker<T>()
        where T: Worker
    {
        var worker = new T(this);
        return worker;
    }
}

class abstract Worker: IDisposable
{
    public Worker(IStopNotifier stopNotifier)
    {
        stopNotofier.StopRequested += HandleStopRequested;
    }

    private IStopNotifier m_stopNotifier;
    private bool m_stopRequested = false;

    internal void HandleStopRequested(object sender, EventArgs e)
    {
        m_stopRequested = true;
    }

    public void Dispose()
    {
        m_stopNotifier.StopRequested -= HandleStopRequested;
    }
}

A: Why don't to create an event to handle stop requests?


text:
Q: How to fill textbox with selected JSON using select form? Help, how to select JSON using selectform and fill some textbox with selected JSON from controller.
For example when i select 1st item in selectform
textbox1=data1, textbox2=data1, texbox3=data3 if i select 2nd item from selectform textbox1=data2, textbox2=data2, texbox3=data2 and so on.
VIEW

<script>
         var url = $('.url-location').data('url');
         $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: url + "Projects/GetProjects",
                datatype: "json",
                success: function (result)
                {
                    var project = '<option value="">Please Select Project List</option>';
                    for (var i = 0; i < result.data.length; i++) {
                        project += '<option value="' + result.data[i].ProjectID + '">' + result.data[i].ProjectID + '</option>';
                        var data1 = result.data[i].ProjectID;
                        var data2 = result.data[i].Description;
                        var data3 = result.data[i].ConReference;
                    }
                    $("#ProjectList").html(project);
                    $('#ProjectList').change(function ()
                    {
                        $('#ProjectNo').val(data1);
                        $('#ProjectName').val(data2);
                        $('#CustomerPONo').val(data3);
                    });
                }
            });
         });
    </script>

CONTROLLER

public ActionResult GetProjects(string username)
        {
            bool morePages = false;
            ProjectListDataSet rscProjct = null;
            try
            {
                rscProjct = _connection.ProjectSvc.GetList("Company = 'CBM'", 0, 0, out morePages);
                List<object> result = new List<object>();
                foreach (DataRow dr in rscProjct.ProjectList.Rows)
                {
                    result.Add(new {
                        ProjectID = dr["ProjectID"],
                        Description = dr["Description"],
                        ConReference = dr["ConReference"],
                        StartDate = dr["StartDate"],
                        ConCustNum = dr["ConCustNum"],
                        Company = dr["Company"]
                    });
                }
                return Json(new { data = result }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception x)
            {
                return Json(new { data = "", error = x.Message }, JsonRequestBehavior.AllowGet);
            }
        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: parametric curves, parameter and integration I just started learning about parametric curves and I find it confusing that we have a 3rd variable but this 3rd variable "t" is some imaginary variable....I dont get what the difference is between this parameter "t" and the good ole 3 variable functions...This gets confusing for me especially when I do area in a bounded region integration related questions because I am trying to understand what this variable "t" for parameter really means...is this just some fake number or the 3rd dimension Z?
The example below uses t as the bounds of integration but why do that? Doesn't this graph look just like you regular integration graph where you can just use the x bounds for finding the area bounded by the curve?

NOTE: this example has an error in it, where it says t= 3/2 it should be t = 2

A:
I just started learning about parametric curves and I find it
  confusing that we have a 3rd variable but this 3rd variable "t" is
  some imaginary variable....I dont get what the difference is between
  this parameter "t" and the good ole 3 variable functions...

Hopefully the visualization below will help convey the different types of information that can be communicated by expressing a function in parametric form.
Here, we are taking the standard parametrization of the unit circle:
$$x(t)=\cos t, \quad y(t)=\sin t, \quad 0\le t\le 2\pi.$$

Top left: plot of the space curve $(t,x(t),y(t))$ in $\mathbb{R}^3$; $t$, $x$, and $y$ information is all available simultaneously
Top right: plot of the plane curve $(x(t),y(t))$; at time $t^*$, the point on the graph is $(t^*,x(t^*),y(t^*))$; $t$ information is suppressed in the static version (usually shown in a textbook) although we gain that information in an animation like this; plot conveys $x$-$y$ relationship over time; usually called the phase plane/space in applications
Bottom left: plot of the plane curve $t$ vs. $x(t)$; at time $t^*$, the point on the graph is $(t^*,x(t^*))$; conveys $t$-$x$ information; usually called time-state space in applications
Bottom right: plot of the plane curve $t$ vs $y(t)$; at time $t^*$, the point on the graph is $(t^*,y(t^*))$; conveys $t$-$y$ information; usually called time-state space in applications
PS Think of the black dot as the "fly" mentioned in the other answer. The curve traced out is the flight path of the fly.

A: In your example, you could actually do what you suggest - namely find $x$ bounds for the curve in question - but in order to do that you would have to rewrite the parametric curve in terms of $y$ and $x$ only:
$$x^2=t^2-2+t^{-2}\\
y^2=t^2+2+t^{-2}\\
\Rightarrow y^2=x^2+4.$$
From this point you could proceed as normal. We do not have to do this for any reason, however, and in fact since the curve is already parametrized it is just as easy to continue on in that way.
It is usually easiest to think of a parametrization by describing the values of $x$ and $y$ over a period of time. In the two dimensional case as you have, let's say that we have a fly walking around on our coordinate grid. At any particular time $t$, the fly has an $x$ value and a $y$ value, and we describe each as a function of time $t$.
We could also, as you note, imagine that $t=z$ in the Cartesian three dimensional space. This helpful way of thinking about a parametrized curve is no longer helpful when we consider a three dimensional case - imagine a fly buzzing through your room, and at any time it's $x$, $y$, and $z$ coordinate can be given as a function of $t$. Although it's true that this is the same idea as a four dimensional system, we can no longer visualize it usefully this way. We can, however, consider the path traced out over time in three dimensions, as if the fly were emitting a trail of dust which stayed in place in midair.
Without going too far off course, I would recommend thinking of the parameter $t$ as time. When integrating in two dimensions, imagine the fly walking along the paper, leaving a trail of it's path as it goes.


text:
Q: Plotting the spectrogram Using the answer to this link:Spectrogram C++ library I have written a code to calculate the spectrogram of a sinusoidal signal:
1-Created a sinusoidal signal.
2- I applied the Hann Window.
3- used FFTW .
4- Calculated log magnitude of frequency coefficients.
Here is the script:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <fftw3.h>
#include <iostream>
#include <cmath>

using namespace std;

int main(void)
{
    int i;
    double y;
    int N=256;
    double Fs=30000;//sampling frequency
    double  T=1/Fs;//sample time
    double f=5000;//frequency
    double *in;
    fftw_complex *out;
    double t[N-1];//time vector
    fftw_plan plan_forward;

    in = (double*) fftw_malloc(sizeof(double) * N);
    out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
    for (int i=0; i< N;i++)
    {
        t[i]=i*T;
        in[i] =0.7 *sin(2*M_PI*f*t[i]);// generate sine waveform
        double multiplier = 0.5 * (1 - cos(2*M_PI*i/(N-1)));//Hanning Window
        in[i] = multiplier * in[i];
    }

    plan_forward = fftw_plan_dft_r2c_1d ( N, in, out, FFTW_ESTIMATE );

    printf ( "\n" );
    printf ( "  Input Data:\n" );
    printf ( "\n" );

    for ( i = 0; i < N; i++ )
    {
        printf ( "  %4d  %12f\n", i, in[i] );
    }

    fftw_execute ( plan_forward );

    printf ( "\n" );
    printf ( "  log magnitude of frequency domain components :\n" );
    printf ( "\n" );

    for ( i = 0; i < N; i++ )
    {
        cout << log(sqrt(out[i][0]*out[i][0]+ out[i][1]*out[i][1])) ;

    }
    fftw_destroy_plan ( plan_forward );
    fftw_free ( in );
    fftw_free ( out );
    return 0;
}

The question is how should I proceed from here? Which library should I use to plot the spectrogram? Any suggestions? Thanks.

A: If you want to stay with C++ and be reasonable cross-platform, you might want to consider Qt as UI and either Qwt or QCustomPlot ar scientific plots widget
Links
http://sourceforge.net/projects/qwt/
http://www.qcustomplot.com/


text:
Q: How to pass 2 radio selection value with a single Submit?? echo '<form method="post" action="mod_slots.php">';
 $i = 1;
 while(cond)
 {
 echo '<input type="radio" name="change1" value="'.$i.'" />';
 $i++;
 }

 $j = 1;
 while(cond)
{
  echo '<input type="radio" name="change1" value="'.$j.'" />';
 $j++;
}

}

  echo '<input type="submit" value="Change Selected" />';
  echo '</form>';

The above code passes only change1 value to the next page! But I want a single submit button, which will send both value!!??
My implementation may be wrong!

A: Radios with same name could only have one selection, if you want to divide them, just use different name.

A: Either you can pass them by giving their names as array like
 echo '<input type="radio" name="change[]" value="'.$i.'" />';

and after submit you can print them like
print_r($_POST['change']);


text:
Q: How can I select 10th, 20th, 30th ... row of the result of another select query I have a table with a column to, from and ID. I need to select only rows with every 10th ID which is from A to B.

A: select * from
(select * from table where from = 'A' and to ='B' order by ID)
where mod(rownum/10,1) = 0

It first takes only those from 'A' to 'B', then giving them rownums, and selecting only those in the 10th 20th ETC places..

A: Or you can just use
select from, to, id
from table1
where id like'%0' and from ='A' and to = 'B'


text:
Q: Is there a function like the php function key() in JavaScript/jQuery? I transferred a multidimensional array into JavaScript via <?php echo json_encode($my_array); ?> And I would like to compare entries of that JSON with other variables. So how could I get an object as string without the sub-entries?
Let's say my object is [Object { 1429={Object { 8766={...}, 8483={...}, 7345={...}}}}, Object { 9041={...}}]
So how could I get 1429 or 8766 as String? I know how to do that with a multidimensional array in PHP (there it is key()) - but what would it be in JavaScript?

A: In PHP the key() function simply returns the key of the array element that's currently being pointed to by the internal pointer.
for example (from manual):
<?php
 $array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');

// this cycle echoes all associative array
 // key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
    echo key($array).'<br />';
}
next($array);
}
?>

There is no such thing in the js like internal pointer in object, so there is no similar function.

A: Just an example of what I think you want. You can extend on this more.
var obj = {
    "5": "some",
    "8": "thing"
};
var keys = $.map(obj, function (value, key) {
    return key;
});
//result keys: ["5", "8"]

JSFIDDLE DEMO - open the console to see the result.


text:
Q: Updater for Python Application I'm currently developing a small tool that's supposed to let players of a particular game customize their game way quicker thn actually browsing through the game files, making changes to each and any .ini file. However that is not the matter.
I'd like to get a function going to update my application within itself where there i have a function to download a .zip with the most recent version of my application and unzip it onto the app's directory.
However i need some sort of checkig mechanism to determine rather there's a new version of my app or not. As for that matter, i've uploaded both a .html aswell as a .txt with just a 0 in it which would then be changed to a 1 and uploaded to the web server in case there's an update.
So my question is how you'd go through this as in how would you read the text of the .txt file for example and determine rather it's 0 or 1 in so if the result is 1, it'll go over to downloading the newest version.
Any input is welcome,
Best regards,


text:
Q: Call js functions inside PHP loops while passing php variable as parameter to one of the functions Ok so have created two javascipt functions and i want to call them inside a php loop while passing php variable as parameter to the second function
addElements($filePath)

this filePath variable has to be the last one from the inner loop i guess written like this will not get the first variable from the first loop
Here is what I want and what have written so far:
                <script>
                <?php foreach( glob( 'posts/*' ) as $filePath ){
                        //createPost(); call js function declared in header
                        foreach( glob( $filePath.'/*' ) as $filePath ){
                        //addElements($filePath) call second hs function declared in header here i pass the last $filePath from the second loop as parameter
                        }

                }?>
              </script>

Another try but still doesn't work
<script>
                        <?php foreach( glob( 'posts/*' ) as $filePath ){
                                //createPost(); call js function declared in header
                                echo 'createPost()';
                                foreach( glob( $filePath.'/*' ) as $filePath ){
                                //addElements($filePath) call second hs function declared in header here i pass the last $filePath from the second loop as parameter
                                echo 'addElements('.$filePath.')';
                                }

                        }?>

A: PHP is executed on the server side only so you cannot have a PHP loop that is executing javascript functions (javascript = client side). However you can generate the javascript code on your server and it will be executed on the client side.
So the easy solution is to write something like that:
<script>
  <?php
  foreach( glob( 'posts/*' ) as $filePath ){
    echo 'createPost();'; // call js function declared in header
    foreach( glob( $filePath.'/*' ) as $filePath ){
      echo 'addElements("'.$filePath.'");'; // call second hs function declared in header here i pass the last $filePath from the second loop as parameter
    }
  }
  ?>
</script>

It will generate something like that:
createPost();
addElements('filepathA');
addElements('filepathB');
addElements('filepathC');
createPost();
addElements('filepathD');
addElements('filepathE');
// ...

As you can see there is no loop here. Another solution is to create an array of data on your server side and using json_encodephp function to have javascript data that you can use on the client side:
    <?php
$results = [];
foreach( glob( 'posts/*' ) as $filePath ){
    $subDirs = [];
    foreach( glob( $filePath.'/*' ) as $filePath ){
        $subDirs[] = $filePath;
    }
    $results[] = [
        'dir' => $filePath,
        'subDirs' => $subDirs
    ];
}
echo 'var data = ' . json_encode($results) . ';';
?>

You now have a javascript array that you can use as usual :
for (var i = 0; i < data.length; i++){
    createPost();
    for (var j = 0; j < data[i].subDirs.length; j++){
         addElements(data[i].subDirs[j]);
    }
}


text:
Q: Animation of elements with horizontal scrolling There are 9 circles that scroll horizontally, left to right. It is necessary that each circle when approaching the right side of the screen increased in size by 150% (see screenshot), also when scrolling should be animated rotation of each circle in a clockwise direction. Please advise how this can be implemented using JS/CSS.
enter image description here
.wrapper {
  display: flex;
  overflow-x: auto;
  gap: 10px;
  transform: rotateY(-180deg);
}

.wrapper .item {
  min-width: 350px;
  min-height: 350px;
  border-radius: 50%;
  text-align: center;
  border: 1px dashed black;
  transform: rotateY(180deg);
}

Companies we keep


text:
Q: komascript - typearea bug So I have this letter template, which used to work fine until recently. I know there was a bug in the komascript classes <3.21. My distro maintainer (Arch Linux) has upgraded komascript to 3.21.
Here is my MWE:
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{marvosym}
\usepackage{graphicx}
\usepackage{polyglossia}
\setmainlanguage{english}
\usepackage[english=british]{csquotes}

\pagestyle{empty}

\usepackage[scale=0.775]{geometry}
\setlength{\parindent}{0pt}
\addtolength{\parskip}{6pt}

\def\firstname{John}
\def\familyname{Doe}
\def\FileAuthor{\firstname \familyname}
\def\FileTitle{\firstname \familyname's }
\def\FileSubject{Letter}
\def\FileKeyWords{\firstname \familyname, Letter}

\renewcommand{\ttdefault}{pcr}

\usepackage{url}
\urlstyle{tt}
\ifpdf
  \usepackage[pdftex,pdfborder=0,breaklinks,baseurl=http://,pdfpagemode=None,pdfstartview=XYZ,pdfstartpage=1]{hyperref}
  \hypersetup{
    pdfauthor   = \FileAuthor,%
    pdftitle    = \FileTitle,%
    pdfsubject  = \FileSubject,%
    pdfkeywords = \FileKeyWords,%
    pdfcreator  = \LaTeX,%
    pdfproducer = \LaTeX}
\else
  \usepackage[dvips]{hyperref}
\fi

\begin{document}
\sffamily   % for use with a résumé using sans serif fonts;
%\rmfamily  % for use with a résumé using serif fonts;
\hfill%
\begin{minipage}[t]{.6\textwidth}
\raggedleft%
{\bfseries John doe}\\[.35ex]
\small\itshape%
Field Lane\\
 Austria\\[.35ex]
\Telefon~+43~730~1234756\\
\Letter~\href{mailto:john@doe.com}{john@doe.com}
\end{minipage}\\[1em]
%
\begin{minipage}[t]{.4\textwidth}
\raggedright%
{\bfseries T-Mobile}\\[.35ex]
\small\itshape%
Cross Lane\\
Vienna
\end{minipage}
\hfill % US style
%\\[1em] % UK style
\begin{minipage}[t]{.4\textwidth}
\raggedleft % US style
\today
%April 6, 2006 % US informal style
%05/04/2006 % UK formal style
\end{minipage}\\[2em]
\raggedright
Dear Sir or Madam,\\[1.5em]

%Yours sincerely,\\[2em] % if the opening is "Dear Mr(s) Doe,"
Yours faithfully,\\[2em] % if the opening is "Dear Sir or Madam,"
%
{\bfseries John doe}\\
%
\vfill%
%{\slshape Enclosure}
{\slshape Attachment:{Invoice}}
\end{document}

Here is the associated part of the error log:
! Undefined control sequence.
\PDF@SetupDoc ...pstringB {\@baseurl }\pdfcatalog
                                                  {/PageMode/\@pdfpagemode \...
l.44 \begin{document}

The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

! Undefined control sequence.
\PDF@SetupDoc ... \@pdfnumcopies \fi }\pdfcatalog
                                                  {\ifx \Hy@temp \@empty \el...
l.44 \begin{document}

The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

! Undefined control sequence.
\Hy@DestName #1#2->\pdfdest
                            name{#1}#2\relax
l.44 \begin{document}

The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

! Missing number, treated as zero.
<to be read again>
\relax
l.44 \begin{document}

A number should have been here; I inserted `0'.
(If you can't figure out why I needed to see a number,
look up `weird error' in the index to The TeXbook.)

! Illegal unit of measure (pt inserted).
<to be read again>
\relax
l.44 \begin{document}

Dimensions can be in units of em, ex, in, pt, pc,
cm, mm, dd, cc, nd, nc, bp, or sp; but yours is a new one!
I'll assume that you meant to say pt, for printer's points.
To recover gracefully from this error, it's best to
delete the erroneous units; e.g., type `2' to delete
two letters. (See Chapter 27 of The TeXbook.)

! Undefined control sequence.
<argument> \pdfpageheight

l.44 \begin{document}

The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

! Missing number, treated as zero.
<to be read again>
\relax
l.44 \begin{document}

A number should have been here; I inserted `0'.
(If you can't figure out why I needed to see a number,
look up `weird error' in the index to The TeXbook.)

! Illegal unit of measure (pt inserted).
<to be read again>
\relax
l.44 \begin{document}

Is this error still caused by komascript or some other package?
If I insert \usepackage{luatex85} it does compile, so I am wondering if this is another komascript related?!


text:
Q: jQuery Grouping Elements Say i have 10 elements and I want to create groups of 5, How can I wrap X elements in jQuery? here is my markup:

Item

Item

Item

Item

Item

Item

Item

Item

A: Dynamically?  Maybe something like.
var grouping = [];
var $newWrapping = $('

");

$('.mainWrap .item').each(function(index, value){
    grouping.push($(value));

    if (grouping.length > 4) {
        $newWrapping.append(grouping);
        grouping = [];
    }
});

if (grouping.length > 0) {
    $newWrapping.append(grouping);
}

$('.mainWrap').replaceWith($newWrapping);


text:
Q: Docker, no IPAddress in docker inspect I m using the following dockerfile :
FROM ubuntu:14.04
MAINTAINER xxx xxx<xx@xx.com>

# SSH
RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:xxxxxxx' | chpasswd
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config

# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile

EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]

# NodeJS Apache2
RUN apt-get update &&\
        apt-get -y upgrade &&\
        apt-get -y install nodejs nodejs-legacy nodejs-dev npm git curl apache2

I have followed :https://docs.docker.com/examples/running_ssh_service/#run-a-test_sshd-container
but it seems that I dont have an IPAddress.
What am I doing wrong, or what I haven't done ?

A: Looks like you need to run boot2docker ip and use that


text:
Q: On back button trigger event I'm doing a web site with tons of rows and when you press in a row I hidde the rest of them. To show again all of them you have to press again but the customer may want to press the back button of the browser/mobile.
I'm looking for a way in js or jquery that:
if rows are hidden and press back button do something (show again all rows), if not do normal back button funcionality.
Any idea?
Thanks in advance.

A: try this

 function detectBrowser()
     {
    window.onpopstate = function(event)
     {
    alert('helloindia');
    };
    }
    detectBrowser();

A: You need to use the history API.
Use history.pushState() to create a new state when clicking a row.
Register a callback to window.onpopstate to modify the behavior when the user click the back button (you can cancel the event and do your stuff).
Example (untested, jquery optional) :

$('.row').on('click', function() {
  // do your stuff

  window.pushState({rowId: rowId}); // you might need the additional parameters, particularly to change the URL
});

$(window).on('popstate', function(event) {
  if ('rowId' in event.state) {
    // do your stuff

    event.preventDefault();
  }
});

More info :
https://developer.mozilla.org/en-US/docs/Web/API/History_API
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate


text:
Q: How to find the least $N$ such that $N \equiv 7 \mod 180$ or $N \equiv 7 \mod 144$ but $N \equiv 1 \mod 7$? How to approach this problem:

N is the least number such that $N \equiv 7 \mod 180$  or $N \equiv 7 \mod 144$  but $N \equiv 1 \mod 7$.Then which of the these is true:

*

*$0 \lt N \lt 1000$

*$1000 \lt N \lt 2000$

*$2000 \lt N \lt 4000$

*$N \gt 4000$

Please explain your idea.
ADDED: The actual problem which comes in my paper is "or" and the "and" was my mistake but I think I learned something new owing to that.Thanks all for being patient,and appologies for the inconvenience.

A: (1) For the original version of the question $\rm\:mod\ 180 \ $ and $\rm\: mod\ 144\::$
$\rm\: 144,\:180\ |\ N-7\ \Rightarrow\ 720 = lcm(144,180)\ |\ N-7\:.\:$
So, $\rm\: mod\ 7:\ 1\equiv N = 7 + 720\ k\ \equiv -k\:,\:$ so $\rm\:k\equiv -1\equiv 6\:.$
Thus $\rm\: N = 7 + 720\ (6 + 7\ j) =\: 4327 + 5040\ j\:,\:$ so $\rm\ N\ge0\ \Rightarrow\ N \ge 4327\:.$
(2) For the updated simpler version $\rm\:mod\ 180\ $ or $\rm\  mod\ 144\:,\:$ the same method shows that
$\rm\: N = 7 + 180\ (3+ 7\ j)\:$ or $\rm\:N = 7 + 144\ (2 + 7\ j)\:,\:$ so the least$\rm\ N> 0\:$ is $\rm\:7 + 144\cdot 2 = 295\:.$
SIMPLER $\rm\ N = 7+144\ k\equiv 4\ k\ (mod\ 7)\:$ assumes every value $\rm\:mod\ 7\:$ for  $\rm\:k = 0,1,2,\:\cdots,6\:,\:$ and all these values satisfy $\rm\:0 < N < 1000\:.\:$ Presumably this is the intended "quick" solution.

A: The title says "or" and the text says "and". I will assume "and".
We want $N$ to be congruent to $7$ modulo $180$ and modulo $144$.  This will be true iff $N$ is congruent to $7$ modulo the LCM of $180$ and $144$, which is $720$.
So $N$ must have shape $N=720k+7$ for some integer $k$.
But we want $N \equiv 1 \pmod{7}$.
Since $N=700k +20k +7$, we can see that $N\equiv 20k \pmod{7}$.
Presumably we want $N$ positive, though this was not specified. It is easy to see that the least positive $k$ that works is $k=6$.  Why is it so easy? Note that $20\equiv -1 \pmod{7}$.  So to make $20k \equiv 1 \pmod{7}$, we must have $k \equiv -1\pmod{7}$.  The least positive $k$ congruent to $-1$ is $6$.
That forces $N>4000$.
Added: The text of the original question said $180$ and $144$.
For the "or" version, we note that $N \equiv 7 \pmod{\gcd(180,140)}$.
Thus $N\equiv 7 \pmod{36}$, or equivalently $N$ is of the shape $36k+7$.  In particular, since $N \equiv 1 \pmod 7$, we must have $k\equiv 1 \pmod 7$. Probably at this stage (or earlier!) search is most efficient. Try $k=8$. That gives $N=295$, which works, since $295=(2)(144)+7$.

A: I assume that the question is "or."  Then it is simplest to just compute the answer.
Notice that $180 \equiv 5 \pmod{7}$ and $144\equiv 4 \pmod{7}$.  Since $3\cdot 5\equiv 1\pmod 7$, we see that $3\cdot 180+7\equiv 1\pmod{7}$.  Also, since $2\cdot4\equiv 1\pmod{7}$ we also have $2\cdot144 +7\equiv 1\pmod{7}$.  As the smaller of the two is the second, we conclude that $N=295$.


text:
Q: Sending data between an asp.net page and a pop up page? What are the different ways of communication between asp.net page and a popup page? Query strings etc. Which is most secure?

A: If you are talking about an actual pop-up page, where you are using window.open from javascript.  You have the querystring and Javascript as your only real available options for passing information between.
As for "security" of this.  The users will be able to see anything via a querystring, JavaScript can move values across, but they would be existing on the other page.  But you could pass something like an excrypted value to make things more secure.

A: You say "communication between" the pop-up and the main ASP.NET page.  First, I assume that the pop-up is an ASP.NET page as well so the communication from the main page to the pop-up is no different from the communication from one page to the next in a series of pages.  That is, you can store and then use data in the session (if the data is available when the main page is loaded), via query strings, etc.  Unless the data is sensitive, the simplest way by far is to include a variable in the call to the pop-up that is replaced by the appropriate arguments.  Here is a sample image link:
<img style='cursor:hand;' alt="Open Note" onclick="javascript:window.open('NoteEdit.aspx?T=3&UID=<%#NoteUID%>', 'Note', 'HEIGHT=400,WIDTH=420');" src="images/Note.gif" />

Note the "NoteUID" replacement argument.
The more interesting question is how to pass information back to the window that popped up the pop up.  To do that, start with this javascript:
<script type="text/javascript">
    function OpenHRAResults()
    {
        opener.location.href="<%#DestName%>";
        window.close();
    }
</script>

This is taken from code where I re-open a specific page but, as you can guess, you can do all sorts of things with the "opener" window (the window that popped-up the pop up).
Hope this helps...

A: A few methods

*

*Query strings (window.open('/users/123'..)

*Javascript (window.opener)

*HTTP POST (open a popup via javascript, set the form target to it's name as target and post)

*Sessions or other server side methods

In answer to the security consideration I'd say that query strings in combination with server side security is the way to go. Open the popup passing the information via query strings, then validate that the logged in user has permissions to access that user. Some specific requirements would call for encrypting the querystring data.
For delete operations I'd probably use a postback to avoid problems like "my indexing spider deleted all users".

A: We try to avoid query strings where possible in sometimes they are just too convenient.  In those cases we always encrypt the querystring.  There are several ways to do this - example of one approach:
http://www.codeproject.com/kb/web-security/querystringencryptionnet.aspx

A: You don't need to sent the real data to the popup window. Just create a GUID on the opener page.
Create a class in asp.net which represent all the data you need to sent between the popup page and the opener page. For example popupdata
Store the serialized class in the Session with the GUID as the name Session[Guid] = class object
Session[Guid] = popupdata;
Open the popup with f.i. ~/popupwindow.aspx?PageID=Guid
Retrieve the session object with calling the Session[Guid] again (Guid is coming from the PageID querystring.
so on the popup page call popupdata data = (popupdata)Session[Guid];
And then do whatever yuo like withthe data.
If data is changed on the popupwindow you can store it in the Session variable again
and send it back to the opener...
Very secure since no data is sent to the client.


text:
Q: Ionic + Vuew: strange error when compiling I'm experimenting with vuejs+ionic but when I try to compile on the mac I get this error
TS2339: Property 'selectedDate' does not exist on type '{ handler(date: string): Promise<false | undefined>; deep: boolean; }'.
If I compile in window everything is working.
This is located in the "watch" section.

A: <template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-title>Controlli Preoperativi</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content :fullscreen="true">
      <ion-header collapse="condense">
        <ion-toolbar>
          <ion-title size="large">Controlli preoperativi</ion-title>
        </ion-toolbar>
      </ion-header>
      <ion-grid>
        <ion-row>
          <ion-col>

              Da qui potrai impostare la presenza o assenza di non conformità nel tuo locale.

              Attenzione, le modifiche nel passato sono possibili solo fino al giorno precedente.

          </ion-col>
        </ion-row>
        <ion-row>
          <ion-col>
            <ion-item>
              <ion-label>imposta la data di lavoro</ion-label>
              <ion-datetime display-format="DD/MM/YYYY" v-model="selectedDate"></ion-datetime>
            </ion-item>
          </ion-col>
        </ion-row>
        <ion-row>
            <ion-col v-for="item in controlli" :key="item.id">
              <ion-card>

                <ion-card-header>
                  <ion-card-title>{{ item.nome }}</ion-card-title>
                </ion-card-header>
                <ion-card-content>

                    {{ item.descrizione }}

                    <ion-item>
                      <ion-label>presente</ion-label>
                      <ion-checkbox v-model="item.nonConformitaPresente" :data-id="item.id" data-type="ncp" @click="handleCheckChange(item.id, 'ncp')" />
                    </ion-item>

                    <ion-item>
                      <ion-label>non presente</ion-label>
                      <ion-checkbox v-model="item.nonConformitaNonPresente" :data-id="item.id" data-type="ncnp" @click="handleCheckChange(item.id, 'ncnp')" />
                    </ion-item>

                    <ion-item>
                      <ion-label position="floating">problema riscontrato</ion-label>
                      <ion-textarea rows="5" v-model="item.problemaRiscontrato"></ion-textarea>
                    </ion-item>
                    <ion-item>
                      <ion-label position="floating">risoluzione</ion-label>
                      <ion-textarea rows="5" v-model="item.risoluzione"></ion-textarea>
                    </ion-item>

                    <ion-button type="submit" shape="round" @click="handleSaveButton(item.id)" :data-id="item.id">
                        Salva
                        <ion-icon :icon="save"></ion-icon>
                    </ion-button>

                </ion-card-content>
              </ion-card>
            </ion-col>
        </ion-row>
      </ion-grid>
    </ion-content>
  </ion-page>
</template>


text:
Q: Laravel's Hash missing argument? I'm getting a weird error in Laravel 5.3's hash mechanism.
Missing argument 2 for Illuminate\Hashing\BcryptHasher::check(), called in C:\xampp\htdocs\Missionseek2\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php on line 237 and defined

This is the code that defines it.
public function postSignIn(Request $request){

        $val = DB::table('ministry')->where('Username', Input::get('Username'))->first();

        if ($val && Hash::check(Input::get('Password', $val->Password))) {
            return redirect()->route('agencydash');
        } return 'failed';
       // if (Auth::attempt(['Username' => $request['Username'], 'Password' => $request['Password']])) {
       //     return redirect()->route('agencydash');
       // }
        //return redirect()->back();
    }

What's going on here? I feel like it's not getting the password value from the database and so we're getting an error, but I'm not sure why. The name's are correct.

A: You are passing 2 argument in Input::get() instead of check(). You have to correct brackets positions
if ($val && Hash::check(Input::get('Password'), $val->Password))

A: I think your parenthesis is not in the right place
You have  :
Hash::check(Input::get('Password', $val->Password))
And I think you have to move your parenthesis to :
Hash::check(Input::get('Password'), $val->Password)

A: Not sure how Hash::check works, but here
Hash::check(Input::get('Password', $val->Password))

you gave it only one parameter.

A: I think you have something wrong in your parentheses.
if ($val && Hash::check(Input::get('Password', $val->Password)))

becomes
if ($val && Hash::check(Input::get('Password'), $val->Password))


text:
Q: How to keep animation running while background thread is active? I have an application that needs to convert a lot of SVGs to Drawables right at the beginning, using a variant of svg-android.
The problem I've run into is that the conversion is fairly processor intensive, so if I run it on the UI thread, everything pauses for 10 seconds or so while it happens. I've tried moving the conversion to a background thread, but that causes some weirdness because some other methods that are dependent on the array of Drawables fire before all the Drawables are complete. I've tried a couple of different things to do a loading animation, but they won't animate while the background process is active.
Here's my relevant code:
//get and resize SVGs
new Thread(new Runnable(){
    public void run(){
       for (int i=0;i<drawablesArray.length;i++){
            SVG vector = SVGParser.getSVGFromResources(getResources(),resourceArray[i]);
            Drawable drawable = new PictureDrawable(vector.resizePicture(height,width); //resize picture is a custom function in SVG-Android
            drawablesArray[i]=drawable;
        }
    }
}).start();

while(drawablesArray[20]==null){
    loadingView.animate().setDuration(100).rotationBy(25);
}

With that code it will successfully hold off the later methods from firing until the background process completes, but the animation in the while loop will never actually play. I've also tried using an indeterminate ProgressBar for loadingView, both with and without the while loop (altered to not actually do anything), and it will animate up until the background thread starts, at which point it will freeze.
If I take the animation code that's there out of the while loop, the animation will fire after the background thread finishes, not concurrently with the background thread.
How do I keep the animation going while the background thread is running?

A:
With that code it will successfully hold off the later methods from firing until the background process completes, but the animation in the while loop will never actually play.

You are tying up the main application thread in your while loop. Your UI will be frozen during this time, just as if you had done the SVG work on the main application thread.

I've also tried using an indeterminate ProgressBar for loadingView, both with and without the while loop (altered to not actually do anything), and it will animate up until the background thread starts, at which point it will freeze.

Presumably, that is because you are tying up the main application thread with your while loop, though I am less certain of that as we do not have this code.

How do I keep the animation going while the background thread is running?

You start by getting rid of the while loop.
Just have a ProgressBar be visible while the background work is going on for now -- later, once you have that working, you can experiment with other solutions. Switch the Thread to an AsyncTask, and in onPostExecute() of the AsyncTask, you hide the ProgressBar and do whatever it is that you needed to do with your converted SVGs.


text:
Q: Java printing Arraylist These are my 2 classes, they work. I want to add Member into the ArrayList of Lan. My problem is, I can't seem to print out the members that are set in the ArrayList of Lan, the name and alias or just the name. when I print this comes: Member@1279d2f, any ideas? :S
import java.util.ArrayList;

public class Lan
{

private ArrayList<Member> members;

    public Lan()
    {
      members = new ArrayList<Member>();

    }

    public void addMember(Member newMember)
    {
        if(newMember.getBalance() >= 200)
        {
            this.members.add(newMember);
        }
        else
        {
            System.out.println("You dont have enough money to enter");
        }

    }
   public void printMembers(){

       System.out.println("People attending");
       for(Member member : members){

          System.out.println(member);
       }

   }

}

public class Member
{

    private String name;
    private String alias;
    private int balance;

    public Member(String fullName, String nickname)
    {
        this.name = fullName;
        this.alias = nickname;
        this.balance = 0;
    }
    public void setBalance(int account)
    {
        if(account > 0)
        {
            balance = balance + account;
        }
        else
        {
            System.out.println("You have not entered a valid number");
        }
    }

    public String getName()
    {
        return name;
    }
    public String getAlias()
    {
        return alias;
    }

    public int getBalance()
    {
        return balance;
    }
}

A: You must define a toString() method for your Member class:
public class Member {

  private String name;
  private String alias;
  private int balance;

  public Member(String fullName, String nickname)
  {
      this.name = fullName;
      this.alias = nickname;
      this.balance = 0;
  }
  public void setBalance(int account)
  {
      if(account > 0)
      {
          balance = balance + account;
      }
      else
      {
          System.out.println("You have not entered a valid number");
      }
  }

  public String getName()
  {
      return name;
  }
  public String getAlias()
  {
      return alias;
  }

  public int getBalance()
  {
      return balance;
  }

  @Override
  public String toString() {
    return this.name + "\t" + this.balance;
  }

}

Without a toString() method for your custom class, you will print its location in memory. If there's other information you want to print in Member, modify the method that I've provided for you.


text:
Q: Reducing the complexity of getting unique values from dict in Python I am fairly new to Python (and writing good and efficient algorithms) and am not too familiar with the different data structures that can be used to iterate over large amounts of data efficiently. I need to find the unique set of values from a nested dict, and have written the following code:
data = {'c14da622-7fb8-4da3-a2fb-d8c632957fbe': {'25': {'label': 'no plane'}, '50': {'label': 'no plane'}, '125': {'label': 'no plane'}, '150': {'label': 'no plane'}, '175': {'label': 'plane'}, '200': {'label': 'plane'}, '275': {'label': 'plane'}, '300': {'label': 'plane'}, '325': {'label': 'plane'}, '350': {'label': 'plane'}, '375': {'label': 'plane'}, '400': {'label': 'plane'}, '425': {'label': 'plane'}, '450': {'label': 'plane'}, '475': {'label': 'plane'}, '500': {'label': 'plane'}, '525': {'label': 'plane'}, '550': {'label': 'plane'}, '575': {'label': 'plane'}, '600': {'label': 'plane'}, '625': {'label': 'plane'}, '650': {'label': 'plane'}, '875': {'label': 'plane'}, '900': {'label': 'plane'}, '925': {'label': 'plane'}, '950': {'label': 'plane'}, '975': {'label': 'plane'}, '1000': {'label': 'plane'}, '1025': {'label': 'plane'}, '1050': {'label': 'plane'}, '1075': {'label': 'plane'}, '1100': {'label': 'plane'}, '1125': {'label': 'plane'}, '1150': {'label': 'plane'}, '1175': {'label': 'plane'}}, '60cb59c7-6b0a-4225-b00f-2d888a9d5250': {'30': {'label': 'no plane'}, '60': {'label': 'no plane'}, '90': {'label': 'no plane'}, '120': {'label': 'no plane'}, '150': {'label': 'no plane'}, '180': {'label': 'plane'}, '210': {'label': 'plane'}, '240': {'label': 'plane'}, '270': {'label': 'plane'}, '300': {'label': 'plane'}, '330': {'label': 'plane'}, '360': {'label': 'plane'}, '390': {'label': 'plane'}, '420': {'label': 'plane'}, '450': {'label': 'plane'}, '480': {'label': 'plane'}, '510': {'label': 'plane'}, '570': {'label': 'plane'}, '600': {'label': 'plane'}, '660': {'label': 'plane'}, '690': {'label': 'plane'}, '720': {'label': 'plane crash'}, '750': {'label': 'plane crash'}, '780': {'label': 'plane crash'}, '810': {'label': 'plane crash'}, '840': {'label': 'plane crash'}, '870': {'label': 'plane crash'}, '900': {'label': 'plane crash'}, '930': {'label': 'plane crash'}, '960': {'label': 'plane crash'}, '990': {'label': 'no plane'}, '1020': {'label': 'plane crash'}, '1050': {'label': 'plane crash'}, '1080': {'label': 'plane crash'}, '1110': {'label': 'plane crash'}, '1140': {'label': 'plane crash'}, '1170': {'label': 'plane crash'}, '1200': {'label': 'plane crash'}, '1230': {'label': 'plane crash'}, '1260': {'label': 'plane crash'}, '1290': {'label': 'plane crash'}, '1320': {'label': 'plane crash'}, '1350': {'label': 'plane crash'}, '1380': {'label': 'plane crash'}, '1410': {'label': 'plane crash'}, '1560': {'label': 'plane crash'}, '1590': {'label': 'plane crash'}, '1620': {'label': 'plane crash'}, '1650': {'label': 'plane crash'}, '1680': {'label': 'plane crash'}, '1710': {'label': 'plane crash'}}}

def parse_label_categories(data):
    tuples = list(data.values())
    unique_labels = []
    for labels in tuples:
        labels_dump = list(labels.values())
        for dump in labels_dump:
            label = list(dump.values())
            new = label.pop()
            unique_labels.append(new)
    return list(set(unique_labels))

parse_label_categories(data)

Which returns the three unique values:
['plane crash', 'plane', 'no plane']

I have a nested for loop and overall my code is pretty atrocious, but I have been hard pressed to find a more elegant and efficient solution to this problem in Python.
Any help/suggestions would be much appreciated :-)

A: Pro-tip: jsonlint will format data into a readable format, even if that JSON has already been parsed into a python list/dict.
data = {'c14da622-7fb8-4da3-a2fb-d8c632957fbe': {'25': {'label': 'no plane'}, '50': {'label': 'no plane'}, '125': {'label': 'no plane'}, '150': {'label': 'no plane'}, '175': {'label': 'plane'}, '200': {'label': 'plane'}, '275': {'label': 'plane'}, '300': {'label': 'plane'}, '325': {'label': 'plane'}, '350': {'label': 'plane'}, '375': {'label': 'plane'}, '400': {'label': 'plane'}, '425': {'label': 'plane'}, '450': {'label': 'plane'}, '475': {'label': 'plane'}, '500': {'label': 'plane'}, '525': {'label': 'plane'}, '550': {'label': 'plane'}, '575': {'label': 'plane'}, '600': {'label': 'plane'}, '625': {'label': 'plane'}, '650': {'label': 'plane'}, '875': {'label': 'plane'}, '900': {'label': 'plane'}, '925': {'label': 'plane'}, '950': {'label': 'plane'}, '975': {'label': 'plane'}, '1000': {'label': 'plane'}, '1025': {'label': 'plane'}, '1050': {'label': 'plane'}, '1075': {'label': 'plane'}, '1100': {'label': 'plane'}, '1125': {'label': 'plane'}, '1150': {'label': 'plane'}, '1175': {'label': 'plane'}}, '60cb59c7-6b0a-4225-b00f-2d888a9d5250': {'30': {'label': 'no plane'}, '60': {'label': 'no plane'}, '90': {'label': 'no plane'}, '120': {'label': 'no plane'}, '150': {'label': 'no plane'}, '180': {'label': 'plane'}, '210': {'label': 'plane'}, '240': {'label': 'plane'}, '270': {'label': 'plane'}, '300': {'label': 'plane'}, '330': {'label': 'plane'}, '360': {'label': 'plane'}, '390': {'label': 'plane'}, '420': {'label': 'plane'}, '450': {'label': 'plane'}, '480': {'label': 'plane'}, '510': {'label': 'plane'}, '570': {'label': 'plane'}, '600': {'label': 'plane'}, '660': {'label': 'plane'}, '690': {'label': 'plane'}, '720': {'label': 'plane crash'}, '750': {'label': 'plane crash'}, '780': {'label': 'plane crash'}, '810': {'label': 'plane crash'}, '840': {'label': 'plane crash'}, '870': {'label': 'plane crash'}, '900': {'label': 'plane crash'}, '930': {'label': 'plane crash'}, '960': {'label': 'plane crash'}, '990': {'label': 'no plane'}, '1020': {'label': 'plane crash'}, '1050': {'label': 'plane crash'}, '1080': {'label': 'plane crash'}, '1110': {'label': 'plane crash'}, '1140': {'label': 'plane crash'}, '1170': {'label': 'plane crash'}, '1200': {'label': 'plane crash'}, '1230': {'label': 'plane crash'}, '1260': {'label': 'plane crash'}, '1290': {'label': 'plane crash'}, '1320': {'label': 'plane crash'}, '1350': {'label': 'plane crash'}, '1380': {'label': 'plane crash'}, '1410': {'label': 'plane crash'}, '1560': {'label': 'plane crash'}, '1590': {'label': 'plane crash'}, '1620': {'label': 'plane crash'}, '1650': {'label': 'plane crash'}, '1680': {'label': 'plane crash'}, '1710': {'label': 'plane crash'}}}

def parse_label_categories(data):
    seen = set()
    for some_lable, data_dict in data.items():
        for some_number, outcome in data_dict.items():
            seen.add(outcome['label'])
    return seen

a = parse_label_categories(data)

I don't think there is a more efficient approach to this in Python. You might be able to use pandas and possibly push the loops into C, as it expands out the JSON into a dataframe, but I'm not convinced.

Since the pandas approach did come up, I did the timings:
import pandas as pd

data = {'c14da622-7fb8-4da3-a2fb-d8c632957fbe': {'25': {'label': 'no plane'}, '50': {'label': 'no plane'}, '125': {'label': 'no plane'}, '150': {'label': 'no plane'}, '175': {'label': 'plane'}, '200': {'label': 'plane'}, '275': {'label': 'plane'}, '300': {'label': 'plane'}, '325': {'label': 'plane'}, '350': {'label': 'plane'}, '375': {'label': 'plane'}, '400': {'label': 'plane'}, '425': {'label': 'plane'}, '450': {'label': 'plane'}, '475': {'label': 'plane'}, '500': {'label': 'plane'}, '525': {'label': 'plane'}, '550': {'label': 'plane'}, '575': {'label': 'plane'}, '600': {'label': 'plane'}, '625': {'label': 'plane'}, '650': {'label': 'plane'}, '875': {'label': 'plane'}, '900': {'label': 'plane'}, '925': {'label': 'plane'}, '950': {'label': 'plane'}, '975': {'label': 'plane'}, '1000': {'label': 'plane'}, '1025': {'label': 'plane'}, '1050': {'label': 'plane'}, '1075': {'label': 'plane'}, '1100': {'label': 'plane'}, '1125': {'label': 'plane'}, '1150': {'label': 'plane'}, '1175': {'label': 'plane'}}, '60cb59c7-6b0a-4225-b00f-2d888a9d5250': {'30': {'label': 'no plane'}, '60': {'label': 'no plane'}, '90': {'label': 'no plane'}, '120': {'label': 'no plane'}, '150': {'label': 'no plane'}, '180': {'label': 'plane'}, '210': {'label': 'plane'}, '240': {'label': 'plane'}, '270': {'label': 'plane'}, '300': {'label': 'plane'}, '330': {'label': 'plane'}, '360': {'label': 'plane'}, '390': {'label': 'plane'}, '420': {'label': 'plane'}, '450': {'label': 'plane'}, '480': {'label': 'plane'}, '510': {'label': 'plane'}, '570': {'label': 'plane'}, '600': {'label': 'plane'}, '660': {'label': 'plane'}, '690': {'label': 'plane'}, '720': {'label': 'plane crash'}, '750': {'label': 'plane crash'}, '780': {'label': 'plane crash'}, '810': {'label': 'plane crash'}, '840': {'label': 'plane crash'}, '870': {'label': 'plane crash'}, '900': {'label': 'plane crash'}, '930': {'label': 'plane crash'}, '960': {'label': 'plane crash'}, '990': {'label': 'no plane'}, '1020': {'label': 'plane crash'}, '1050': {'label': 'plane crash'}, '1080': {'label': 'plane crash'}, '1110': {'label': 'plane crash'}, '1140': {'label': 'plane crash'}, '1170': {'label': 'plane crash'}, '1200': {'label': 'plane crash'}, '1230': {'label': 'plane crash'}, '1260': {'label': 'plane crash'}, '1290': {'label': 'plane crash'}, '1320': {'label': 'plane crash'}, '1350': {'label': 'plane crash'}, '1380': {'label': 'plane crash'}, '1410': {'label': 'plane crash'}, '1560': {'label': 'plane crash'}, '1590': {'label': 'plane crash'}, '1620': {'label': 'plane crash'}, '1650': {'label': 'plane crash'}, '1680': {'label': 'plane crash'}, '1710': {'label': 'plane crash'}}}

def parse_label_categories(data):
    seen = set()
    for some_lable, data_dict in data.items():
        for some_number, outcome in data_dict.items():
            seen.add(outcome['label'])
    return seen

def pandas_approach(d):
    all_df=None
    for id, d in data.items():
        df = pd.DataFrame.from_dict(d, orient="index")
        if all_df is None:
            all_df = df
        else:
            all_df = pd.concat([all_df, df])

Which gives:
%timeit parse_label_categories(data)
18 µs ± 2.31 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit pandas_approach(data)
2.7 ms ± 156 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

A: You could turn this into a dataframe and significantly reduce the amount of looping you need to do. You would still have to loop on the first level and then concatenate the results, but as the rest would make use of vectorization in the background it could be significantly faster:
import pandas as pd
all_df=None
for id, d in data.items():
    df = pd.DataFrame.from_dict(d, orient="index")
    if all_df is None:
        all_df = df
    else:
        all_df = pd.concat([all_df, df])

print(all_df["label"].unique())


text:
Q: jQuery-UI scripts stop working after .load() in wordpress I am currently working on a dynamic survey form that would ask a customer what kind of product he wants and then display relevant products from our e-shop. Kind of like searching by parameters, but more personal.
Now I tried doing it by loading each page of form from individual .php files that are meant to replace certain div on my page to avoid having to reload whole page.
I am using, or rather I am TRYING to use jQuery UI widgets, but they stop working when I load the next page using .load('url') function. Console outputs error, at widget initialisation stating $(...).slider is not a function(…)
My individual pages look something like this

      Price range:
      <input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">

    back
    back

The whole thing is inside
 in page which I load stuff into.
As I said in title, I am doing this in wordpress, so I have jquery and jquery-ui properly enqueued, it actually works on the first page which is identical for testing purposes. Also it is regular wordpress page created in admin panel and I had button and slider functions in functions.js file which is also properly enqueued in theme functions file.
So my question is, how do I make the scripts work after the .load(). I've read something about $.getScript() and thought to load jQuery UI files but I am not entirely sure how to make it work with WP and also if it's not being redundant, loading the same file over and over again. I am fairly new to these internet programming languages... especially to integrating them with WP.
Also if anyone has other ideas how I might do the whole form in different, better/easier way, I am open to any ideas.
Thank you for answers

A: $(...).slider is not a function(…) error specifically states that you have written this code before loading reference to the jquery-ui.js file. So whatever script loading you have, put it before writing your plugin initialisation.
For the events to not work on dynamically loaded page through .load below would be the possible cause:

*

*Your dynamically loaded page's element might not have events attached to it, as in .slider, since it is loaded after the plugin has been initialised.

So, you need to have a callback function after your .load so that you can re-initialise on the newly loaded elements.
Callback function
$('#back-button').click(function(){
     $('#formular-content').load('/eshop/formular/1.php',function(){
          $( "#slider-range" ).slider({
               range: true,
               min: 0,
               max: 500,
               values: [ 75, 300 ],
              slide: function( event, ui ) {
                 $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
              }
          });
          //initialise anything here as in .slider() to the `element` which is loaded through ajax.
     });
});

A: Thought this was Wordpress related, turns out it's not.
The solution
TL;DR
Add jQuery UI widgets initialization in

I didn't use jQuery(document).ready event and there was the problem.
Thanks Guruprasad Rao for your time on TeamViewer :)


text:
Q: How are the "Login" and "Register" links from Laravel's built-in authentication system added to existing pages? I have created several pieces of my Laravel 7 application (I'm a newbie trying to learn).  I then wanted to add authentication on top of that, so I did:
php artisan ui bootstrap --auth
npm install && npm run dev

After doing so,  I have a "login" and a "register" link on the top left-corner of every page of my app.  These links are being added by some automated method and are not changing the pages (views - *.blade.php files) that I had created before adding the authentication system.
I'd like to prevent these links from being added automatically.  Then I can add my own links to my navigation bar.  The problem is I can't figure out how they're being created or added to my views.  Can someone help me?

NEVERMIND - I FIGURED IT OUT.
Appearently during the authentication system scaffolding my "layout.blade.php" was modified to include both the "login" and "register" links by the addition of this code just under the  tag:

        @if (Route::has('login'))

            @auth
            Home
            @else
            Login

            @if (Route::has('register'))
            Register
            @endif
            @endauth

        @endif

All I needed to do is remove that code block.  Hope this helps someone in the future.

A: The login links are created on a separate template file (views/layouts/app.blade.php). To remove them you need to customize this file.
This is the part where the header links are created:

                        @guest

                                {{ __('Login') }}

                            @if (Route::has('register'))

                                    {{ __('Register') }}

                            @endif
                        @else

                                    {{ Auth::user()->name }}

                                        {{ __('Logout') }}

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                        @csrf
                                    </form>

                        @endguest


text:
Q: What I'm doing wrong while installing scipy using pip3 on Mac Facing following issue while installing scipy 1.2.1
(env) sahibyar@Sahibs-MacBook-Pro services % pip3 install scipy==1.2.1
Collecting scipy==1.2.1
  Using cached scipy-1.2.1.tar.gz (23.1 MB)
Using legacy setup.py install for scipy, since package 'wheel' is not installed.
Installing collected packages: scipy
    Running setup.py install for scipy ... error
    ERROR: Command errored out with exit status 1:
     command: /Users/sahibyar/Dailytasks/env/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/5_/5blqbh750wsc9pc01bn0lgph0000gn/T/pip-install-lk7yk3u0/scipy/setup.py'"'"'; __file__='"'"'/private/var/folders/5_/5blqbh750wsc9pc01bn0lgph0000gn/T/pip-install-lk7yk3u0/scipy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/5_/5blqbh750wsc9pc01bn0lgph0000gn/T/pip-record-96sbgt69/install-record.txt --single-version-externally-managed --compile --install-headers /Users/sahibyar/Dailytasks/env/include/site/python3.7/scipy
         cwd: /private/var/folders/5_/5blqbh750wsc9pc01bn0lgph0000gn/T/pip-install-lk7yk3u0/scipy/
    Complete output (107 lines):
    /private/var/folders/5_/5blqbh750wsc9pc01bn0lgph0000gn/T/pip-install-lk7yk3u0/scipy/setup.py:114: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
      import imp

    Note: if you need reliable uninstall behavior, then install
    with pip instead of using `setup.py install`:

      - `pip install .`       (from a git repo or downloaded source
                               release)
      - `pip install scipy`   (last SciPy release on PyPI)

    Running from scipy source directory.
    lapack_opt_info:
    lapack_mkl_info:
    customize UnixCCompiler
      libraries mkl_rt not found in ['/Users/sahibyar/Dailytasks/env/lib', '/usr/local/lib', '/usr/lib']
      NOT AVAILABLE

    openblas_lapack_info:
      libraries openblas not found in ['/Users/sahibyar/Dailytasks/env/lib', '/usr/local/lib', '/usr/lib']
      NOT AVAILABLE

    openblas_clapack_info:
      libraries openblas,lapack not found in ['/Users/sahibyar/Dailytasks/env/lib', '/usr/local/lib', '/usr/lib']
      NOT AVAILABLE

    flame_info:
      libraries flame not found in ['/Users/sahibyar/Dailytasks/env/lib', '/usr/local/lib', '/usr/lib']
      NOT AVAILABLE

    accelerate_info:
      NOT AVAILABLE

    atlas_3_10_threads_info:
    Setting PTATLAS=ATLAS
      libraries lapack_atlas not found in /Users/sahibyar/Dailytasks/env/lib
      libraries tatlas,tatlas not found in /Users/sahibyar/Dailytasks/env/lib
      libraries lapack_atlas not found in /usr/local/lib
      libraries tatlas,tatlas not found in /usr/local/lib
      libraries lapack_atlas not found in /usr/lib
      libraries tatlas,tatlas not found in /usr/lib
    <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
      NOT AVAILABLE

    atlas_3_10_info:
      libraries lapack_atlas not found in /Users/sahibyar/Dailytasks/env/lib
      libraries satlas,satlas not found in /Users/sahibyar/Dailytasks/env/lib
      libraries lapack_atlas not found in /usr/local/lib
      libraries satlas,satlas not found in /usr/local/lib
      libraries lapack_atlas not found in /usr/lib
      libraries satlas,satlas not found in /usr/lib
    <class 'numpy.distutils.system_info.atlas_3_10_info'>
      NOT AVAILABLE

    atlas_threads_info:
    Setting PTATLAS=ATLAS
      libraries lapack_atlas not found in /Users/sahibyar/Dailytasks/env/lib
      libraries ptf77blas,ptcblas,atlas not found in /Users/sahibyar/Dailytasks/env/lib
      libraries lapack_atlas not found in /usr/local/lib
      libraries ptf77blas,ptcblas,atlas not found in /usr/local/lib
      libraries lapack_atlas not found in /usr/lib
      libraries ptf77blas,ptcblas,atlas not found in /usr/lib
    <class 'numpy.distutils.system_info.atlas_threads_info'>
      NOT AVAILABLE

    atlas_info:
      libraries lapack_atlas not found in /Users/sahibyar/Dailytasks/env/lib
      libraries f77blas,cblas,atlas not found in /Users/sahibyar/Dailytasks/env/lib
      libraries lapack_atlas not found in /usr/local/lib
      libraries f77blas,cblas,atlas not found in /usr/local/lib
      libraries lapack_atlas not found in /usr/lib
      libraries f77blas,cblas,atlas not found in /usr/lib
    <class 'numpy.distutils.system_info.atlas_info'>
      NOT AVAILABLE

    lapack_info:
      libraries lapack not found in ['/Users/sahibyar/Dailytasks/env/lib', '/usr/local/lib', '/usr/lib']
      NOT AVAILABLE

    /Users/sahibyar/Dailytasks/env/lib/python3.7/site-packages/numpy/distutils/system_info.py:1858: UserWarning:
        Lapack (http://www.netlib.org/lapack/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [lapack]) or by setting
        the LAPACK environment variable.
      return getattr(self, '_calc_info_{}'.format(name))()
    lapack_src_info:
      NOT AVAILABLE

    /Users/sahibyar/Dailytasks/env/lib/python3.7/site-packages/numpy/distutils/system_info.py:1858: UserWarning:
        Lapack (http://www.netlib.org/lapack/) sources not found.
        Directories to search for the sources can be specified in the
        numpy/distutils/site.cfg file (section [lapack_src]) or by setting
        the LAPACK_SRC environment variable.
      return getattr(self, '_calc_info_{}'.format(name))()
      NOT AVAILABLE

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/5_/5blqbh750wsc9pc01bn0lgph0000gn/T/pip-install-lk7yk3u0/scipy/setup.py", line 492, in <module>
        setup_package()
      File "/private/var/folders/5_/5blqbh750wsc9pc01bn0lgph0000gn/T/pip-install-lk7yk3u0/scipy/setup.py", line 488, in setup_package
        setup(**metadata)
      File "/Users/sahibyar/Dailytasks/env/lib/python3.7/site-packages/numpy/distutils/core.py", line 135, in setup
        config = configuration()
      File "/private/var/folders/5_/5blqbh750wsc9pc01bn0lgph0000gn/T/pip-install-lk7yk3u0/scipy/setup.py", line 395, in configuration
        raise NotFoundError(msg)
    numpy.distutils.system_info.NotFoundError: No lapack/blas resources found. Note: Accelerate is no longer supported.
    ----------------------------------------
ERROR: Command errored out with exit status 1: /Users/sahibyar/Dailytasks/env/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/5_/5blqbh750wsc9pc01bn0lgph0000gn/T/pip-install-lk7yk3u0/scipy/setup.py'"'"'; __file__='"'"'/private/var/folders/5_/5blqbh750wsc9pc01bn0lgph0000gn/T/pip-install-lk7yk3u0/scipy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/5_/5blqbh750wsc9pc01bn0lgph0000gn/T/pip-record-96sbgt69/install-record.txt --single-version-externally-managed --compile --install-headers /Users/sahibyar/Dailytasks/env/include/site/python3.7/scipy Check the logs for full command output.
WARNING: You are using pip version 20.1.1; however, version 21.3.1 is available.
You should consider upgrading via the '/Users/sahibyar/Dailytasks/env/bin/python3.7 -m pip install --upgrade pip' command.
(env) sahibyar@Sahibs-MacBook-Pro services %

A: it seems your pip aversion in mac is too old, you need to upgrade pip first
 pip install --upgrade pip

A: If you having issue with PIP you can try following ways
Download the dispenses  directly from site
https://pypi.org/project/scipy/#files
later install directly wheel with pip
pip install wheelname.whl`

`
Example
pip install scipy-1.5.4-cp38-cp38-macosx_11_0_x86_64.whl

Along with this check below thread
https://github.com/scipy/scipy/issues/13102#issuecomment-850882851


text:
Q: How can I plug in the value of parameter found by Maximum a Posterior? Suppose I have 1 heads and 4 tails from 5 coin tosses. To find out the probability of 1 heads and 4 tails in my coin toss experiments, I decided to use Binomial Probability Mass Function for the calculation of the probability on the current observations.
I used Maximum a Posterior with the Beta prior $ (\alpha=5, \beta=5) $, instead of Maximum Likelihood Estimation, to estimate the parameter value of $ \theta $ and I got $ 0.3846 $ from Maximum a Posterior. Now, I have the parameter value of $\theta$ and I want to find out the probability that I would observe 1 heads and 4 tails, which one of the following equations should I plug in the estimate parameter value, $ 0.3846 $:

*

*$ {n}\choose{k} $ $ \Pi^n_{i=1} \theta^{x_i} (1-\theta)^{(1-x_i)} \theta^{(\alpha-1)}  (1-\theta)^{(\beta-1)}$
The above equation is considering the prior probability for the calculation of the probability for my experiment. Or should I just plug the value of $ \theta $ into the Binomial Probability Mass Function?

*$ {n}\choose{k} $ $ \Pi^n_{i=1} \theta^{x_i} (1-\theta)^{(1-x_i)}$
I know this sounds very naive but I just want to make sure I am thinking correctly.

A: You have data $X \sim \mathcal{B}(\theta)$, and you observe $(X_1,\dots,X_n)$,  $X_o = \sum X_i$, which means that for $k\in \{0,\dots,n\}$,
$$
\mathbb P(X_o = k \mid \theta) = \binom{n}{k} \theta^k(1-\theta)^{n-k}
$$
From a bayesian perspective you also have a prior distribution on $\theta$ which is a Beta distribution $p(\alpha,\beta)$.
Then you get the posterior distribution of $\theta$,
\begin{align*}
p(\theta \mid X_o) &\propto p(\alpha,\beta) \mathbb P(X_o \mid \theta) \\
&\propto p(\alpha,\beta) \theta^{X_o} (1-\theta)^{n-X_o},
\end{align*}
and you can derive the maximum a posteriori,
$$
\hat \theta= \arg\max_{\theta} p( \theta \mid X_o)
$$
Now if you want to compute the probability of getting 1 head out of 5 (new and independent) coin tosses, given  that the probability of head is $\hat \theta$, you can simply put $\hat \theta$ in the likelihood $\mathbb P(X \mid \theta)$:
$$
\mathbb P(X=1 \mid \hat \theta ) = \binom{5}{1} \hat \theta(1-\hat \theta)^4
$$

But from a Bayesian point of view it may be more relevant to consider all possible values of $\theta$, and not just a point estimate like $\hat \theta$, and rather compute
$$
\mathbb P(X= 1 \mid X_o) = \int_\Theta P(X  = 1 \mid \theta) p(\theta \mid X_o)d\theta
$$


text:
Q: NODE.JS - OpenShift 503 Service is Temporarily Unavilable: Server.js and Package.json files are fine Project running on a Node.js Server:
I'm going crazy over here. I can't figure out why I am getting a 503 error when I have done exactly what Open Shift instructs to do.
Server.js:
 var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
 var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';

server.listen(server_port, server_ip_address, function(){
 console.log("Listening on " + server_ip_address + ",
 server_port " +server_port);
});

package.json:
 {
 "scripts": {
   "start": "supervisor server.js"
 },
 "main": "server.js"
 }

I have gone through my logs and everything, and it says there is an issue at line 5 on server.js. How is that so? Am I going crazy, or am I missing something? The NPM modules are cleared, and the application says it is fine.
This is not a replica of another post, because I have done all of those.
Server Log Trail Error:
 ReferenceError: server is not defined
     at Object.<anonymous> (/var/lib/openshift/550764f6e0b8cd8a8a00007e/app-  root/runtime/repo/server.js:4:1)
     at Module._compile (module.js:456:26)
     at Object.Module._extensions..js (module.js:474:10)
     at Module.load (module.js:356:32)
     at Function.Module._load (module.js:312:12)
     at Function.Module.runMain (module.js:497:10)
     at startup (node.js:119:16)
     at node.js:902:3
 DEBUG: Program node server.js exited with code 8
 DEBUG: Starting child process with 'node server.js'
 /var/lib/openshift/550764f6e0b8cd8a8a00007e/app-       root/runtime/repo/server.js:4
 server.listen(server_port, server_ip_address, function(){
 ^

I have no idea what is going on. I keep getting a server is undefined issue, and everything is done correctly from what I can see.

A: You have a string opened at the end of line 5 and you never close it. change it to
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'

server.listen(server_port, server_ip_address, function(){
 console.log("Listening on " + server_ip_address
           + ", server_port " + server_port);
});

and you should be good to go

A: If that is what your file actually looks like, it looks like you are missing a chunk of code:
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(200, {'Content-Type': 'text/plain'});
      response.write("Welcome to Node.js on OpenShift!\n\n");
      response.end("Thanks for visiting us! \n");
});

server.listen( port, ipaddress, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

That code is referenced from this quickstart: https://github.com/openshift-quickstart/openshift-nodejs-http-and-websocket-example/blob/master/server.js
The references server.js includes some websocket code also, but you can ignore that (unless you want to use it, that's fine too)


text:
Q: How to get the last modification date for Contacts list (Add/Delete/Modify) How can i know the last date the Contacts table was modiefied at? i have tried ContactsContract.RawContacts.VERSION and CONTACT_STATUS_TIMESTAMP but it seems that these are used to know the modified date for a single contact, and it is not working well with me. how can i get the last modified date for any contact in the contacts List

A: At last i have made an array String in all the Versions of the Contacts i have, since it is the same this means that the Contacts table has not been changed, i have not found any other way, this is my Code
private String sGetCurrentContatcsVersions() {

        Cursor allContacts = mContext.getContentResolver().query(
                ContactsContract.RawContacts.CONTENT_URI, null, null, null, null);

        StringBuilder sbCurrentVersion = new StringBuilder();
        allContacts.moveToFirst();

        for (int i = 0; i < allContacts.getCount(); i++) {

            if (!TimelineService.bScannerIsRunning) {
                break;
            }
            int col = allContacts.getColumnIndex(ContactsContract.RawContacts.VERSION);
            sbCurrentVersion.append(allContacts.getString(col));
            allContacts.moveToNext();
        }

        return sbCurrentVersion.toString();
    }


text:
Q: how to change the class attribute of a selected item in the navigation bar I'm using twitter bootstrap with grails and have the following in my layout:

My Link

On my page I have the following:

        <meta name="layout" content="bootstrap">

        sometext

Question
In my layout how do I detect when the My Link action is clicked? so that I can highlight it using class="active"

A: Use actionName and controllerName to know in which action you are.

My Link

By the way, I suggest you to use g:link instead of g:createLink where it is possible. Here :

<g:link controller="request" action="new">My Link</g:link>

A: Here is how I tend to do this.
First, in your layout, you would do something like this:

My Link

And in your page:

        <meta name="layout" content="bootstrap">
        <meta name="nav" content="foo"/>

        sometext

foo is the trigger to apply the .active class.

A: Change your layout gsp to:

            <g:remoteLink controller='request' action='new' update='data'>My Link</g:remoteLink>

    <g:layoutBody />

A: This should work (notice it's slightly different to Isammoc's answer)

 profile


text:
Q: Start activity from Service through notification and get result back in service I am connecting BLE Device to phone, before connecting this device I want to connect this only if user verify this from other activity, I am showing notification when device found and start a Activity with verify button on this page, Till user clicks on verify button on the activity I want to pause the execution of onLeScan method in the service and after verification device will connect
My code is :
   public void onLeScan(final BluetoothDevice device, int rssi,
            byte[] scanRecord) {

        Log.i(TAG, "BluetoothLeService::onLeScan " + device.getAddress()
                + " name: " + device.getName());

  //We are creating notification here

   NotificationManager notificationManager =
                 (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                Notification myNotification = new Notification(R.drawable.icon,
                  "Notification!",
                  System.currentTimeMillis());
        String notificationTitle = "Exercise of Notification!";
        String notificationText = "http://google.com/";
        Intent myIntent = new Intent(getApplicationContext(), SettingActivity.class);
        PendingIntent pendingIntent
          = PendingIntent.getActivity(getBaseContext(),
            0, myIntent,
            Intent.FLAG_ACTIVITY_NEW_TASK);
        myNotification.defaults |= Notification.DEFAULT_SOUND;
        myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
        myNotification.setLatestEventInfo(getApplicationContext(),
           notificationTitle,
           notificationText,
           pendingIntent);
        notificationManager.notify(0, myNotification);

        if (Verified) {
    if (connect(device.getAddress())) {
    } else {
        //Skip to connect
            }
        }
    }
};


text:
Q: decrypt password in laravel 4 I need help. I'm using Laravel 4, I'm very new in laravel and i have 4 days in a row trying to solve this problem :(
I don't know how to decrypt a password to email it to the user and with it, activate his account.
I hope you can help me. Thanks.
My RegController.php:
//creates a key for 24h to activate account
$key = Str::random(32);
        Cookie::queue('key', $key, 60*24);
        Cookie::queue('email', $user->email, 60*24);

        //creates url
        $msg = "email/$key")."'>Confirm acount";

        $data = array(
            'user' => $user,
            'msg' => $msg,
            );

        $fromEmail = 'noreply@noreply.com';
        $fromName = 'Administrator';

        Mail::send('emails.register', $data, function($message) use ($fromName, $fromEmail, $user){
            $message->to($user->email);
            $message->from($fromEmail, $fromName);
            $message->subject('Confirm registration in Laravel');
        });
        $message = '
we sent an email to confirm your registration
';
        return Redirect::to('registro')->with('message', $message);

The view show in the email:

Welcome to the aplication Laravel

Your user: {{$user->username}}

Your password: {{$passworddecrypted)}}

Confirm your registration on this link:

    {{$msg}}

I don't know how to decrypt in this part, when I send the email, the encrypted password always appears
Email example:
Welcome to the aplication Laravel
Your user: lalo
Your password: eyJpdiI6IllHZzFcL1hxaGNRd2w0UkRLZTdNMWt3PT0iLCJ2YWx1ZSI6IlJZMmkyeElYRVpka21cL25BU2ZrQ093PT0iLCJtYWMiOiI5ZTBlYTYzOTZjOTE0YmFkZDE4OTlkY2M1MjBiMGRmOGZkMWExYTE0MzI1MWNiN2FmMGM0ZjllMjcxZjVjZjYyIn0=
Confirm your registration on this link:
Confirm registration in Laravel.


text:
Q: How can I make a deepcopy of a function in Python? I would like to make a deepcopy of a function in Python.  The copy module is not helpful, according to the documentation, which says:

This module does not copy types like module, method, stack trace, stack frame, file,
  socket, window, array, or any similar types. It does "copy" functions and classes (shallow
  and deeply), by returning the original object unchanged; this is compatible with the way
  these are treated by the pickle module.

My goal is to have two functions with the same implementation but with different docstrings.
def A():
    """A"""
    pass

B = make_a_deepcopy_of(A)
B.__doc__ = """B"""

So how can this be done?

A: from functools import partial

def a():
    """Returns 1"""
    return 1

b = partial(a)
b.__doc__ = """Returns 1, OR DOES IT!"""

print help(a)
print help(b)

Wrap it as a partial?

A: The FunctionType constructor is used to make a deep copy of a function.
import types
def copy_func(f, name=None):
    return types.FunctionType(f.func_code, f.func_globals, name or f.func_name,
        f.func_defaults, f.func_closure)

def A():
    """A"""
    pass
B = copy_func(A, "B")
B.__doc__ = """B"""

A:
My goal is to have two functions with the same implementation but with different docstrings.

Most users will do this, say the original function is in old_module.py:
def implementation(arg1, arg2):
    """this is a killer function"""

and in new_module.py
from old_module import implementation as _implementation

def implementation(arg1, arg2):
    """a different docstring"""
    return _implementation(arg1, arg2)

This is the most straightforward way to reuse functionality. It is easy to read and understand the intent.
Nevertheless, perhaps you have a good reason for your main question:

How can I make a deepcopy of a function in Python?

To keep this compatible with Python 2 and 3, I recommend using the function's special __dunder__ attributes. For example:
import types

def copy_func(f, name=None):
    '''
    return a function with same code, globals, defaults, closure, and
    name (or provide a new name)
    '''
    fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__,
        f.__defaults__, f.__closure__)
    # in case f was given attrs (note this dict is a shallow copy):
    fn.__dict__.update(f.__dict__)
    return fn

And here's an example usage:
def main():
    from logging import getLogger as _getLogger # pyflakes:ignore, must copy
    getLogger = copy_func(_getLogger)
    getLogger.__doc__ += '\n    This function is from the Std Lib logging module.\n    '
    assert getLogger.__doc__ is not _getLogger.__doc__
    assert getLogger.__doc__ != _getLogger.__doc__

A commenter says:

This can't work for built‑in functions

Well I wouldn't do this for a built-in function. I have very little reason to do this for functions written in pure Python, and my suspicion is that if you are doing this, you're probably doing something very wrong (though I could be wrong here).
If you want a function that does what a builtin function does, and reuses the implementation, like a copy would, then you should wrap the function with another function, e.g.:
_sum = sum
def sum(iterable, start=0):
    """sum function that works like the regular sum function, but noisy"""
    print('calling the sum function')
    return _sum(iterable, start)

A: def A():
    """A"""
    pass

def B():
    """B"""
    return A()

A: The others answers do not allow for serialization with pickle. Here a code that I am using to clone a function and allow for serialization for python3:
import pickle
import dill
import types

def foo():
    print ('a')

oldCode=foo.__code__

name='IAmFooCopied'

newCode= types.CodeType(
        oldCode.co_argcount,             #   integer
        oldCode.co_kwonlyargcount,       #   integer
        oldCode.co_nlocals,              #   integer
        oldCode.co_stacksize,            #   integer
        oldCode.co_flags,                #   integer
        oldCode.co_code,                 #   bytes
        oldCode.co_consts,               #   tuple
        oldCode.co_names,                #   tuple
        oldCode.co_varnames,             #   tuple
        oldCode.co_filename,             #   string
        name,                  #   string
        oldCode.co_firstlineno,          #   integer
        oldCode.co_lnotab,               #   bytes
        oldCode.co_freevars,             #   tuple
        oldCode.co_cellvars              #   tuple
        )

IAmFooCopied=types.FunctionType(newCode, foo.__globals__, name,foo.__defaults__ , foo.__closure__)
IAmFooCopied.__qualname__= name
print ( 'printing foo and the copy', IAmFooCopied, foo )
print ( 'dill output: ', dill.dumps(IAmFooCopied ))
print ( 'pickle Output: ', pickle.dumps (IAmFooCopied) )

Output:
printing foo and the copy <function IAmFooCopied at 0x7f8a6a8159d8> <function foo at 0x7f8a6b5f5268>
dill output:  b'\x80\x03cdill._dill\n_create_function\nq\x00(cdill._dill\n_load_type\nq\x01X\x08\x00\x00\x00CodeTypeq\x02\x85q\x03Rq\x04(K\x00K\x00K\x00K\x02KCC\x0ct\x00d\x01\x83\x01\x01\x00d\x00S\x00q\x05NX\x01\x00\x00\x00aq\x06\x86q\x07X\x05\x00\x00\x00printq\x08\x85q\t)X\x10\x00\x00\x00testCloneFunc.pyq\nX\x0c\x00\x00\x00IAmFooCopiedq\x0bK\x05C\x02\x00\x01q\x0c))tq\rRq\x0ec__builtin__\n__main__\nh\x0bNN}q\x0ftq\x10Rq\x11.'
pickle Output:  b'\x80\x03c__main__\nIAmFooCopied\nq\x00.'

You may encounter problem with the qualname attribute if you try this snippet with class methods (I think pickle should fail to find your function). I never tried it, however it should be easily fixable. Just check the doc about qualname

A: It's quite easy to do using lambda and rest parameters:
def my_copy(f):
        # Create a lambda that mimics f
        g = lambda *args: f(*args)
        # Add any properties of f
        t = list(filter(lambda prop: not ("__" in prop),dir(f)))
        i = 0
        while i < len(t):
            setattr(g,t[i],getattr(f,t[i]))
            i += 1
        return g

# Test
def sqr(x): return x*x
sqr.foo = 500

sqr_copy = my_copy(sqr)
print(sqr_copy(5)) # -> 25
print(sqr_copy(6)) # -> 36
print(sqr_copy.foo) # -> 500
print(sqr_copy == sqr) # -> False

Try it online!

A: put it in a function:
def makefunc( docstring ):
    def f():
        pass
    f.__doc__ = docstring
    return f

f = makefunc('I am f')
g = makefunc("I am f too")

A: Adjusted for python3
import types
def copy_func(f, name=None):
    return types.FunctionType(f.__code__, f.__globals__, name or f.__name__,
        f.__defaults__, f.__closure__)
def func1(x):
  return 2*x
func2=copy_func(func1)
print(func2(7))

A: I've implemented a general-purpose function copy in haggis, a library which I wrote and maintain (available with pip but probably not conda). haggis.objects.copy_func makes a copy on which you can not only reassign the __doc__ attribute, but also modify the module and __globals__ attributes effectively.
from haggis.objects import copy_func

def a(*args, **kwargs):
    """A docstring"""

a2 = copy_func(a)
a2.__doc__ = """Another docstring"""

>>> a == a2
False
>>> a.__code__ == a2.__code__
True
>>> a.__doc__
'A docstring'
>>> a2.__doc__
'Another docstring'


text:
Q: How to update formulas referring to different files wih the newest sheet added to them in Excel I have several Excel files that represent Projects. Every month there is a new sheet that appears with the updated information for the current month. I need to combine them in one sheet as a summery overview.
My problem comes when from the fact that I am downloading the project files on my PC and the formula dragging information from them refers to the folder and the sheet. Let's say now we are in October and the formula is:
IFERROR('[Project (1).xlsm]Oct 17'!$E$24;" ").

However, when November comes I will need to update Oct 17 to Nov 17 which is huge manual work.
Is there a way to do that with a drop down menu related to some VBA macro? For example there is an Intro page on which you can choose from a drop down menu the certain month and all the formula paths are updated based on that.

A: You could try the following where you run a sub to find formulas that contain a specific string stored in a variable. I am calling it FindMonth. You search and replace this string with the desired month, ReplaceMonth. Note i am including the end part of the year to the string e.g. "Nov 17". When running each month you just edit these two lines:
 FindMonth = "Oct 17" 'Edit for month you want to find
 ReplaceMonth = "Nov 17" 'Edit for month you want to replace with

You could associate the procedure with a command button and use inputbox prompts for the FindMonth and ReplaceMonth and assign the value input to the variables instead.
You define the area for replacement in the Set searchRange.
As i don't know what area you are searching i have used 2 functions by Ron De Bruin to find the last used row and column in the sheet variable ws (you would amend to the sheet you want to change formulas in) and said the search range is from A1 to the last used cell i.e. lastrow, lastcolumn.
 Set searchRange = ws.Range(ws.Cells(1, 1), ws.Cells(LastRow(ws), LastCol(ws)))

This is to prevent looping through every cell in the sheet.
You would need to amend to which ever sheet you are actually replacing in.
Also, consider what kind of error handling you want to include in case lookup sheet is not present in lookup workbook (e.g.Dec 17 sheet missing) or workbook is not open...... I have used On Error Resume Next for now. You might choose something like On Error GoTo ErrHandler and in the ErrHandler have a CASE Err.Number 1004 ...do something........
  Option Explicit

  Sub ReplaceFormula()
    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Sheet1") ' change as appropriate to your sheet name

    Dim searchRange As Range
    Dim cell As Range

    Dim FindMonth As String
    Dim ReplaceMonth As String

    FindMonth = "Oct 17"
    ReplaceMonth = "Nov 17"

    Set searchRange = ws.Range(ws.Cells(1, 1), ws.Cells(LastRow(ws), LastCol(ws)))

    Application.EnableEvents = False

    On Error Resume Next 'Sheet may not be present or source workbook may not be open

    For Each cell In searchRange.Cells

        If InStr(1, cell.Formula, FindMonth) > 0 Then cell.Formula = Replace(cell.Formula, FindMonth, ReplaceMonth)

    Next cell

    On Error GoTo 0

    Application.EnableEvents = True

End Sub

Function LastRow(sh As Worksheet)
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            LookAt:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function

Function LastCol(sh As Worksheet)
    On Error Resume Next
    LastCol = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            LookAt:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByColumns, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Column
    On Error GoTo 0

End Function

A: I typically do a find replace for this - I also have a monthly job where I have this scenario. (You can restrict the search replace to highlighted cells if required).
Also, the reference to the directory should dissappear if you load the files in memory.
With the above info you could script this - I do find the search replace takes a few seconds of a multi-hour job so I haven't bothered automating. Hit F2 and select what you want to replace and paste that into the find box (e.g. ]Oct 17 and then replace with ]Nov 17


text:
Q: How to schedule task every second Monday and given hour in Java Spring Is there any way to schedule a task in Spring so it runs every other Monday at a given hour (say, midnight)? I know running the task every Monday at midnight using cron would look like that 0 0 0 * * MON but it gets kinda obscure for me how to handle the "every other" Monday.
To be clear: if I deployed my application on Sunday 06.06.2021, I'd like the task to run on midnight 07.06.2021, 21.06.2021, 05.07.2021
Would something like 0 0 0 * * MON/2 work? Or should I take a different approach, maybe using something different than cron?
Any help will be much appreciated

A: No,Cron doesn't have such things in JAVA .It has some kind of workaround in linux and unix machines , but not in java.
But you can programmatically achieve it by using weeks of month.

    Calendar c = Calendar.getInstance();
       if(c.get(Calendar.WEEK_OF_MONTH) % 2 != 0) {
             //execute job
       } else {
             //not execute job just skip operation
       }

The above code executes for all odd weeks of a month.Let's say a particular month has 5 weeks , this will run for 1,3 and 5 of that month and will again run on 1st week of next month.
If you badly want it to run only twice a month , use can block it by checking if the week of month is grater than 4 and block it. (* I haven't checked it , give it a try)

    Calendar c = Calendar.getInstance();
       if(c.get(Calendar.WEEK_OF_MONTH) % 2 != 0 && !c.get(Calendar.WEEK_OF_MONTH)>4) {
             //execute job
       } else {
             //not execute job just skip operation
       }


text:
Q: Reactjs material ui textfield number max and min
I have an input field which should only take values between min and max.
I did as shown below, but entering the number manually as seen in the image bypasses the control.
How can I do?
Link: codesandbox
<TextField
          id="outlined-number"
          label="Number max number 10"
          type="number"
          InputProps={{ inputProps: { min: "0", max: "10", step: "1" } }}
          variant="outlined"
          handleChange('number')
        />

My handleChange:
const handleChange = field => ({ target: { value } }) => {
        setState(prev => {
            const _item = prev.item;
            _item[field] = value;
            return { ...prev, item: _item };
        });
    };

handleChange('nameAttr')

A: You can use the TextField as a controlled component to prevent the input to be more than 10. You should also use an additional state variable for that.
The code is as follows (Replace the component with the component given below and import useEffect additionally)
export default function FormPropsTextFields() {
  const classes = useStyles();

  const [value, setValue] = useState();

  function handler(e) {
    if (Number(e.target.value) > 10) {
      setValue(10);
    }else{
      setValue(e.target.value);
    }
  }

  return (
    <form className={classes.root} noValidate autoComplete="off">
      <div>
        <TextField
          id="outlined-number"
          label="Number max number 10"
          type="number"
          InputProps={{ inputProps: { min: "0", max: "10", step: "1" } }}
          variant="outlined"
          onChange={handler}
          value={value}
        />
      </div>
    </form>
  );
}

So if the input value is more than 10, it prevents updating the state variable value thanks to our logic in the handler function. This is not the best solution and you may want to build upon you logic based on this example.

A: Maybe a little late but it worked for me
const minValue = 0  //Or whichever number you want
const maxValue = 10
const [value, setValue] = useState(minValue)

//Executes when the value changes
const handle = (e) => {
    const newValue = Math.min(Math.max(e.target.value, minValue), maxValue)
    setValue(previousValue => newValue)
}

Then in yout TextField you do...
    <TextField
      id="outlined-number"
      label="Number max number 10"
      type="number"
      variant="outlined"
      handleChange(e => handle(e))
      value={value}
    />

A: set a function to onChange of the text input
set a state of the number
const [number, setNumber] = useState('');

set the value of the text input to the number and then add the onChange event
<TextField
    ....
    onChange={validateNumber}
    value={number}
/>

const validateNumber = (event) => {
  const value = event.target.value;
  const setValue = value <= 10 ? value : number; //if the input value is greater than 10, then don't change the input value
  setNumber(setValue);
};

Updated Example

A: https://codesandbox.io/s/material-demo-forked-hxflw?file=/demo.js
Use onBlur or onChange to adjust your value to your max.
Using your onChange:
const handleChange = field => ({ target: { value } }) => {
    setState(prev => {
        const _item = prev.item;
        _item[field] = parseInt(value) > 10 ? "10" : value;
        return { ...prev, item: _item };
    });
};