text:
Q: Returning the result of an AJAX Call in Codeigniter I want to implement AJAX in my codeigniter application, but I am clueless on how to return the data to the view. Also I'm not very sure if I am executing the controller in the right manner. However, the AJAX call is a success as I get the message below
XHR finished loading:

$.ajax({
              type: "post",
              cache:true,
              url: "<?php echo site_url('getrates/index'); ?>",
            }).done(function() {
              $("#ajax-message").html("Success");
            });

Here is the controller
class Getrates extends CI_Controller {

public function __construct()
{
    parent::__construct();
    $this->load->model('getrates');
}

public function index()
{
     $username = $sess_array['username'];

     $data['rates'] = $this->getrates->index($username);

     $this->load->view('dashboard', $data['rates']);

}

}
And the Model
class Rates extends CI_Model {

public function __construct()
{
    parent::__construct();

}

function index($user) {

    $username = $user;

    $sql = "SELECT * FROM tarrifs WHERE username = ? ";

    $rates = $this->db->query($sql, array(1, $username));

    return $rates;

}

}

A: Please put ajax response in message section, try this way
 $.ajax({
                  type: "post",
                  cache:true,
                  url: "<?php echo site_url('getrates/index'); ?>",
                }).done(function(data) {
                  $("#ajax-message").html(data);
                });

In model
function index($user) {

    $username = $user;

    $sql = "SELECT * FROM tarrifs WHERE username = {$username} ";

    $rates = $this->db->query($sql);

    return $rates->row_array(); // return single row in array

}

And controller please try this way
public function index()
{
     $username = $sess_array['username'];

     $data['rates'] = $this->getrates->index($username);
     // true parameter return view data
     echo $this->load->view('dashboard', $data['rates'], true);
     die();

}

A: I'm guessing that $.ajax is not retrieving any data coming from your controller, maybe because its pointing to the wrong url, maybe you should replace it with this instead:
url: "<?php echo site_url('getrates'); ?>

referring to how codeigniter controllers works, and instead of loading a view in that controller try echoing the value your receiving from your model instead, so your $.ajax wouldn't retrieve the whole view your controller is rendering, ie:
$username = $sess_array['username'];
$data['rates'] = $this->getrates->index($username);
echo json_encode($data['rates']) or return json_encode($data['rates'])

which one works to you the best, then change the id of your placeholder that exist in a certain page, then load that controller instead of the one your loading right now:
$("#a-different-page").html(data);

As to your model I'm not sure if it's incorrect to name a model function as "index" but I would suggest naming it with a more appropriate one like function model_genrates(){}
hope it helps, cheers!


text:
Q: R: Replace Abbreviations\ Words I have tried to resolve this problem all day but without any improvement.
I am trying to replace the following abbreviations into the following desired words in my dataset:
-Abbreviations:  USA, H2O, Type 3, T3, bp

*

*Desired words United States of America, Water, Type 3 Disease, Type 3 Disease, blood pressure

The input data is for example

*

*[1] I have type 3, its considered the highest severe stage of the disease.

*[2] Drinking more H2O will make your skin glow.

*[3] Do I have T2 or T3? Please someone help.

*[4] We don't have this on the USA but I've heard that will be available in the next 3 years.

*[5] Having a high bp means that I will have to look after my diet?
The desired output is

*

*[1] i have type 3 disease, its considered the highest severe stage
of the disease.

*[2] drinking more water will make your skin glow.

*[3] do I have type 3 disease? please someone help.

*[4] we don't have this in the united states of america but i've heard that will be available in the next 3 years.

*[5] having a high blood pressure means that I will have to look after my diet?
I have tried the following code but without success:
   data= read.csv(C:"xxxxxxx, header= TRUE")
   lowercase= tolower(data$MESSAGE)
   dict=list("\\busa\\b"= "united states of america", "\\bh2o\\b"=
   "water", "\\btype 3\\b|\\bt3\\"= "type 3 disease", "\\bbp\\b"=
   "blood pressure")
   for(i in 1:length(dict1)){
   lowercasea= gsub(paste0("\\b", names(dict)[i], "\\b"),
   dict[[i]], lowercase)}

I know that I am definitely doing something wrong. Could anyone guide me on this? Thank you in advance.

A: If you need to replace only whole words (e.g. bp in Some bp. and not in bpcatalogue) you will have to build a regular expression out of the abbreviations using word boundaries, and - since you have multiword abbreviations - also sort them by length in the descending order (or, e.g. type may trigger a replacement before type three).
An example code:
abbreviations <- c("USA", "H2O", "Type 3", "T3", "bp")
desired_words <- c("United States of America", "Water", "Type 3 Disease", "Type 3 Disease", "blood pressure")
df <- data.frame(abbreviations, desired_words, stringsAsFactors = FALSE)
x <- 'Abbreviations: USA, H2O, Type 3, T3, bp'
sort.by.length.desc <- function (v) v[order( -nchar(v)) ]

library(stringr)
str_replace_all(x,
    paste0("\\b(",paste(sort.by.length.desc(abbreviations), collapse="|"), ")\\b"),
    function(z) df$desired_words[df$abbreviations==z][[1]][1]
)

The paste0("\\b(",paste(sort.by.length.desc(abbreviations), collapse="|"), ")\\b") code creates a regex like \b(Type 3|USA|H2O|T3|bp)\b, it matches Type 3, or USA, etc. as whole word only as \b is a word boundary. If a match is found, stringr::str_replace_all replaces it with the corresponding desired_word.
See the R demo online.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any way to create rounded corners for SVG ARC? I would like to create rounded corners for svg arc.

Here is my code for above arc
(function()
{
     var svg = d3.select('#pieChart').append("svg:svg").attr('width', 300).attr('height', 300).attr('fill', '#123456').append("g").attr("transform", "translate(" + 300 / 2 + "," + 300 / 2 + ")");
     var arc = d3.svg.arc().innerRadius(100).outerRadius(140).startAngle(0).endAngle(190 * (Math.PI)/180);
     svg.append("path").attr('d', arc);
}());

A: If you add a stroke then you can set the properties appropriately on the stroke to render rounded corners - here's the rough idea:
(function()
{
     var svg = d3.select('#pieChart').append("svg:svg").attr('width', 300).attr('height', 300).append("g").attr("transform", "translate(" + 300 / 2 + "," + 300 / 2 + ")");
     var arc = d3.svg.arc().innerRadius(100).outerRadius(100).startAngle(0).endAngle(190 * (Math.PI)/180);
     svg.append("path").attr('stroke-width','60px').attr('stroke-linejoin','round').attr('d', arc).attr('fill', '#123456').attr('stroke','#123456');
}());

Demo fiddle here

A: All you need to do is specify a corner radius. However, cornerRadius is only a recent addition to d3, so it won't work in any of the versions currently available in the SO snippet editor.
You can see it working below, using the latest version of d3 imported directly from d3js.org:

(function(theta) {
  var svg = d3.select('#pieChart')
    .append("svg:svg")
    .attr('width', 300)
    .attr('height', 300)
    .attr('fill', '#123456')
    .append("g")
    .attr("transform", "translate(" + 300 / 2 + "," + 300 / 2 + ")");
  var arc = d3.svg.arc()
 /*************************************************/
 /* This only works in the latest version (3.5.5) */
    .cornerRadius(20)
 /*************************************************/
    .innerRadius(100)
    .outerRadius(140)
    .startAngle(0)
    .endAngle(theta * (Math.PI)/180)
  svg.append("path")
    .attr('d', arc)
}(240));


text:
Q: Gradle, extend/include default settings file in another Is it possible to extend default settings.gradle file?
For example, default settings file(settings.gradle) is as follows
include 'Project1'
 include 'Project2'
i want another settings file (customsettings.gradle) to include the content of settings.gradle and the below snippet to use in CI system.
setBuildFileName(rootProject)

def setBuildFileName(project) {
project.children.each { childProject ->
childProject.buildFileName = "projectname.gradle"
assert childProject.projectDir.isDirectory()
assert childProject.buildFile.isFile()
setBuildFileName(childProject)
  }
}

I tried
include 'settings.gradle'

apply from: 'settings.gradle'`

but non of them worked.
Thanks


text:
Q: What is $\lim_{n \to \infty} n(1-n^{-\alpha}x)^{n-1} - (n-1)(1-n^{-\alpha}x)^{n}$? I'm trying to find the following value.
For $x>0$ and $\alpha>0$,
$$
\lim_{n \to \infty} n(1-n^{-\alpha}x)^{n-1} - (n-1)(1-n^{-\alpha}x)^{n}
$$
It's clear that when $\alpha=1$, the result is $exp(-x) (1+x)$. But how about when $0 < \alpha < 1$ or $\alpha > 1$?

What I tried:
$$
\begin{aligned}
\lim_{n \to \infty} n(1-n^{-\alpha}x)^{n-1} - (n-1)(1-n^{-\alpha}x)^{n} & = \lim_{n \to \infty}(1-n^{-\alpha}x)^{n} \Big[ n (1-n^{-\alpha}x)^{-1} - (n-1) \Big] \\
\end{aligned}
$$
I know $\lim_{n \to \infty}(1-n^{-\alpha}x)^{n} = 0 $ when $0 < \alpha < 1$, and $\lim_{n \to \infty}(1-n^{-\alpha}x)^{n} = 1 $ when $\alpha > 1$.
But what happens if they are combined with the remainder term?

A: For $x>0$ and $\alpha>0$, we can first perform some transformations on the limit:
\begin{align*}
&\lim_{n\to\infty}n(1-n^{-\alpha}x)^{n-1}-(n-1)\cdot (1-n^{-\alpha}x)^n\\
&=\lim_{n\to\infty}n\cdot \left(1-\dfrac{x}{n^\alpha}\right)^{n-1} - (n-1)\cdot \left(1-\dfrac{x}{n^\alpha}\right)^n\\
&=\lim_{n\to\infty}\left(1-\dfrac{x}{n^\alpha}\right)^{n-1}\cdot \left(1+\dfrac{x}{n^{\alpha-1}}-\dfrac{x}{n^\alpha}\right) .
\end{align*}
We can consider the limits of the two factors separately. For the second factor, it is easy to see that
$$\lim_{n\to\infty} 1+\dfrac{x}{n^{\alpha-1}}-\dfrac{x}{n^\alpha}=\begin{cases}1 &\text{if }\alpha>1,\\ 1+x &\text{if }\alpha=1,\\ +\infty &\text{if }1>\alpha>0\end{cases}$$
For the first factor we have:
\begin{align*}
\lim_{n\to\infty}\left(1-\dfrac{x}{n^\alpha}\right)^{n-1}&=\exp\left[\ln \left(\lim_{n\to\infty}\left(1-\dfrac{x}{n^\alpha}\right)^{n-1}\right)\right]&\\
&=\exp\left[\lim_{n\to\infty} \ln \left(1-\dfrac{x}{n^\alpha}\right)^{n-1}\right]&\\
&=\exp\,\lim_{n\to\infty} (n-1)\ln\left(1-\dfrac{x}{n^\alpha}\right)&\\
&=\exp\lim_{n\to\infty}\dfrac{\ln\left(1-\frac{x}{n^\alpha}\right)}{\frac{1}{n-1}}\\
&=\exp \left[\lim_{n\to\infty} \dfrac{\dfrac{1}{1-\dfrac{x}{n^\alpha}}\cdot \dfrac{-\alpha\cdot x}{n^{\alpha+1}}}{\dfrac{-1}{(n-1)^2}}\right] &\text{(By L'Hôpital's rule)}\\
&=\exp\left[\lim_{n\to\infty}\dfrac{\alpha\cdot x}{1-\dfrac{x}{n^\alpha}}\cdot \dfrac{(n-1)^2}{n^{\alpha+1}}\right]\\
&=\begin{cases}\exp(0)=1 &\text{if }\alpha>1,\\ \exp(\alpha\cdot x) &\text{if }\alpha=1,\\ +\infty &\text{if }1>\alpha>0. \end{cases}
\end{align*}
Hence, putting things together, we conclude that
$$\lim_{n\to\infty}n(1-n^{-\alpha}x)^{n-1}-(n-1)\cdot (1-n^{-\alpha}x)^n=\begin{cases}1\cdot 1=1, &\text{if }\alpha>1,\\ (1+x)\cdot e^{\alpha\cdot x} &\text{if }\alpha=1\\ +\infty &\text{if }1>\alpha>0. \end{cases}$$


text:
Q: Prove that $\ell_1$ is a Banach space Check my proof please. The space $\ell_1$ is defined as
$$\ell_1:=\left\{(x_n)\in s(\Bbb K):\|(x_n)\|_1=\sum |x_n|<\infty\right\}$$
Here $\Bbb K$ represents $\Bbb R$ or $\Bbb C$. The operations of a normed vector space are easy to check, we can see that if $s,t\in\ell_1$ then $s+t\in\ell_1$, etc. Then I need to show that $\ell_1$ is complete.
This mean that for every Cauchy sequence in $\ell_1$ it converges to some element of $\ell_1$:
$$(\forall\epsilon>0,\exists N\in\Bbb N:\|s_n-s_m\|_1<\epsilon,\forall n,m\ge N)\implies (s_n)\to s\in\ell_1$$
Because $\|s_n\|_1=\sum |x_{k,n}|$ and $\|s_m\|_1=\sum |x_{k,m}|$ then we can write
$$\|s_n-s_m\|_1=\sum|x_{k,n}-x_{k,m}|<\epsilon$$
Because $\Bbb K$ is a Banach space then $\lim_m x_{k,m}=x_k\in\Bbb K$. In other words because $(x_{k,n})_k$ is Cauchy, by the above expression, and every $x_{k,n}\in\Bbb K$ then $(x_{k,n})_k\to x_k$ and we can write
$$\lim_m\sum |x_{k,n}-x_{k,m}|=\sum |x_{k,n}-x_k|\le\epsilon$$
And
$$\left|\sum|x_{k,n}|-\sum|x_k|\right|=\sum ||x_{k,n}|-|x_k||\le\sum |x_{k,n}-x_k|\le\epsilon$$
From the last statement if $\sum |x_k|=\infty$, and because $\sum|x_{k,n}|=x\ge 0$ we would have the contradiction
$$|x-\infty|\le\epsilon$$
then necessarily $\sum |x_k|$ converges. Then if we define $s=(x_k)$ we finally have that $(s_n)\to s$.$\Box$.


text:
Q: strange udp socket sendto behaviour I'm trying to send a data using UDP socket and capture the data using a wireshark (under Windows7):
client_sockd= socket(AF_INET,SOCK_DGRAM,IPPROTO_IP);
client_address.sin_family = AF_INET;
client_address.sin_addr.s_addr = inet_addr("192.168.3.100");
client_address.sin_port=htons(8015);
client_len=sizeof(client_address);
int sended = sendto(client_sockd,buf,11,0,(const struct sockaddr *)&client_address,sizeof(client_address));

it's sending the packet to the correct ip but dest port becoming 2698. i'm trying to change the port in my code, but it doesnot have any effect to the real destination port. It's still to be 2698.
How can i fix it?

A: Try IPPROTO_UDP instead of IPPROTO_IP:
client_sockd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);


text:
Q: IndexOf() he will only show the first encounter with the letter **// function for searching the positions of a letter**
function zoekLetter() {
    var letter = "Minister Jet Bussemaker van Onderwijs, Cultuur en      Wetenschap bracht maandag een bezoek aan SintLucas locatie Boxtel. Vanuit het Koning Willem College waren hierbij aanwezig: Cor van Gerven, Erwin Brouwer en de leerlingen Gezel schilder Rick van Hoof, Wesley Stolzenbach en de Gezel stukadoor Rick van der Werf. Doel van het bezoek van de minister was om de titel Meester, die de excellentie van iemands vakmanschap bestempelt, te bespreken en te kijken of deze binnenhet mbo ingezet kan worden. Bijvoorbeeld bij een 'moderne' opleiding zoals Game art.";
    var letterinvoer = prompt("voer een letter in!");
    for (i = 0; i < letter.length; i++) {
        var locatie = letter.indexOf(letterinvoer);
        alert(locatie);
    }

}

// it will only show the first encounter with the letter given in the prompt, and i need to show all the positions


text:
Q: Changing the background on a tabPageBackground The code itself works but my TabPages's BackgroundImage still remains the same even if I change it into transparent. So how can I make an Image appear for the background of an TabPage. All it does now is show the image behind the TabPage's Background.
Random randomPic = new Random();

private void button4_Click(object sender, EventArgs e)
{
     int ShowPic = 0;

     ShowPic = randomPic.Next(1, 3);

     if(ShowPic == 1)
     {
          BackgroundImage = Image.FromFile(@"myndir/Animal-1.jpg");
     }
}

A: BackgroundImage changes the Form's BackgroundImage. To change the TabPages's BackgroundImage you should try this:
tabControl1.TabPages[0].BackgroundImage = Image.FromFile(@"myndir/Animal-1.jpg");

And if you want to change all TabPages's BackgroundImage try this:
for (int i = 0; i < tabControl1.TabCount; i++)
{
     tabControl1.TabPages[i].BackgroundImage = Image.FromFile(@"myndir/Animal-1.jpg");
}

Also if you want to make a transparent TabPage, have a look at this post.


text:
Q: Multiple threads. Doing similar tasks, but need to see their output I have a program which I select the amount of threads and it starts it, but I would like to have control of closing each thread one by one after they have started and see there output of each thread as well.
What is the best approach in this case?

A: These methods allow you to fetch results of all tasks, that were submitted to an executor service. And this shuts it down.

A: Create a Hashtable that will contain your threads and have the thread name used as the Key in the hashmap. So whenever you want to perform an operation on your thread you can get its reference from the hashtable and do whatever you want with it.
Hashtable<String, Thread> threadTable = new Hashtable<String, Thread>();

Thread t1 = new Thread() {
    public void run() {
         //Do sttuff
    }
}

Thread t2 = new Thread() {
    public void run() {
         //Do sttuff
    }
}

threadTable.put("T1", t1);
threadTable.put("T2", t2);

Of course this the above is just a simple example. If you take a class and make it extends Thread, you can then add methods to suspend and resume the thread as well as printing out its status.


text: Q: Create Album with React Native CameraRoll With ReactNative CameraRoll, you can save a photo/video to an existing album on your device's camera roll. Is there a way to create the album, if it does not yet exist, before saving to it?


text:
Q: How to take a string of numbers and check if there are any duplicate numbers in python? How would I write code that will allow me to check for duplicates in a string of numbers.
alist = [['123456789', '112345678', '123345678', '859403126']]
(alist[0][0] = no duplicate)
(alist[0][1] = duplicate)
(alist[0][2] = duplicate)
(alist[0][3] = no duplicate)

Thanks for the help.

A: Create set and compare lengths
>>> x = alist[0][0]
>>> len(set(x)) == len(x)
True

A: You can try this approach:
"".join(set(alist[0][0]))

As a result you will get a set of unique letters in the string, and join() will join the letters back to a string in arbitrary order. After this operation simply check if new string has the same length as the original one.

A: this list comprehension
dups = [[len(set(el)) != len(el) for el in el0] for el0 in alist]

produces
[[False, True, True, False]]

i.e. False for 'no duplicates', True for 'duplicates'
In case you really want such literals, use:
dups = [[ 'duplicate' if len(set(el)) != len(el) else 'no duplicate' for el in el0] for el0 in alist]

which produces
[['no duplicate', 'duplicate', 'duplicate', 'no duplicate']]

A: First , I think pacholik's answer is the most easy-understanding one.
Inspird by this example , I provide the following solution
import re
alist = [['123456789', '112345678', '123345678', '859403126']]
for i in alist[0]:
    print('alist[0][{}] = '.format(i),'duplicate' if re.search(r'.*?(.).*?\1',i) else 'no duplicate')


text:
Q: login form through lightBox Effect I have used a simplest CSS to show a litebox view. The code I used is, I have removed the unnecessary CSS properties from here:

Html for the form

        <input id="name" name="name" type="text" />

        <input id="password" name="password" type="password" />
        <input type="submit" name="submit" value="Sign In" onclick="check(this.form)"/>

And a JavaScript function, to check if the fields are correct
function check(form)/*function to check userid & password*/
{

var name= $( "#name" );
var pass=$("#password");
 if(name== "admin" && pass == "admin")
  {
  document.getElementById('light').style.display='none';
  document.getElementById('fade').style.display='none';
  }
 else
 {
   alert("Error Password or Username");/*displays error message*/
  }
}

The functionality I want is, when the user inputs correct name and pass, that is "admin" the lite box effect fade away... But it is not, the lite box is still there. How can i close it. I also want that this litebox effect should be shown as the page loads.

A: Replace
var name= $( "#name" );
var pass=$("#password");

with
var name= $( "#name" ).val();
var pass=$("#password").val();

A: Is the problem that the submit event is not captured and prevented? In The markup there is no form. If you add it like
<form id="submit-me"> your form inputs

you can observe it via JS
$("#submit-me").submit(function(event) {
  // your js code
  event.preventDefault();
});

For your actual example you could try to add a "return false;" in the onclick handler? But I do not know whether this works...
Best regards


text:
Q: Прошу помощи в написании программы в jave совсем не шарю В ЭВМ автомастерской после обслуживания клиента вводится стоимость ремонта. В конце дня вместо стоимости вводится число 0, после чего ЭВМ выводит на экран дисплея общую сумму выручки за день. Составьте такую программу для ЭВМ.

A: Javascript:
for(var res=0,x;x=+prompt();res+=x);alert(res)

Java: tio.run
import java.util.function.*;
import javax.script.*;
import java.io.*;

public class Main {
  @FunctionalInterface
  public interface SupplierThrows<T> {
    T call() throws Exception;
  }

  public static void main(String[] args) throws Exception {
    var engine = new ScriptEngineManager().getEngineByName("js");
    engine.put("prompt", (SupplierThrows<String>)new BufferedReader(new InputStreamReader(System.in))::readLine);
    engine.put("alert", (Consumer<Object>)System.out::println);
    engine.eval("for(var res=0,x;x=+prompt();res+=x);alert(res)");
  }
}


text:
Q: python - How to find and visually mark the local minima of a sequence? How to draw a sequence of points with increasing local minima and mark them with another color? Something similar as in the picture. I am not able to set a list with that sequence and the minima are wrong. Or is there an easier way to do that?

I tried this code:
import sys
from numpy import NaN, Inf, arange, isscalar, asarray, array
import random
import numpy as np
import matplotlib.pyplot as plt

def peakdet(v, delta, x = None):
    '''
    Converted from MATLAB script at http://billauer.co.il/peakdet.html
    Returns two arrays
    function [maxtab, mintab]=peakdet(v, delta, x)
    '''
    maxtab = []
    mintab = []

    if x is None:
        x = arange(len(v))
    v = asarray(v)
    if len(v) != len(x):
        sys.exit('Input vectors v and x must have same length')
    if not isscalar(delta):
        sys.exit('Input argument delta must be a scalar')
    if delta <= 0:
        sys.exit('Input argument delta must be positive')

    mn, mx = Inf, -Inf
    mnpos, mxpos = NaN, NaN
    lookformax = True
    for i in arange(len(v)):
        this = v[i]
        if this > mx:
            mx = this
            mxpos = x[i]
        if this < mn:
            mn = this
            mnpos = x[i]
        if lookformax:
            if this < mx-delta:
                maxtab.append((mxpos, mx))
                mn = this
                mnpos = x[i]
                lookformax = False
        else:
            if this > mn+delta:
                mintab.append((mnpos, mn))
                mx = this
                mxpos = x[i]
                lookformax = True
    return array(maxtab), array(mintab)

if __name__=="__main__":
    from matplotlib.pyplot import plot, scatter, show
    series = [7,6,5,4,3,1,3,5,6,9,12,13,10,8,6,3,5,6,7,8,13,15,11,12,9,6,4,8,9,10,15,16,17,19,22,17,15,13,11,10,7,5,8,9,12]
    maxtab, mintab = peakdet(series,.3)
    y = np.linspace(0, 10, len(series))
    plt.plot(y, series, '-', color='black');
#    scatter(array(maxtab)[:,0], array(maxtab)[:,1], color='blue')
    scatter(array(mintab)[:,0], array(mintab)[:,1], color='red')
    show()

I got this figure:

A: Try scipy.signal.find_peaks. To find minima's you multiply series by -1.
find_peaks returns the indices of peaks or minima.  To get the correct plotting positions, you have to index x and series with the output from find_peaks.
If you are concerned about your singal containing sequences of decreasing minima, you could compare the magnitudes of sequential peaks using np.diff.
import matplotlib.pyplot as plt
from scipy.signal import find_peaks
import numpy as np

series = np.array([7,6,5,4,3,1,3,5,6,9,12,13,10,8,6,3,5,6,7,8,13,15,11,12,9,6,4,8,9,10,15,16,17,19,22,17,15,13,11,10,7,5,8,9,12])
peaks, _ = find_peaks(series)
mins, _ =find_peaks(series*-1)
x = np.linspace(0, 10, len(series))
plt.plot(x, series, color='black');
plt.plot(x[mins], series[mins], 'x', label='mins')
plt.plot(x[peaks], series[peaks], '*', label='peaks')
plt.legend()

A: There were two mistakes in your original code:

*

*In your original version, you used 'o' as marker symbol in plt.plot. This draw dots. Now you corrected it using '-' to draw lines.

*You still didn't call your peakdet with the same x as used for plotting the line. By using a different x the scatter plots get placed using different x-positions as the line plot.

Please refer to @dubbbdan's answer for a good alternative for your peakdet function. You'll need to experiment for the best settings depending on the exact values you have in your application.
Here is your original code, but with the mistakes corrected:
import sys
from numpy import NaN, Inf, arange, isscalar, array
import numpy as np
import matplotlib.pyplot as plt

def peakdet(v, delta, x):
    '''
    Converted from MATLAB script at http://billauer.co.il/peakdet.html
    Returns two arrays
    function [maxtab, mintab]=peakdet(v, delta, x)
    '''
    maxtab = []
    mintab = []
    if len(v) != len(x):
        sys.exit('Input vectors v and x must have same length')
    if not isscalar(delta):
        sys.exit('Input argument delta must be a scalar')
    if delta <= 0:
        sys.exit('Input argument delta must be positive')

    mn, mx = Inf, -Inf
    mnpos, mxpos = NaN, NaN
    lookformax = True

    for i in arange(len(v)):
        this = v[i]
        if this > mx:
            mx = this
            mxpos = x[i]
        if this < mn:
            mn = this
            mnpos = x[i]

        if lookformax:
            if this < mx-delta:
                maxtab.append((mxpos, mx))
                mn = this
                mnpos = x[i]
                lookformax = False
        else:
            if this > mn+delta:
                mintab.append((mnpos, mn))
                mx = this
                mxpos = x[i]
                lookformax = True
    return array(maxtab), array(mintab)

series = [7,6,5,4,3,1,3,5,6,9,12,13,10,8,6,3,5,6,7,8,13,15,11,12,9,6,4,8,9,10,15,16,17,19,22,17,15,13,11,10,7,5,8,9,12]
x = np.linspace(0, 10, len(series))
maxtab, mintab = peakdet(series, .3, x)   # it is very important to give the correct x to `peakdet`
plt.plot(x, series, '-', color='black')   # use the same x for plotting
plt.scatter(maxtab[:,0], maxtab[:,1], color='blue') # the x-coordinates used in maxtab need to be the same as those in plot
plt.scatter(mintab[:,0], mintab[:,1], color='red')
plt.show()

This plots:


text:
Q: Why does a single loop cause a memory leak? I'm facing with a very strange behaviour.
With this dummy code:
 static void Main( string[] args )
    {
        int i = 0;

        while ( true )
        {
            i++;

            String giro = "iteration " + i;

            Console.WriteLine(giro);

            Thread.Sleep(40);
        }
    }

Using perfom the private bytes are increasing.
img http://dl.dropbox.com/u/2478017/memory.gif
How is it possible?
I thought GC takes care of these stuffs.
Moreover, if I compare memory behavior of this with a version in which i force GC collection every 10 iterations, the result is (for me) surprising:

The green process is the one with no GC.COllect(), and black one is the other.
Could you help me to understand the issue?
Thanks!

A: You're creating a bunch of strings. The GC hasn't seen fit to collect them yet. Eventually the memory graph will plateau. The GC works fine - there's no problems here :)

A: The GC doesn't tidy up memory straightaway. That would be very inefficient.

A: Use StringBuilder instead of String and see if that doesn't solve your issue.

A: There is no leakage. Remove the Thread.Sleep(40); and wait longer, GC should kick in after a while.

A: Try change this:
String giro = "iteration " + i;
Console.WriteLine(giro);

to
Console.WriteLine("iteration " + i);

A: If you need the garbage collector you can call it:
                        GC.Collect();
                        GC.WaitForPendingFinalizers();

...its very expensive though...

A: if you define to giro out of loop
it will solve your issue
 String giro;

  while ( true )
    {
        i++;

        giro = "iteration " + i;

        Console.WriteLine(giro);

        Thread.Sleep(40);
    }


text:
Q: Why do I need to run an application as a root for the PAPI library to work? I just upgraded to Ubuntu 16.04 LTS. In my C++ applications I use the PAPI library, so I installed it from http://icl.utk.edu/papi/. However for some reason I can not run my applications anymore without having to type sudo in the beginning.
Even just typing papi_avail on the terminal to see which counters are available I get this:
================================================================================
  PAPI Preset Events
================================================================================
    Name        Code    Avail Deriv Description (Note)
PAPI_L1_DCM  0x80000000  No    No   Level 1 data cache misses
PAPI_L1_ICM  0x80000001  No    No   Level 1 instruction cache misses
PAPI_L2_DCM  0x80000002  No    No   Level 2 data cache misses
PAPI_L2_ICM  0x80000003  No    No   Level 2 instruction cache misses
..........
    Of 108 possible events, 0 are available, of which 0 are derived.

avail.c                                     PASSED

If I run sudo papi_avail I get this:
--------------------------------------------------------------------------------
Of 108 possible events, 50 are available, of which 17 are derived.

avail.c                                     PASSED

What changed in Ubuntu 16.04?

A: It is related with the answer here. Theoretically, executing sudo sysctl -w kernel.perf_event_paranoid=0 should be enough.


text:
Q: How to use itertools to generate dictionaries of all permutations of a given dictionary I have the following dictionary:
test = OrderedDict({
        "one":1,
        "two":2,
        "three":3
})

And I wish to have the following result:
{'three':3, 'two':2, 'one':1}
{'three':3, 'one':1, 'two':2}
{'two':2, 'three', 'one':1}
{'two':2, 'one':1, 'three':3}
{'one':1, 'three':3, 'two':2}
{'one':1, 'two':2, 'three':3}

These are all the dictionaries that can be generated using permutations on the given test dict.
For now I can only get tuples of possible permutations using the following:
for perm in itertools.permutations(test):
    print(perm)

Will output:
('three', 'two', 'one')
('three', 'one', 'two')
('two', 'three', 'one')
('two', 'one', 'three')
('one', 'three', 'two')
('one', 'two', 'three')

How can I use itertools to get dictionaries with the key/values instead of tuples ?
EDIT:
Changed test to be an OrderedDict

A: Although dictionaries have no order you can obtain the permutations as tuple and turn those into OrderedDict:
>>> import itertools
>>> import collections
>>> for item in itertools.permutations(test.items()):
...     print collections.OrderedDict(item)
...
OrderedDict([('three', 3), ('two', 2), ('one', 1)])
OrderedDict([('three', 3), ('one', 1), ('two', 2)])
OrderedDict([('two', 2), ('three', 3), ('one', 1)])
OrderedDict([('two', 2), ('one', 1), ('three', 3)])
OrderedDict([('one', 1), ('three', 3), ('two', 2)])
OrderedDict([('one', 1), ('two', 2), ('three', 3)])


text:
Q: JBPM Workflow patch generation I have been using JBPM workflow in my project and I have a small question regarding generating the database patches or SQL statements to apply JBPM workflow modifications.
Currently JBPM workflow provides a way to refresh the JBPM tables in schema with the deployment of the latest process definitions. However what if my system is already live with process definition deployed with state X and now I have modified the process definition file to accommodate change X2. I still need to be able to deploy the delta changes without disrupting the instances of old saved data.
Is it possible to generate only "delta" database scripts for the JBPM process definition modification? And what are other good tools which can be used to modify process definitions more intuitively?
To reiterate on my problem, JBPM deploy cleans the JBPM tables of old instances maintained there and then redeploys the latest files; how do I generate the delta without deleting old data? Are there any user friendly tools for that?
Any help in this regard will be appreciated.

A: I'm not sure to have understood correctly your issue. JBpm doesn't clean tables for old process instances when you deploy a new process definition.
When you deploy a new process definition with the same name of an existing one, you get new version of that process definition.
Existing process instances continue running with the process definition version they was started with, while new process instances take the latest version unless you specify the precise version to be used.
In theory, process definition can also be modified for running process instances using the API. In doing so, you must pay attention to make these changes compatible with the flowing of these instances.


text:
Q: How to use a database value in manifest.json The project uses Symfony 4 and React.
In the project, there is two folders :

*

*api for Symfony

*client for React

So, there is two public directories. One into api and another one into client.
The entrypoint of application is the index.html in client/public. At this place I declare the manifest.json :
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="pragma" content="no-cache" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <link rel="apple-touch-icon" sizes="180x180" href="%PUBLIC_URL%/favicon.ico">

    <title>DFP</title>

      You need to enable JavaScript to run this app.

The application has a backoffice where we could define the logo. This logo is saved in api/public folder.
I would like to retrieve this logo for using it as icon. So using api/public (symfony) data from client (react) folder.
I tried to create a Symfony route but she's not accessible maybe because the application uses React route. I tried when data are persisted in database to create the file in client/public directory but not working too.
What could I do to achieve this ?
Thanks for help

A: Serve manifest.json with Symfony controller.
Add to routes.yaml file
manifest.json:
    path: /manifest.json
    controller: App\Controller\ManifestController::index

and create manifest controller, something like
<?php
namespace App\Controller;

use App\Entity\Config;
use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Component\HttpFoundation\JsonResponse;

class ManifestController
{

    private $doctrine;

    public function __construct(ManagerRegistry $doctrine)
    {
        $this->doctrine = $doctrine;
    }

    public function index(): JsonResponse
    {

        $bgColor = '#fff';
        $config = $this->doctrine->getManagerForClass(Config::class)
            ->getRepository(Config::class)
            ->findOneBy(['type' => 'background_color']);
        if ($config) {
            $bgColor = $config->getValue();
        }

        $manifest = [
            "name" => 'Example.com',
            "gcm_user_visible_only" => true,
            "short_name" => 'Example',
            "description" => 'Some example description',
            "start_url" => "/index.php",
            "display" => "standalone",
            "orientation" => "portrait",
            "background_color" => $bgColor,
            "theme_color" => "#f0f0f0",
            "icons" => [
                "src" => "logo-load.png",
                "sizes" => "96x96 128x128 144x144",
                "type" => "image/png"
            ],
            "src" => "logo-icon.png",
            "sizes" => "48x48 72x72",
            "type" => "image/png"
        ];

        return new JsonResponse($manifest);
    }
}


text:
Q: ProgressBar when program is running I'm trying to add to my program progress bar ,when it executes.Actualy I want to add something like this:
public class TestProgressBar extends javax.swing.JFrame {
   public  TestProgressBar Bar;
    public TestProgressBar() {
        initComponents();
        Bar=this;
    }
public void start(){
      //progress bar action
            SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                for(int i=0;i<100;i++){
                          jProgressBar1.setValue(jProgressBar1.getValue()+10);
                    try {
                    Thread.currentThread().sleep(100);
                      } catch (InterruptedException ex) {
                          Logger.getLogger(TestProgressBar.class.getName()).log(Level.SEVERE, null, ex);
                      }
            }
              }
              });
        //program running
   while(true);
}
    public static void main(String args[]) {
     TestProgressBar t=new TestProgressBar();
     t.setSize(320, 320);
     t.pack();
     t.setVisible(true);
     t.start();
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JProgressBar jProgressBar1;
    // End of variables declaration
}

but it doesn't work
I found code that implements what i want to do
Code
but for met it's messy
So the questrion is how to implement progress bar  which changes than program is working?
The progress bar value changes but form doesn't show these changes

A: You're calling Thread.sleep(...) on the Swing event thread which is putting your application to sleep. The while (true) may also be called on the event thread, but I'm not 100% sure on this.
Solution: don't step on the Swing event thread (or Event Dispatch Thread or EDT) but instead use a background thread for this. Please read Concurrency in Swing to see how to use a SwingWorker to help you create a background thread for this.


text:
Q: How to dynamic formating Enum label at runtime I created a custom Enum type for error handling with two variables code and label, and I would like the value of the label property of the enum to be formatted at runtime using like String.format(key, value)
`
public enum CustumErrorEnum{
    MISSING_VALUE1("CODE1","the label %s is missing"),
    WRONG_VALUE1("CODE2","the label %s is wrong");

    private String code;
    private String label;

    CustumErrorEnum(String code, String label){
        this.code = code;
        this.label = label;
    }

}

`
I am trying to customise log by specifying the raison and the value that throw the exception
e.g when user field a wrong for example, I need the output to be :
W001, The value 2026-13-13 is wrong

A: You can use String.format method.
public static String finalMsg(final CustumErrorEnum custumErrorEnum, Object... args) {
        final String formattedMsg = String.format(custumErrorEnum.label, args);
        return custumErrorEnum.code + "," + formattedMsg;
    }

Complete applicaiton is given below.
public class App {

    private static enum CustumErrorEnum {
        MISSING_VALUE1("CODE1", "the label %s is missing"), WRONG_VALUE1("CODE2", "the label %s is wrong");

        private String code;
        private String label;

        CustumErrorEnum(String code, String label) {
            this.code = code;
            this.label = label;
        }

    }

    public static String finalMsg(final CustumErrorEnum custumErrorEnum, Object... args) {
        final String formattedMsg = String.format(custumErrorEnum.label, args);
        return custumErrorEnum.code + "," + formattedMsg;
    }

    public static void main(String[] args) {
        System.out.println(finalMsg(CustumErrorEnum.MISSING_VALUE1, "city"));
    }

}

A: For adding Values inside a String you can do:
String error = "W001, The Value " + variable + " is wrong"

In combination with your enum, if you get a String than create a new one like
String error = yourString.subString(index1,index2) + variables + sourString.subString(index3, index4);


text:
Q: Calculate the value of $\frac{1}{2}+\frac{1}{4}+\frac{2}{8}+\frac{3}{16}+....+\frac{F_n}{2^n}+....$ The Fibonacci sequence starts with 1, 1, 2, 3, 5, 8, 13, ... .(Start from the 3rd term,
each term is the sum of the two previous terms). Let $F_n$ be the $n$th term of this sequence. $S$ is defined as $S=\frac{1}{2}+\frac{1}{4}+\frac{2}{8}+\frac{3}{16}+....+\frac{F_n}{2^n}+....$
Calculate the value of $S$
I have no idea how to solve this, hints aswell as solutions would be appreciated
Taken from the 2013 AITMO

A: Replace $F_n$ with $F_{n-1}+F_{n-2}$, now you have two series that are both similar to $S$

A: Hint: $$F_n{={\frac {\Phi ^{n}-\Psi ^{n}}{\sqrt {5}}}={\frac {1}{\sqrt {5}}}\left(\left({\frac {1+{\sqrt {5}}}{2}}\right)^{n}-\left({\frac {1-{\sqrt {5}}}{2}}\right)^{n}\right)}$$
$$S = \sum_{n=1}^{\infty}\dfrac{F_n}{2^n}=\dfrac{1}{\sqrt{5}}\sum_{n=1}^{\infty}\left[\left(\dfrac{\Phi}{2}\right)^n- \left(\dfrac{\Psi}{2}\right)^n\right]$$

A: Hint: if you know that the generating function for the Fibonacci sequence is:
$\displaystyle \sum_{n=0}^\infty F_nx^n = \frac{x}{1-x-x^2}$
then you can substitute $x=\frac 1 2$ and you immediately have
$\displaystyle \sum_{n=0}^\infty \frac{F_n}{2^n} = \frac{\frac 1 2}{1-\frac 1 2 -\frac 1 4} =2 $
So to answer questions like this quickly, you should learn about generating functions.

A: $$F_n=\frac{a^n-b^n}{\sqrt{5}},~ a+b=1, ~ab=-1,~ a,b=\frac{1\pm\sqrt{5}}{2}.$$
The required sim $$ s=\sum_{n=1}^{\infty} \frac{F_n}{2^n}= \frac{1}{\sqrt{5}} \sum_{n=1}^{\infty} \left ( \frac{a^n}{2^n}-\frac{b^n}{2^n} \right) =\frac{1}{\sqrt{5}}\left(\frac{a}{2-a}-\frac{b}{2-b}\right)= \frac{1}{\sqrt{5}}~\frac{2(a-b)}{4-2(a+b)+ab}=\frac{2 \sqrt{5}}{\sqrt{5}}=2.$$

A: To expand on the hint of @empy2:
$$\begin{array}{rlll}
  S(z) &= 1 + & 1z +& 2z^2 + 3z^3 + 5z^4 + ... \\\
z S(z) &=     & 1z +& 1z^2 + 2z^3 + 3z^4 + 5z^5 + ... \\\
S(z)-zS(z)-1 &=     && 1z^2 + 1z^3 + 2z^4 + 3z^5   \\\
\end{array} \\\
\begin{array}{rlll} \hline
S(z)-zS(z)-1 &= z^2 S(z) &\qquad & \phantom{sdfsdfsdfsdfs} \\\
S(z)(1-z-z^2)& =1 \\\
S(z) &= 1/(1-z-z^2)
\end{array}
$$
Now insert $1/2$ for $z$ and compute $1/2 S(1/2)$


text:
Q: Share a storyboard viewcontroller between multiple subclasses I have the same problem as Pedro here but not satisfied with the answer and since there is allready a bounty out and rewarded I created this question and I'll add a bounty as soon as possible.
I want to create or manipulate a segue (highlighted in yellow) in code such that the Master view is any one of a number of subclasses of MFMasterViewController (highlighted in red).

When doing this using Nibs I could create a Nib, SharedNib.xib & set
  the class as MFMasterViewController, then create my subclasses, say
  MFMasterViewControllerSubclassA, MFMasterViewControllerSubclassB
  etc. & then instantiate whichever subclass I wanted using...
MFMasterViewControllerSubclassA *controller = [[MFMasterViewControllerSubclassA alloc] initWithNibName:@"SharedNib" bundle:nil];

or...
MFMasterViewControllerSubclassB *controller = [[MFMasterViewControllerSubclassB alloc] initWithNibName:@"SharedNib" bundle:nil];

etc.
Any clues as to how I can get this right using storyboards?

I cannot use the provided answer on Pedro's question, my subclassing extends beyond the datasource & delegate.

A: You can just add unconnected view controllers to your storyboard and give them identifiers. Then in code you can do something like this in your navigation controller subclass:
MFMasterViewControllerSubclassA *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"SubclassA"];
self.viewControllers = @[controller];

This will change the navigation controller's root view controller to controller. If you want to animate the change, then you could use setViewControllers:animated: instead of that second line.

A: I know this is an old post, but I thought I'd respond since it hasn't been answered yet. This is not difficult to do. Wherever you wish to refer to your superclass simply refer to it by the appropriate subclass. The subclass contains everything the superclass does. There are a number of ways to do this depending how you wish to do your segues. If you're using prepareForSegue then do it like this:

*

*Create a segue from a button or whatever.

*Assign it an id

*Import your subclass into the .m file

*In prepareForSegue do the following.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
   {
      if ([segue.identifier isEqualToString:@"YourID"]) {
            SubclassA *subA = segue.destinationViewController; // the file's owner in the storyboard is set to the super class
            subA.someString = @"subclass A is setting this";
        }
   }

This is pretty limited since you are sharing a storyboard scene and there is no subclass of the scene. You would have to hide elements, for instance, and then unhide them if it were instantiated using a particular subclass. Another way to do this is to set a boolean on the one class depending on where you're segueing from and then write conditional code. This latter way might be regarded as a bit of a code smell, but it's better than duplicating storyboards which is probably a really bad idea.


text:
Q: How to parse from JSON to Unity GameObject I'm building a rudimentary app to store some basic character data.  I've gotten as far as storing all of the character data input as serialized data and persistently saved to a JSON file.
Now I'm stuck at trying to figure out how to get that data out of the JSON and into lists. (I figure from there I know how to instantiate new prefab objects populated with the data from the lists, so this is really where I'm stuck.)
My JSON data looks like this (if this helps with providing examples of what to do with it):
"Items": [
        {
            "characterName": "No Name Assigned",
            "chararacterCampaign": "No Campaign Assigned",
            "chararacterJob": "No job Assigned",
            "chararacterTown": "No town Assigned",
            "chararacterRace": "No race Assigned",
            "chararacterSkin": "No skin Assigned",
            "chararacterEyes": "No eyes Assigned",
            "chararacterHair": "No hair Assigned",
            "chararacterAge": "No age Assigned",
            "chararacterBuild": "No build Assigned",
            "chararacterPitch": "no value",
            "chararacterTexture": "no value",
            "chararacterNasality": "no value",
            "chararacterEnunciation": "no value",
            "chararacterTonalRange": "no value",
            "chararacterSpeed": "no value",
            "chararacterVolume": "no value",
            "chararacterAccent": "No accent Assigned"

I have code that is successfully reading the JSON on start, as it isn't overwriting the pre-existing data. The code I've written so far to parse the data looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class CharacterData
{
    public string cName;
    public string campaign;
    public string job;
    public string town;
    public string race;
    public string skin;
    public string eyes;
    public string hair;
    public string age;
    public string build;
    public string pitch;
    public string texture;
    public string nasality;
    public string enunciation;
    public string tonalRange;
    public string speed;
    public string volume;
    public string accent;

    public static CharacterData CreateFromJSON(string jsonString)
    {
        return JsonUtility.FromJson<CharacterData>(jsonString);
    }
}

Issue #1 that I'm running into is that I cannot seem to attach this script to anything, as it does not inherit from MonoBehavior, so right away, I think I need to address that, but I'm not sure how.
Issue #2, where I'm really stuck, is I can't really visualize how to parse that data from the string that will be produced into a format I can then do something with.
Any ideas?

A: You would need to create a class that is a type of MonoBehaviour and add that component on any object in the scene. Here is an example:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class JSONParser : MonoBehaviour
{
    public CharacterData data;
    void Start()
    {
        data = CharacterData.CreateFromJSON("your json string");
    }
}

enter image description here
enter image description here

A: You cannot deserialize classes inheriting UnityEngine.Object, like ScriptableObject, MonoBehaviour or GameObject. They can only be created by the engine (such as with Instantiate, or a specialized constructor).
Your approach is correct, to deserialize into a class that does not inherit anything. You can then attach that to a variable in another class that is a component. The idea of data-only classes is usually called the "model" or "data transfer object", for this case specifically.
class CharacterController : MonoBehaviour {
    private CharacterData _data;

    private void Awake() {
        _data = CharacterData.CreateFromJSON("your json data");

        // Do something with the data
    }
}


text:
Q: Where is the Artifactory OSS source code located? I can download the latest Artifactory OSS release (5.2.1), but I can't seem to find its source code.
The Artifactory documentation links to https://api.bintray.com/content/jfrog/artifactory/jfrog-artifactory-oss-$latest-sources.tar.gz;bt_package=jfrog-artifactory-oss-zip, but there's no source at that address.
Does anyone know what the real URL is, or if there's a public svn or git repo that I can clone?

A: Thanks for letting us know.
We have uploaded the sources of version 5.2.1 to Bintray.
feel free to download the file:
https://api.bintray.com/content/jfrog/artifactory/jfrog-artifactory-oss-$latest-sources.tar.gz;bt_package=jfrog-artifactory-oss-zip

A: For the 7.x releases you can find them here:
https://releases.jfrog.io/artifactory/bintray-artifactory/org/artifactory/oss/jfrog-artifactory-oss/7.10.2/


text:
Q: Including ManagedObjectModel in a Framework I am developing a framework for which I would like to include an NSManagedObjectModel with abstract entities that are designed to be subclassed in the application. Is it possible for an application to subclass entities in the NSManagedObjectModel in the framework?

A: Of course you can subclass classes from a framework. There is no reason why subclassing should not work.
If you want to extend the NSManagedObjectModel from the framework in the app it might get tricky, but it could work as well. You should try it out and ask a new question when you hit a more concrete roadblock.


text:
Q: How to subsample a dataframe based on individual ID's and time I have over 113,000 acoustic telemetry data points and I want to randomly subset one data point every hour for each unique animal ID. The thing is, not every animal ID will be present in every hour. Is there a way to subset my data in R even though not every animal ID is present in every hour?
Here is a snapshot of the data:
data_hour          transmitter_id            DATETIME
1 2021-10-15 19:00          64617 2021-10-15 19:06:11
2 2021-10-15 19:00          64599 2021-10-15 19:07:08
3 2021-10-15 19:00          64599 2021-10-15 19:12:10
4 2021-10-15 19:00          64621 2021-10-15 19:16:29
5 2021-10-15 19:00          64599 2021-10-15 19:20:09
6 2021-10-15 19:00          64599 2021-10-15 19:21:47
....
35 2021-10-15 19:00         64621 2021-10-15 19:58:09
36 2021-10-15 19:00         64617 2021-10-15 19:58:44
37 2021-10-15 19:00         64599 2021-10-15 19:59:41
38 2021-10-15 20:00         64599 2021-10-15 20:02:16
39 2021-10-15 20:00         64599 2021-10-15 20:04:20
40 2021-10-15 20:00         64617 2021-10-15 20:04:29
41 2021-10-15 20:00         64621 2021-10-15 20:05:15
42 2021-10-15 20:00         64617 2021-10-15 20:07:01
43 2021-10-15 20:00         64599 2021-10-15 20:07:25
44 2021-10-15 20:00         64603 2021-10-15 20:09:11

...etc.

Thank you very much for any help/suggestions, R newbie!

A: Update thanks to @Arthur: See comments:
library(dplyr)
df %>%
  group_by(data_hour, transmitter_id) %>%
  slice_sample(n=1)

 data_hour        transmitter_id DATETIME
  <chr>                     <int> <chr>
1 2021-10-15 19:00          64599 2021-10-15 19:21:47
2 2021-10-15 19:00          64617 2021-10-15 19:06:11
3 2021-10-15 19:00          64621 2021-10-15 19:58:09
4 2021-10-15 20:00          64599 2021-10-15 20:07:25
5 2021-10-15 20:00          64603 2021-10-15 20:09:11
6 2021-10-15 20:00          64617 2021-10-15 20:07:01
7 2021-10-15 20:00          64621 2021-10-15 20:05:15

We could group and use slice_sample():
library(dplyr)
df %>%
  group_by(data_hour) %>%
  slice_sample(n=1)

  data_hour        transmitter_id DATETIME
  <chr>                     <int> <chr>
1 2021-10-15 19:00          64617 2021-10-15 19:06:11
2 2021-10-15 20:00          64599 2021-10-15 20:04:20


text:
Q: Select all checboxes after selecting the first one I have a few checkboxes, and I want all the others to be checked as well, after selecting the first one. Why is this code not working correctly?
var del = document.querySelectorAll('input[name="del_id[]"]');

del.forEach(function(elem){
   elem.addEventListener('input',function(){
      if(del[0].checked){
         elem.checked = true;
      }
   });
});


text:
Q: How to get matched aggregations based on SWICHID calculate the avarage time in Node.js I am working on sample application in react in that I am using aggregations, I implemented a query matching SWITCHID field and STATUS to get all data where status is LIGHTS ON .How to get the difference between average time based on RECEIVEDDATE and CREATE_DATE fields.
db.lights.aggregate([   {"$match":{"STATUS":"LIGHTS ON"}},   {"$sort":{"RECEIVEDDATE":1,"CREATE_DATE":1}},   {"$group":{     "_id":"$SWITCHID",     "LIGHTONALLTIME":{"$push":"$$ROOT"}   }},{$out:"bhavana"} ])
my fields:
            "_id" : "Z5-W52-53A/8.",
            "LIGHTONALLTIME" : [
                {
                    "_id" : ObjectId("5a8bab026c44f9d64085a2eb"),
                    "SWITCHID" : "Z5-W52-53A/8.",
                    "TOTALSTREETLIGHTS" : 22,
                    "WORKINGSTREETLIGHTS" : 22,
                    "CUMULATIVEKWH" : 260.79,
                    "STATUS" : "LIGHTS ON",
                    "LATITUDE" : 17.6755,
                    "LONGITUDE" : 83.1965,
                    "RECEIVEDDATE" : "2010-01-10-13.44.16.719000",
                    "OFFICE_ID" : "200-96",
                    "FLAG2" : "K",
                    "CREATE_DATE" : "2018-02-09-03.04.03.621000"
                },
                {
                    "_id" : ObjectId("5a8bab026c44f9d64085a2e6"),
                    "SWITCHID" : "Z5-W52-53A/8.",
                    "TOTALSTREETLIGHTS" : 22,
                    "WORKINGSTREETLIGHTS" : 22,
                    "CUMULATIVEKWH" : 260.79,
                    "STATUS" : "LIGHTS ON",
                    "LATITUDE" : 17.6755,
                    "LONGITUDE" : 83.1965,
                    "RECEIVEDDATE" : "2018-01-10-13.44.16.719000",
                    "OFFICE_ID" : "200-96",
                    "FLAG2" : "K",
                    "CREATE_DATE" : "2018-02-09-00.04.06.952000"
                },
        "_id" : "Z4-W40-SS451A/4",
            "LIGHTONALLTIME" : [
                {
                    "_id" : ObjectId("5a8bab026c44f9d64085a2be"),
                    "SWITCHID" : "Z4-W40-SS451A/4",
                    "TOTALSTREETLIGHTS" : 22,
                    "WORKINGSTREETLIGHTS" : 22,
                    "CUMULATIVEKWH" : 257.39,
                    "STATUS" : "LIGHTS ON",
                    "LATITUDE" : 17.7429,
                    "LONGITUDE" : 83.2542,
                    "RECEIVEDDATE" : "2018-02-09-00.12.17.494000",
                    "OFFICE_ID" : "200-84",
                    "FLAG2" : "K",
                    "CREATE_DATE" : "2018-02-09-00.04.06.952000"
                },
                {
                    "_id" : ObjectId("5a8bab026c44f9d64085a2c6"),
                    "SWITCHID" : "Z4-W40-SS451A/4",
                    "TOTALSTREETLIGHTS" : 22,
                    "WORKINGSTREETLIGHTS" : 22,
                    "CUMULATIVEKWH" : 257.7,
                    "STATUS" : "LIGHTS ON",
                    "LATITUDE" : 17.7429,
                    "LONGITUDE" : 83.2542,
                    "RECEIVEDDATE" : "2018-02-09-04.25.35.232000",
                    "OFFICE_ID" : "200-84",
                    "FLAG2" : "K",
                    "CREATE_DATE" : "2018-02-09-04.04.05.591000"
                },`enter code here`


text:
Q: Inverse Mellin transform of products of gamma functions I want to calculate the inverse Mellin transform  of products  of 3 gamma functions.
$$F\left ( s \right )=\frac{1}{2i\pi}\int \Gamma(s)\Gamma (2s+a)\Gamma( 2s+b)x^{-s}ds$$
Above contour integral has 3 poles.
$$s_{1}=-n$$
$$s_{2}=-\left ( \frac{n+a}{2} \right )$$
$$s_{3}=-\left ( \frac{n+b}{2} \right )$$
Which pole is used in contour integral?
$$F\left ( s \right )=\sum_{n=0}^{\infty }\frac{\left ( -1 \right )^{n}}{n!}\Gamma \left ( a-2n \right )\Gamma \left ( -2n+b \right )x^{n}+\sum_{n=0}^{\infty}\frac{\left ( -1 \right )^{n}}{n!}\Gamma \left ( -\frac{n}{2}-\frac{a}{2} \right)\Gamma \left ( -n-a+b\right )x^{\frac{n}{2}+\frac{a}{2}}+\sum_{n=0}^{\infty}\frac{(-1)^{n}}{n!}\Gamma \left (-\frac{n}{2}-\frac{b}{2} \right )\Gamma (-n-b+a)x^{\frac{n}{2}+\frac{b}{2}}$$
Is this correct??


text:
Q: Why use yup validation? There is a validation method provided by the react hook form. Nevertheless, some developers sometimes use yup validation. What I thought about seems to have the advantage of using schema validation together in the frontend and backend.
I wonder if there is anything else out of this.

A: I'm using zod as an external validation instead of yup ...

schema validation together in the frontend and backend.

Another big advantage is ...

*

*Since the schema can be defined independently, unit testing can be done easily.

*Since the schema can be defined independently, it is easy to understand as a validation definition.

*Can handle complex validation
Complex validation is, for example, "when the validation of field A depends on the state of other fields B".
With zod, you can create complex validations across other fields, such as with refine superRefine.

*

*https://github.com/colinhacks/zod#refine

*https://github.com/colinhacks/zod#superrefine


text:
Q: Meteor materialize:materialize sass error Can some please tell why am i getting this error when trying to use the materialize:materialize package . I have node-sass installed. And kola is also install on my machine.
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Users\\alexi\\AppData\\Local\\.meteor\\packages\\meteor-tool\\1.4.1_1\\mt-os.windows.x86_32\\dev_bundle\\bin\\node.exe"
"C:\\Users\\alexi\\AppData\\Local\\.meteor\\packages\\meteor-tool\\1.4.1_1\\mt-os.windows.x86_32\\dev_bundle\\lib\\node_modules\\npm\\bin\\npm-cli.js"
"rebuild" "--no-bin-links" "--update-binary"
npm ERR! node v4.5.0
npm ERR! npm  v3.10.6
npm ERR! code ELIFECYCLE
npm ERR! node-sass@3.2.0 postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@3.2.0 postinstall script 'node scripts/build.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the node-sass package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node scripts/build.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs node-sass
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls node-sass
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!
C:\Users\alexi\AppData\Local\.meteor\packages\fourseven_scss\3.2.0\plugin.compileScss.os.windows.x86_32\npm\node_modules\meteor\compileScss\compileScss\node_modules\.temp-cwxlp8\npm-debug.log

A: You are using npm modules so, You can create one with npm init. Make sure to define a "start" script inside it too before running npm start.
OR
installed "windows-build-tools"
meteor update
meteor update --all-packages
meteor add materialize:materialize

A: Try adding fourseven:scss first
meteor add fourseven:scss

than
 meteor add materialize:materialize

Worked for me.


text:
Q: Multidimensional slicing array Python I want to "select" specific rows and columns of a 2D-np.array and don't know how to do this efficiently.
import numpy as np

array = np.random.rand(4*100,4*360)

lon_min = np.array([-72.5, -72.5, -70, -67.5, -65, -62.5, -60, -57.5, -55, -52.5, -50])
lon_max = lon_min + 2.5
lat_min = np.array([-10, -7.5, -5, -4, -3, -3, -2, -1, -1, -1, -1])
lat_max = lat_min + 2.5
indices_lon_min = (180+lon_min)*4
indices_lat_min = (50-lat_min)*4
indices_lon_max = indices_lon_min + 4*2.5
indices_lat_max = indices_lat_min -4*2.5

> indices_lat_min = [240. 230. 220. 216. 212. 212. 208. 204. 204. 204. 204.]
> indices_lat_max = [230. 220. 210. 206. 202. 202. 198. 194. 194. 194. 194.]
> indices_lon_min = [430. 430. 440. 450. 460. 470. 480. 490. 500. 510. 520.]
> indices_lon_max = [440. 440. 450. 460. 470. 480. 490. 500. 510. 520. 530.]

I hoped there is something like:
array[indices_lat_min.astype(int): indices_lat_max.astype(int), indices_lon_min.astype(int):indices_lon_max.astype(int)]

Basically I want to achieve
array[240:230, 430:440]

but with multiple "slices".

A: Maybe something like this:
array[list(map(range, indices_lat_min.astype(int), indices_lat_max.astype(int))),
      list(map(range, indices_lon_min.astype(int), indices_lon_max.astype(int)))]

This is basically your idea, I just used map to get all the min max pairs in the index lists.
For a descending range:
array[list(map(range, indices_lat_min.astype(int), indices_lat_max.astype(int), np.full(indices_lat_max.size, -1))),
      list(map(range, indices_lon_min.astype(int), indices_lon_max.astype(int),))]


text:
Q: Admob with Surfaceview crashes I want to add Admob Banner ad with SurfaceView but it gives NullPointerException,
Here is code:
private AdView mAdView;
private LinearLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ll = new LinearLayout(this);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
ll.addView(mAdView);
ll.addView(new GamePanel(this));
setContentView(ll);
}

GamePanel is a class that extends SurfaceView and implements SurfaceHolder
Error says:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)' on a null object reference
                                                                               at com.example.binnat.zigzag.MainActivity.onCreate(MainActivity.java:54)

line 52: mAdView.loadAd(adRequest);

A: You don't have that view in your layout yet so find the Adview in your LinerLayout.
mAdView = (AdView) ll.findViewById(R.id.adView);

Edit:
You can also move your setContentView call just to after you've created your LinearLayout:
ll = new LinearLayout(this);
setContentView(ll);


text:
Q: Choosing alternating numbers There are 3000 cards, each labeled with an integer, 1 to 3000.
Alex chooses 2000 different cards. Bob then tries
to find from these 2000 cards, 1000 cards whose odd or evenness alternates when they are placed in increasing order. If Bob is able to complete his objective, he wins, otherwise, Alex wins.
Who is assured of winning, given they play wisely?

A: Bob.
Group the numbers like $\{1,2\},\{3,4\},\cdots$
Alex chooses $2000$ different cards, i.e. he abandoned $1000$ of them.
For each group, if one card is abandoned, Bob should abandon the other too.
At last Bob abandon some 'whole group's arbitrarily.
$500$ groups are remained and Bob's objective is completed.


text:
Q: How to find the home press button in android L Hi in my code I'm trying to catch the home Button click in android i'm using this code for capture the home button click
public boolean isApplicationSentToBackgroundAbove(final Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
        }
    }
    return false;
}

on onPause() function i'm calling this
 if (isApplicationSentToBackground(this)){
    Log.i("Activitymain","Home is press");
    }

This function work fine below 5 OS. (Sony 4.4.2 also does not work) rest of the OS is working
how to solve this issue


text:
Q: Why am I getting different outputs in different compilers with JavaScript dates? I have created below program in which I tried to compare date and time. but it is giving different answers in different compilers.
In tutorials point compiler it is working as expected :
tutorialspoint
But, In repl.it compiler it is giving me wrong output : repl.it
Why this problem is happening?
let todayDate = () => {
    var today = new Date();
    var dateAndTime = today.toLocaleString('en-GB', { timeZone: 'Asia/Kolkata' })
    var fulldate = dateAndTime.split(",")[0].split("/")
    var dd = fulldate[0]
    var mm = fulldate[1]
    var yyyy = fulldate[2]

    return yyyy + '/' + mm + '/' + dd;
}

let currentTime = () => {
    var today = new Date();
    var dateAndTime = today.toLocaleString('en-GB', { timeZone: 'Asia/Kolkata' })
    var time = dateAndTime.split(",")[1].split(":")
    var hh = time[0].replace(/^\s+|\s+$/gm,'');
    var mm = time[1]
    var ss = time[2]

    return Date.parse(`${todayDate()} ${hh}:${mm}:${ss}`);

}

if (currentTime() > Date.parse(`${todayDate()} 18:00:00`) && currentTime() <  Date.parse(`${todayDate()} 22:52:58`)){
console.log('Welcome')
}
else{
  console.log('Comeback Later')
}

console.log(currentTime())
console.log(todayDate())


text:
Q: TV show where something living in a well filled containers with gold and jewels? It was a show in the 80s or early 90s.  The episode I remember was about a man and his daughter who found a well or a hole in the ground.  They would send a bucket down and something would fill it with gold and jewels.  The guy wanted to know what was down there so he went down, something ate him, and when the girl pulled him up his suit was full of jewels.

A: This is a likely duplicate of Short horror/SF story where a farmer contacts an underground kingdom while digging a well?.
From my previous answer:
This is almost certainly a television episode of Amazing Stories from the mid-1980s. The title was Thanksgiving, and starred David Carradine.
I can only find an excerpt on YouTube, despite watching the full episode there not a month ago:

Wikipedia lists those with teleplay credits, but does not say whether it was based on an earlier short story.
Managed to find the author of the original short story: Harold Rolseth.
The short is named Hey You Down There! Here is a link of dubious legality:
http://julie-cfahs.wikispaces.com/file/view/Hey+You+Down+There


text:
Q: Submitting Opportunity For Approval With Apex I've followed instructions here to submit records into an approval process. This seems to be running fine without errors, and my debug logs have confirmed the submission has occured:
16:50:09:101 USER_DEBUG [13]|DEBUG|@@@o.Id: 006m0000005TZs1AAG
16:50:09:101 USER_DEBUG [14]|DEBUG|@@@processName: VP_Approval_Final
16:50:11:677 USER_DEBUG [25]|DEBUG|@@@result.isSuccess: true
16:50:11:677 USER_DEBUG [26]|DEBUG|@@@result.getInstanceStatus: Pending

However, upon navigation to this records page, I'd expect to see the record inserted into an approval flow with approval process history. Instead, I see nothing. What am I doing wrong? The code I'm using is nearly an exact copy/paste of the above link.
 private static void runApproval(Opportunity o){

        // Create an approval request for the account
        Approval.ProcessSubmitRequest req1 =
            new Approval.ProcessSubmitRequest();
        req1.setObjectId(o.Id);

        // Submit on behalf of a specific submitter
        req1.setSubmitterId(UserInfo.getUserId());

        System.debug('@@@o.Id: ' + o.Id);
        System.debug('@@@processName: ' + o.Migration_ProcessName__c);
        // Submit the record to specific process and skip the criteria evaluation
        req1.setProcessDefinitionNameOrId(o.Migration_ProcessName__c);
        req1.setSkipEntryCriteria(true);

        // Submit the approval request
        Approval.ProcessResult result = Approval.process(req1);

        // Verify the result
        System.assert(result.isSuccess());

        System.debug('@@@result.isSuccess: ' + result.isSuccess());
        System.debug('@@@result.getInstanceStatus: ' + result.getInstanceStatus());

        System.assertEquals(
            'Pending', result.getInstanceStatus(),
            'Instance Status'+result.getInstanceStatus());

            if(o.Migration_Approve__c){
            // Approve the submitted request
            // First, get the ID of the newly created item
            List<Id> newWorkItemIds = result.getNewWorkitemIds();

            // Instantiate the new ProcessWorkitemRequest object and populate it
            Approval.ProcessWorkitemRequest req2 =
                new Approval.ProcessWorkitemRequest();
            req2.setComments('Approving request.');
            req2.setAction('Approve');
            req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});

            // Use the ID from the newly created item to specify the item to be worked
            req2.setWorkitemId(newWorkItemIds.get(0));

            // Submit the request for approval
            Approval.ProcessResult result2 =  Approval.process(req2);

            // Verify the results
            System.assert(result2.isSuccess(), 'Result Status:'+result2.isSuccess());

            System.assertEquals(
                'Approved', result2.getInstanceStatus(),
                'Instance Status'+result2.getInstanceStatus());
            }
    }

A:
The code I'm using is an exact copy/paste of the above link

The reason you do not see anything in the database via the UI when you look at an opportunity is because the code:

*

*Creates a random account and attempts to submit it, not an opportunity in your org

*I doubt you have a user with the alias 'someStandardUser'

*You probably do not have a process named 'PTO_Request_Process'

Since the code has asserts it is weird that is is not throwing errors because of #2 and #3. But lets say you have them, since there is no error is comes back to number #1

A: I believe I have identified the problem.
I was running the approval process on a list of opportunities, and while some of them seemed to be working, the anonymous apex I was running to do this task failed once it hit certain opportunities that didn't have a defined 'manager'. This seemed to stop the process altogether, even though my asserts and debugs claimed otherwise. This is my inexperience talking - I guess if a bit of anonymous apex fails, can you not trust the logs / asserts of anything previous?
I simply adjusted my SOQL statement to only pull opportunities that have defined managers, and now everything is working as expected.


text:
Q: Rails 3, cucumber "unknown attribute" Starting out a tiny app with my first time using Cucumber 1.1.4 and it's erroring out with an "unknown attribute" error, it appears. I'd like to ensure a record exists, or created if not. I've made sure the show page exists with the erb calls and the record exists, just to be sure.
Here's my feature:

Scenario: normal
      Given an opening exists called "jobid", objective: "Work here", grizzard: "My experience", skills: "My skills"
      When I go to the path "/openings/jobname"
      Then I should see "Sam Walton"
      Then I should see "Work here"
      Then I should see "My experience"
      Then I should see "My skills"

Here's my step file:
Given /^an opening exists called "([^"]*)", objective: "([^"]*)", bob: "([^"]*)", skills: "([^"]*)"$/ do
    |opening_name, objective_text, bob_text, skills_text|

    Opening.create!(name: opening_name, objective: objective_text, skills: skills_text, grizzard: bob_text)
end

When /^I go to the path "([^"]*)"$/ do |path|
    visit(path)
end

Then /^I should see "([^"]*)"$/ do |text|
    page.should have_content(text)
end

Here's my error:

# features/visitor_can_view_an_opening.feature:6
      Given an opening exists called "jobid", objective: "Work here", grizzard: "My experience", skills: "My skills" #
  features/step_definitions/general_steps.rb:5
        unknown attribute: skills (ActiveRecord::UnknownAttributeError)
       ./features/step_definitions/general_steps.rb:6:in /^an opening exists called "([^"]*)", objective: "([^"]*)", bob: "([^"]*)", skills:
  "([^"]*)"$/
       features/visitor_can_view_an_opening.feature:7:in Given an opening exists called "jobid", objective: "Work here", bob: "My
  experience", skills: "My skills"

I've looked over the skills: and it looks like the others, so my inexperience is in the way and would appreciate someone pointing out what I'm not understanding, sam

A: Hmm, you may need to update your test environment database. Run

 rake db:test:prepare

It should work.
HTH.


text:
Q: Regx Validation won't Work in Google Chrome Android app , But Works on Chrome Browser - PC I'am using the following Regex Validation in order enter alpha only (Text Only values) to the text field.
The regex validation works in pc environment, but hosted and access through an Android device through chrome app, the validation doesn't work (Users can enter symbols as well as numbers).  Appreciate your valuable help.
The Method I tried
<input type="text" id="name1"   placeholder="Name" class="form-control" />

$('#name1').bind('keypress', alphaOnly);

function alphaOnly(event) {
    var value = String.fromCharCode(event.which);
    var pattern = new RegExp(/[a-zA-Z]/i);
    return pattern.test(value);
 }

A: You've just missed anchors:
var pattern = /^[a-zA-Z]+$/i;

A: Try this for mobile devices:

$('#name1').bind('keyup', alphaOnly);

function alphaOnly() {
    console.log(this.value);
    this.value = this.value.replace(/[^a-z]/gi,'');
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="name1"   placeholder="Name" class="form-control" />

Got idea from this answer


text:
Q: Jeditable not processing id I am having some hard time trying to update my database after changing the text, in return I receive the following database error: Unknown column '' in 'field list'.
the content of the element id work, but the element id doesn't seems to be retrieved.
the element id is also the name of my field in the database
database fields name:
id| _career| _location| _education
62|IT      | London   | BSc Computer science

index.php file

<?php echo $user_data['firstname'], " ", $user_data['lastname']; ?>

<?php echo $user_data['_career'] ?>

<?php echo $user_data['_location'] ?>

<?php echo $user_data['_education'] ?>

datacenter.php
$(document).ready(function() {
  $('.edit').editable('./datacenter.php', {
    indicator: 'Saving...',
    tooltip: 'Click to edit...'
  });
  $('._career').editable('./datacenter.php', {
    id: 'id',
    name: 'data',
    cancel: 'Cancel',
    submit: 'OK',
    indicator: '',
    tooltip: 'Click to edit...'
  });
  $('._location').editable('./datacenter.php', {
    id: 'id',
    name: 'data',
    cancel: 'Cancel',
    submit: 'OK',
    indicator: '',
    tooltip: 'Click to edit...'
  });
  $('._education').editable('./datacenter.php', {
    id: 'id',
    name: 'data',
    cancel: 'Cancel',
    submit: 'OK',
    indicator: '',
    tooltip: 'Click to edit...'
  });

});

edit.php file
<?php

require 'core/init.php';

if (logged_in() == true && user_details_check($user_data['id'], "firstname", "noname") == true || logged_in() == false) {
  header("Location:./");
}

$f = $_POST['id'];
$value = $_POST['data'];
$user_id = trim($user_data['id']);

mysqli_query($con, "UPDATE users SET `$f` = '$value' WHERE `id` = '$user_id'") or die(mysqli_error($con));

/* sleep for a while so we can see the indicator in demo */
usleep(2000);

$renderer = $_GET['renderer'] ? $_GET['renderer'] : $_POST['renderer'];
if ('textile' == $renderer) {
  require_once './Textile.php';
  $t = new Textile();
  /* What is echoed back will be shown in webpage after editing. */
  print $t->TextileThis(stripslashes($_POST['user_edited_content']));
} else {
  /* What is echoed back will be shown in webpage after editing. */
  print $_POST['data'];
}

I have been stuck on this for days, Really hope someone could please help me figure this out

A: The element id wasnt working, so I switch to element class.
Before:

<?php echo $user_data['firstname'], " ",

Now:

<?php echo $user_data['firstname'], " ",

datacenter.php
Before:
$(document).ready(function() {
  $('#edit').editable('./datacenter.php', {
    indicator: 'Saving...',
    tooltip: 'Click to edit...'
  });

Now:
$(document).ready(function() {
  $('.edit').editable('./datacenter.php', {
    indicator: 'Saving...',
    tooltip: 'Click to edit...'
  });


text:
Q: Servlet security authentication How to make security authentication for a web application that is using servlets and .jsp.
I want to make authentication using tomcat.
Can anyone explain steps I need to take in servlet and jsp for FORM authentication.
Servlet is taking care of .jsp page that needs to be secured.

A: Refer to the Tomcat Realm Configuration.

A: You can also see Chapter 32 of the J2EE Tutorial - though that will deal with generic configuration of a servlet based web app.

A: If you want to use container managed security, see the other answers.
If you're implementing the security layers in your webapp itself (which can be more flexible IME and definitely more traditional for simple apps) you'll need some sort of framework that integrates with whatever you're using to build the app.
I'm using spring-security myself. It might be a bit overkill for what you're doing, but you can have it work completely orthogonal to your app, i.e. just define some URLs that are protected and redirect users to a form when they try to access something and then if they login successfully let them get on their way. Make sure to stick to namespace-based config if your needs aren't too complex. Beans-based is a bit of a slog if you're not actively using spring. All the information you' need for that is in chapter 2.


text:
Q: Handling Popup with Togglebutton I have a Toggle button and a popup in Xaml. popup's IsOpen bound to toggle button's IsChecked and the Popup's StaysOpen is set to false. So the popup will get open when the toggle button checked and close if unchecked. This works fine.
My problem is i have opened the popup and click away from popup, this close my popup due to its stays open false and if i tried to open the popup by clicking the toggle button, popup not get open. Since it is in checked state, and its turn into unchecked state. so its not open the popup.
Any idea, How may i handle this?

A: Set StaysOpen = "True" or even better StaysOpen="{Binding ElementName=TogglePopupButton,Path=IsMouseOver}".
With the second approach you get 2 benefits.
1) The PopUp closes if the user clicks outside the popUpview.
The PopUp Closes if you click on the ToggleButton again.

A: Handle popups Closed/Opened events and on there toggle CheckBox states, and vice versa. I've had similiar problems myself with Popup.


text:
Q: I was trying to implement facebook integration using facebook-passport, I got an error I was trying to implement facebook integration, I got this error:

XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%3A%2F%2Fchefin.com%2Fauth%2Ffacebook%2Fcallback&client_id=865410220269534. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://chefin.com' is therefore not allowed access.

when I call auth/facebook URL on button click.
$scope.facebookLogin = function() {

        $http({
            url: '/auth/facebook',
            method: 'GET',
        }).success(function(response) {
        });
    };

A: It seems the /auth/facebook is having a redirect request. So instead of AJAX can you try:
$scope.facebookLogin = function() {
    window.location.href = "/auth/facebook";
}


text:
Q: Linux Script Ftp I have to make a script that uploads ONLY [ABC][0-100].txt files ('A' or 'B' or 'C' followed by a number and .txt extension) from the directory current at the URL ftp://host/files/, authenticating with the user admin and password 12345.
I already write some lines but doesn`t working for me:
Script code is:
#!/bin/bash

HOST="host"
USER="admin"
PASSWORD="12345"

DESTINATION=upload

ALL_FILES="A{0..100}.txt B{0..100}.txt C{0..100}.txt"

ftp -inv $HOST <<EOF
user $USER $PASSWORD
cd $DESTINATION
mput $ALL_FILES
bye
EOF

can u help me grep only file with specified name

A: With bash version >= 3.1 I suggest to replace
ALL_FILES="A{0..100}.txt B{0..100}.txt C{0..100}.txt"

with
printf -v ALL_FILES "%s " A{0..100}.txt B{0..100}.txt C{0..100}.txt

to allow bash to expand the expression.
I can't tell you if there are any other problems in your code. I recommend to write all self-defined variable names in lower case.


text:
Q: Trying to parse a commandline argument into two separate commands in C for a project I'm writing, there's a section where I must break a command line argument into two so that I can run them separately using execvp. I'm stuck as to how to do this, so far what I'm trying to do is pass a command like argument like so:
$testprogram /bin/ls , /bin/cat

and then break it at the comma so that I can pass /bin/ls and /bin/cat into a generic execvp function separately.
I've tried using a for loop for this with an if statement to ignore the comma but it's not working out so well.
Any ideas?

A: Just give arguments without comma, with blank spaces like
$testprogram /bin/ls  /bin/cat
now,
argv[0]=testprogram
argv[1]=/bin/ls
argv[2]=/bin/cat


text:
Q: How to add a workbook sheet into another workbook Here is the excel "db" and excel "scrape".

And I want to achieve like this, add the sheet "scrap" into excel "db", i.e. four sheets in the same excel (scrap, ai, bd, and eb).

A: Copying sheets from one workbook to another is not hard to be solved. You will only need a Excel Application Scope and a Copy Sheet activity:

So all you need is the file path where the source Excel is. And the destination Excel file path. And the name of the sheet.


text:
Q: Best way to deal "locally" with exceptions thrown in object constructor I have been thinking for some time now about this question, but I have not found an answer online satisfactory enough, yet. So here I am.
Assumptions
For the sake of clarity let us restrict ourselves to C++11 and a custom object. By custom object, I mean a user-defined class that the developer has full control of. All the code snippets below are not meant to be compilable or even syntactically correct. They just illustrate a concept.
Boundary conditions
Our object has a nontrivial constructor that can throw exceptions if an error is encountered. When constructing this object I would like to catch and deal with the exceptions as close as possible to the object creation point, to make the code more readable and catching only the constructor exceptions and nothing else.
Example 1
This example is not ideal because this is exactly what I am trying to avoid: dealing with constructor exceptions far away from the constructor.
class MyClass {
public:
  MyClass() {
    throw 1;
  }
}

int main() {

  try {

    MyClass my_obj;

    try {
      // Do something with my_obj that may throw
    } catch (...) {
      // deal with exceptions
    }

  } catch(...) {
    // deal with constructor exceptions
  }
}

Example 2
Here I use a std::unique_ptr to separate the object declaration and initialization. The downside is that I now create the object on the heap instead of the stack even if I have no strong reason to do that.
class MyClass {
public:
  MyClass() {
    throw 1;
  }
}

int main() {

  std::unique_ptr<MyClass> my_obj_ptr;

  try {
    my_obj_ptr = boost::make_unique<MyClass>();
  } catch (...) {
    // deal with constructor exceptions
  }

  // continue to use my_obj
}

Example 3
Modify the object internal state and check that.
class MyClass {
private:
  good_internal_state;

public:
  MyClass() : good_internal_state(true) {
    try {
      throw 1;
    } catch(...) {
       good_internal_state = false;
    }
  }

  bool IsInternalStateGood() {
    return good_internal_state;
  }
}

int main() {

  MyClass my_obj;
  if (!my_obj.IsInternalStateGood()) {
    // Do something
  }

  // continue to use my_obj
}

Right now I am leaning towards the Example 2 case but I would like to know what is the most syntactically correct way to accomplish what I want.

A: I wouldn't say any of those versions is more or less correct (except for some typos). Example 2 looked like the one I would use. Here scoping seems to be the largest problem. The variable needs to declared outside of the try but must be initialized inside. If you don't like to use the heap std::optional could be usefull:
int main() {

  std::optional<MyClass> maybeMyClass;

  try {
    maybeMyClass.emplace(/*constructor parameters*/);
  } catch (...) {
    // deal with constructor exceptions
  }

  // continue to use my_obj
  maybeMyClass->foo();
}

Allthough the syntax could imply otherwise, the value managed by std::optional is allocated as the footprint of this std::optional (on the stack in this case).

You could also use a factory function createMyClass that would return a std::optional, this would require MyClass to have a move constructor, which shouldn't be to expensive.


text:
Q: how to use 'set' on object properties when the property type has a 'set' of it's own? If '_position' is a Point object member of Sprite, with Number members x and y, and its own get/set definitions, how can I apply a higher level 'set' so this will work (EDIT: I would like to reach the 'set' function in Sprite, rather than the 'set' function in Point):
// EDIT: example calling line, embedding context should be unimportant
// 'this' is a Sprite instance
this.position.set(x, y);

Object.defineProperties(Sprite.prototype, {

// a bunch of other properties excised here

    position: {
        get: function() {
            return this._position;
        },

        set: function(_pos) {
            this._position.x = this.transform.x = _pos.x;
            this._position.y = this.transform.y = _pos.y;
            this.transform.updateTransform();
        }
    }
};

What happens currently is that "this.position" goes to the "position.get" property, and then "this.position.set" goes through to the Point set function.  It seems like attempts to 'set' any object with it's own get/set will drop down to the lowest level.
It feels like there must be a way to change this behaviour, but my google and stackoverflow searches are not coming up with an answer.  It's likely there's a proper term for what I want to do here, without which I'm struggling the phrase the question correctly.
For instance:
this is close, but doesn't quite work in my situation
EDIT: I don't control the source file for Point, or the function where the this.position.set(x,y); is held.  Although I may be able to get permission for a  change to the calling syntax if I can prove that it won't break the other objects which actually want to use the Point set function.

A: Since Bergi didn't post an answer, I will, since this is a good question.
If you don't control any of the surrounding code then, unfortunately, there are only ugly ways to do it.
A) Return a proxy object that will do whatever you want, as Bergi suggested.
The downside is that the surrounding code may be expecting the object it sent to match the object received. It's not inconceivable that the developer would compare object references instead of values, and then such a comparison would fail. But that would happen in your code already, so if you're using it already and nothing breaks you're good to go.
Also, if you go this way, you should make MyPoint.prototype = new Point() or something so that if new methods are added to Point, they will be available in your class as well.
B) Override this._position.set and/or setters and getters manually for each object in the constructor or wherever you set it. This is slow and extremely dirty and is an idea so bad that I wrote a snippet and then deleted it :)
Here are some options on what you should actually do.
A) Agree with the user of Sprite to use sprite.position = newPos or sprite.setPosition(newPos). Then you should return a Object.freeze()d copy of _position in the getter to make sure it's not used inappropriately.
B) Agree with the author of Point to emit some event when it's changed which could then be listened on by Sprite

A: You don't understand Object.defineProperties. Don't feel bad, neither did I until I researched it further. You are confusing the set method of an individual property of the Object with a property called set which could really have it's own set method. The value of your property is where you can create a method, if you like. I'm guessing this is what you need to see:
Object.defineProperties(Sprite.prototype, {
  set: {
    // can also have get and set here
    value: function(){
      // inside Sprite.prototype.set
    }
  },
  position: {
    get: function() {
      return this._position;
    },
    set: function(_pos) {
      this._position.x = this.transform.x = _pos.x;
      this._position.y = this.transform.y = _pos.y;
      this.transform.updateTransform();
    }
  }
});

I think it's cool. This kind of thing must have been used behind the scene so length properties are really methods.


text:
Q: question on quadratic equations. Let $p, q , r$ be distinct real nos such that
$ap^2 + bp + c = (\sin(\theta))p^2 +(\cos(\theta))p$
similarly we get a total of three equations if we replace $q$ and $r$ in place of p.
where $a, b, c$ belongs to $\Bbb{R}$
Question is find the max value of:
$(a^2 + b^2)/a^2+ 3ab +5b^2$

A: Let's write the three equations:
$$\begin{align}
ap^2 + bp + c &=& (\sin(\theta))p^2 +(\cos(\theta))p \\
aq^2 + bq + c &=& (\sin(\theta))q^2 +(\cos(\theta))q \\
ar^2 + br + c &=&(\sin(\theta))r^2 +(\cos(\theta))r\end{align}$$
Now we have to keep in mind that $a,b,c,\theta$ are variables and $p,q,r$ are constants and we need to find the max value of $\frac{a^2+b^2}{a^2+3ab+5b^2}$.
first we can eliminate $c$ by subtractions of the three equations, and as $p,q,r$ are distinct we can simplify by $p-q\neq 0$ and $q-r\neq 0$ to obtain:
$$\begin{align}
a(p+q) + b &=& (\sin(\theta))(p+q) +(\cos(\theta)) \\
a(q+r) + b &=& (\sin(\theta))(q+r) +(\cos(\theta)) \end{align}$$
and hence one can see that $a(p-r)=\sin(\theta) (p-r)$ and again we know that $p-r\neq 0$ hence $a=\sin(\theta)$ and $b=\cos(\theta)$ now it remains to find the max value of:
$$\frac{a^2+b^2}{a^2+3ab+5b^2}=\frac{1}{1+3\cos(\theta)\sin(\theta)+4\cos(\theta)^2} $$
and we can write the denominator as $$1+3\cos(\theta)\sin(\theta)+4\cos(\theta)^2=\frac{1}{2}(3\sin(2\theta)+4\cos(2\theta)+6) =\frac{1}{2}(5 \sin(2\theta+\alpha)+6)$$
where $\alpha=\arctan(\frac{3}{4})$.
Finally the maximum value of the given expression is $2$ and the minimum value is $\frac{2}{11}$.
Comment
The fact that $a=\sin(\theta)$ and $b=\cos(\theta)$ can be justified by the follwing argument. Let $P(x)=(a-\sin(\theta))x^2+(b-\cos(\theta))x+c$, we observe that  $P$ is a polynomial of degree less that $2$ which have more than $3$ roots (p,q,r) hence $P=0$ and from here we have $a-\sin(\theta)=0$ and $b-\cos(\theta)=0$.


text:
Q: Difference between list(dict) and dict.keys()? Say I have a dict:
foo = {'a': 1}

Both list(foo) and foo.keys() return the same thing. What's the difference between the two?

A: Python3:
from the official documentation

Calling foo.keys() will return a dictionary view object. It supports
  operations like membership test and iteration, but its contents are
  not independent of the original dictionary – it is only a view.

in fact,
type(foo.keys())

gives
<class 'dict_keys'>

whereas in Python 2 both
type(list(foo))
type(foo.keys())

give
<type 'list'>

A: There's no real difference in python 2, which is why I suspect dict.keys changed to return a view in python3 and dict.viewkeys was removed.
In python 3:
In [3]: foo = dict((k,k) for k in range(4))

In [4]: foo
Out[4]: {0: 0, 1: 1, 2: 2, 3: 3}

In [5]: foo.keys?
Type:        builtin_function_or_method
String form: <built-in method keys of dict object at 0x7f45d8667708>
Docstring:   D.keys() -> a set-like object providing a view on D's keys

In [6]: foo.keys()
Out[6]: dict_keys([0, 1, 2, 3])

In [7]: type(foo.keys())
Out[7]: dict_keys

In [8]: for i in foo.keys():
   ...:     del foo[i]
   ...:
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-8-659d5446ab29> in <module>()
----> 1 for i in foo.keys():
      2     del foo[i]
      3

RuntimeError: dictionary changed size during iteration

In [9]: for i in list(foo):
    del foo[i]

In [10]: foo
Out[10]: {}

The last two things are basically the thing you need to know about the difference between dict.keys and list(dictionary) in python3. dict.keys is just a view of the keys, so checking item in dictionary.keys() is O(1), but you can't iterate over dictionary.keys() and modify the dictionary at the same time.
They are both iterators, in that they both implement __iter__.

A: One difference is in Python 3. foo.keys() returns an iterator of the keys, which is what foo.iterkeys() does in Python 2, while list(foo) returns a list of the keys.
As noted below, foo.keys() doesn't exactly return an iterator in Python 3. It returns a dict_keys object (or view) which, among its operations, allows iteration. You can also do fun things such as set operations and multiple iteration. It still has the concept of lazy evaluation which makes iterators so powerful.

A: In Python 3, the dict_keys object returned by .keys() is just pointing to the actual dictionary keys (and changes when the dictionary is changed), while the list command creates a copy of the keys.
Therefore, the dict_keys is more lightweight and faster. The list should be used when modifying the dictionary while iterating over its keys. A slightly nonsensical example with dictionary foo:
>>> for kw in foo.keys():
...   foo.pop(kw)

leads to RuntimeError: dictionary changed size during iteration, while the following works:
>>> for kw in list(foo):
...   foo.pop(kw)

A:       'duration': [120.0, 240.0, 90.0, 16.0, 48.0],
      'rate': [0.11, 0.06, 0.08, 0.14, 0.07],
      'down_payment': [100000.0, 0.0, 8900.0, 0.0, 4300.0]} ```

data.keys()

dict_keys(['amount', 'duration', 'rate', 'down_payment'])

dict.keys produce a dictkeys. that we can only read . not can do change


text:
Q: laravel is commenting out my view doctype For reasons I don't understand, Laravel seems to be commenting out the doctype tag at the top of my view file:
<!--?php<!DOCTYPE html-->
<html lang="en">

This is causing the browser to incorrectly render the page.
The view file looks like so:
<!DOCTYPE html>
<html lang="{{ App::getLocale() }}">

There is no whitespace above the doctype.
I have confirmed the problem in Safari and Chrome.
Anyone have any ideas?

A: Fixed the problem, for anyone interested.
I had a blank api.php file and it caused problems. Adding a comment fixed it.


text:
Q: mongoDB issue(or not) when using $lte and $gte with the same value the query doesn't return any value Let me give you an example:
mongos> db.test.insert( { a: 0.1, b: 1, c : 0.01 } )
mongos> db.test.insert( { a: 0.2, b: 2, c : 0.02 } )
mongos> db.test.insert( { a: 0.3, b: 3, c : 0.03 } )
mongos> db.test.find()
{ "_id" : ObjectId("5225e072dd144e45bf406d42"), "a" : 0.1, "b" : 1, "c" : 0.01 }
{ "_id" : ObjectId("5225e07add144e45bf406d43"), "a" : 0.2, "b" : 2, "c" : 0.02 }
{ "_id" : ObjectId("5225e082dd144e45bf406d44"), "a" : 0.3, "b" : 3, "c" : 0.03 }
mongos> db.listings.find({a: { $gte: 0.2, $lte: 0.2 } } );
mongos> db.listings.count({a: { $gte: 0.2, $lte: 0.2 } } );
0

As you can see, even if the document exists in the collection, the query doesn't return any result. I know that this is wierd to use range search for a simple equal, but in my opinion this should work and return the expected document.
Thank you for your answer.
Forgot to mention the mongoDB verison is 2.4.4-pre-.

A: Problem is you inserted data into test collection but perform query on listings collection. If you query test collection everything works as expected:
> db.test.insert( { a: 0.1, b: 1, c : 0.01 } )
> db.test.insert( { a: 0.2, b: 2, c : 0.02 } )
> db.test.insert( { a: 0.3, b: 3, c : 0.03 } )

> db.test.count({a: { $gte: 0.2, $lte: 0.2 } } )
1
> db.test.find({a: { $gte: 0.2, $lte: 0.2 } } );
{ "_id" : ObjectId("5225ecd155feffaf74591328"), "a" : 0.2, "b" : 2, "c" : 0.02 }


text:
Q: What algorithm should I use to optimize a bike sharing redistribution system? I want to optimize a bike-sharing redistribution system( find the best way for an agent to take bikes from a station that has more bikes than needed and relocate them to a station that needs more bikes) and I don't know what technologies to use.
I have details about the path cost and the demand for each station.
I would like to have multiple solutions and compare them.
Thanks!