text:
Q: Code that starts with a variable named "hello" gets dropped Someone posted a question that started with a code sample, and the sample began by assigning a variable named hello. The input filtering removed that line. I tried to do the same thing in my reply and not only did it consistently remove the line it wrecked the format of the rest of the code sample.
If anyone knows the proper tags to add to this question, please do so.

A: Fixed it by adding an empty comment block before your code. The problem is that we have a filter set in place that automatically removes "Hello", "Thanks", etc. lines from the post when you save.
As others have said in the comments though, you should add an explanation of the code.


text:
Q: Autoboxing a character value and then returning a blank value I have this piece of code  that generates a random characters (ASCII)
public char getRandChar(){ return (char)rand.nextInt(27); }

and then I'll print it out using this
System.out.println(new Character(getRandChar()));

How but apparently it is returning a blank value

A: This is because rand.nextInt(27); is returning unprintable character codes. This will be evident if you change your code to return (char)65; for example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lagrange inversion theorem and Legendre polynomials generating function I have been trying to solve the following problem (taken from Spiegel's Complex variables, problem 6.105).
By considering the equation $z=a+w\frac{(z^2-1)}{2}$, show that
$$\frac{1}{\sqrt{1-2aw+w^2}}=1+\sum_{n=1}^{\infty} \frac{w^n}{2^n n!}\frac{d^{n}}{da^{n}}[(a^2-1)^n]$$
I managed to come up with two tries.

Attempt 1:
Starting with the equation $z=a+w\frac{(z^2-1)}{2}$ we can write $w=2\frac{z-a}{z^2-1}$, so we have:
$$\frac{1}{\sqrt{1-2aw+w^2}}=\frac{1}{\sqrt{1-2a(2\frac{z-a}{z^2-1})+(2\frac{z-a}{z^2-1})^2}}=\underbrace{\dots}_\text{some algebra later}=\pm \frac{z^2-1}{z^2-2az+1}=\widetilde{F}(z)$$
We want to apply this $\widetilde{F}(z)$ function to the Lagrange's inversion formula (6.11):

Being $F(z)$ the root of the equation $F(z)=a+wf(z)$, then:
$$F(z)=F(a)+\sum_{n=1}^{\infty} \frac{w^n}{n!}\frac{d^{n-1}}{da^{n-1}}[F'(a)f^n(a)]$$

Then we want to make $\widetilde{F}(a)=1$, so we choose the negative branch of $\widetilde{F}(z)$, so this way
$$\widetilde{F}(a)=\left.-\frac{z^2-1}{z^2-2az+1}\right|_{z=a}=-\frac{a^2-1}{a^2-2a^2+1}=\frac{1-a^2}{1-a^2}=1$$
So, let $F(z)=\frac{1-z^2}{z^2-2az+1}$, then we have $F(a)=1$, and:
$$F'(a)=\frac{d}{dz}F(z)|_{z=a}=\frac{d}{dz}(\frac{1-z^2}{z^2-2az+1})|_{z=a}=\dots=\frac{2a}{a^2-1}$$
while $f(z)=\frac{z^2-1}{2}$. So putting this in Lagrange's formula, we come up with:
$$F(z)=1+\sum_{n=1}^{\infty} \frac{w^n}{n!}\frac{d^{n-1}}{da^{n-1}}[\frac{2a}{a^2-1}(\frac{a^2-1}{2})^n]$$
$$F(z)=1+\sum_{n=1}^{\infty} \frac{w^n}{2^n n!}\frac{d^{n-1}}{da^{n-1}}[\frac{2a}{a^2-1}(a^2-1)^n]$$
$$F(z)=1+\sum_{n=1}^{\infty} \frac{w^n}{2^n n!}\frac{d^{n-1}}{da^{n-1}}[2a(a^2-1)^{n-1}]$$
$$F(z)=1+\sum_{n=1}^{\infty} \frac{w^n}{2^n n!}\frac{d^{n-1}}{da^{n-1}}[\frac{1}{n}\frac{d}{da}(a^2-1)^{n}]$$
$$F(z)=1+\sum_{n=1}^{\infty} \frac{w^n}{2^n n! \color{red}{n}}\frac{d^{n}}{da^{n}}[(a^2-1)^{n}]$$
Therefore:
$$\frac{1}{\sqrt{1-2aw+w^2}}=1+\sum_{n=1}^{\infty} \frac{w^n}{2^n n! \color{red}{n}}\frac{d^{n}}{da^{n}}[(a^2-1)^{n}]$$
which doesn't match with what we wanted to show.

Attempt 2:
After searching for more similar problems, I found Lunt's book (A collection of problems on complex analysis), specifically problem 985, that states:

Let $z=z(w)$ be a single-valued function, defined for sufficiently small $|w|$ by the equation $z-a-wf(z)=0$, the function $f(z)$ analytic at the point $z=a$ and $f(a)\neq 0$.Prove that for every function $\Phi(z)$ analytic at the point $z =a$, for sufficiently small $|w|$ there holds the expansion:
$$\frac{\Phi(z)}{1-wf'(z)}=\Phi(a)+\sum_{n=1}^{\infty} \frac{w^n}{n!}\frac{d^{n}}{da^{n}}[\Phi(a)f^n(a)]$$

Proven this, taking $f(z)=\frac{z^2-1}{2}$ and $z-a-wf(z)=0$ as in attempt 1, and $\Phi(z)=1$ we have:
$$\frac{1}{1-wf'(z)}=\frac{1}{1-(2\frac{z-a}{z^2-1})(z)}=\dots=\frac{1-z^2}{z^2-2az+1}=F(z)$$
and then, the result is immediate:
$$\frac{\Phi(z)}{1-wf'(z)}=\Phi(a)+\sum_{n=1}^{\infty} \frac{w^n}{n!}\frac{d^{n}}{da^{n}}[\Phi(a)f^n(a)]$$
$$F(z)=1+\sum_{n=1}^{\infty} \frac{w^n}{n!}\frac{d^{n}}{da^{n}}[1(\frac{a^2-1}{2})^n]$$
$$\therefore \frac{1}{\sqrt{1-2aw+w^2}}=1+\sum_{n=1}^{\infty} \frac{w^n}{2^n n!}\frac{d^{n}}{da^{n}}[(a^2-1)^n]$$

The Question
I think the 2nd attempt answers the problem but for me it doesn't 'feel correct' in some sense (don't know why). I believe that it should be possible to get the correct answer from attempt 1 but I cannot figure out how.
Actually, Lunt's problem 986 states that starting from problem 985 we can prove that
$$\Phi(z)=\Phi(a)+\sum_{n=1}^{\infty} \frac{w^n}{n!}\frac{d^{n-1}}{da^{n-1}}[\Phi'(a)f^n(a)]$$
if we apply 985 result to the function $\Phi(z)[1-wf'(z)]$. But I have not been able to solve it yet (only assuming that $f'(a)=0$ but it doesn't seems right to do without proving). So maybe this one is the real question here. Any insight, suggestion or further references on this kind of problems will be appreciated.
I haven't found more of this topic related to complex analysis (is it obsolete for some reason?), only in combinatorics and it doesn't seem to be related (?!) to what I'm looking for.
Sorry for the long post ☺.

A: Starting with $$z = a + \frac{1}{2} w (z^2 -1) \tag{1}$$
and applying Lagrange's expansion, we have
$$z = a + \sum_{n=1}^{\infty} \frac{w^n}{2^n n!} \frac{d^{n-1}}{da^{n-1}} (a^2-1)^n \tag{2}$$
On the other hand, $(1)$ is also a quadratic equation which we can solve for $z$, with result
$$z = \frac{1 \pm \sqrt{1-2aw+w^2}}{w}$$
We choose the negative sign in order that $\lim_{w \to 0} z = a$, so
$$z = \frac{1 - \sqrt{1-2aw+w^2}}{w}$$
Differentiating with respect to $a$,
$$\frac{dz}{da} = \frac{1}{\sqrt{1-2aw+w^2}} \tag{3}$$
Also differentiating $(2)$, we have
$$\frac{dz}{da} = 1 + \sum_{n=1}^{\infty} \frac{w^n}{2^n n!} \frac{d^{n}}{da^{n}} (a^2-1)^n \tag{4}$$
Equating $(3)$ and $(4)$,
$$\frac{1}{\sqrt{1-2aw+w^2}} = 1 + \sum_{n=1}^{\infty} \frac{w^n}{2^n n!} \frac{d^{n}}{da^{n}} (a^2-1)^n$$


text:
Q: Run a fetch call onLoad - React I am new to React.
I am trying to run a fetch call to get some data when my react page loads. I am not sure I am calling the event correctly though.
Here is how I am calling it:
export default function GetRecipe(props) {
  let { name } = useParams()
  const [searchQuery, setSearchQuery] = useState('')
  const [recipeName, setRecipeName] = useState('')
  const [methodStepsList, setMethodStepsList] = useState([])
  const [ingredients, setIngredients] = useState([])

  const retrieveRecipe = function (e) {
    console.log('getting recipe')
    e.preventDefault()
    console.log(searchQuery.length)
    let queryString
    if (searchQuery.length) {
      queryString = `http://localhost:3001/getbasicrecipe/?name=${searchQuery}`
    } else {
      queryString = `http://localhost:3001/getbasicrecipe/?name=${name}`
    }
    fetch(queryString, {
      method: 'GET',
      headers: { 'Content-type': 'application/json' },
    })
      .then((resp) => resp.json())
      .then((json) => {
        console.log(json)
        let result = json
        let recipeName = result[0].recipe_name
        let recipeMethod = result[0].recipe_method.split(/\r?\n/)
        console.log(recipeMethod)
        setRecipeName(recipeName)
        setMethodStepsList(recipeMethod)
        setIngredients(json)
      })
  }

  return (

        <form className="recipe-form">
          [...]

        </form>

  )

I read about componentDidMount() but could not figure out how to include it in my code.
Thanks!

A: If you are using a class component then, as you mentioned you can use the componentDidMount() lifecycle method like this:
componentDidMount() {
    // Runs after the first render() lifecycle
    retrieveRecipe();
}
...
render(){
...
}

Docs: https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class
However if you are using a function component you should use instead the useEffect hook like this:
useEffect(() => {
   retrieveRecipe();
}, []); // by using an empty array as dependency this useEffect will act as the componentDidMount function
...
return (
...
)

Docs: https://reactjs.org/docs/hooks-effect.html

A: If you are using Class based component
componentDidMount(){
 //Your code here
}
render(){
return ...
}

If using function component
useEffet(()=>{
   //your code here
}, [])

return (...)

A: this is a classic case of using useEffect hook -
as in before the return function use -
useEffect(()=>{ retrieveRecipe(); },[]);
it comes instead of componentDidMount
I recommend to play a bit with react.js tutorial to get the hang of it before creating your own projects.

A:     import React, {  useEffect } from "react";

    function YourComponent() {

      useEffect(() => {
      retrieveRecipie(e).then((res)=>{
       console.log(res);
  }
)
      }, []);

      return (

      );
    }

    export default YourComponent;

mak you retrieveRecipie function
const retrieveRecipie= (yourParams) => {
  return fetch(
    `URL from where you are fetching data`,
    {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-type": "application/json",
      },
body: JSON.stringify(yourParams),
    }
  )
    .then((response) => {
      return response.json();
    })
    .catch((err) => {
      console.log(err);
    });
};

A: As you are using Functional Component of React JS, you don't need to handle the component lifecycle method manually. For functional component, there is useEffect hook which will handle the lifecycle of the component.
import React, { useEffect } from 'react';

export default function GetRecipe(props) {
    useEffect(() => {
        retrieveRecipe();
    },[]);

    return <></>;
}

The above code will call the retrieveRecipe function only once after rendering this component.


text:
Q: Having trouble loading image with webpack file-loader I'm currently working on a project using React and webpack, but I'm new to both. I need to display an image from the server's filesystem. I'm attempting to use webpack's file-loader to display the image, but I'm having trouble getting it to work.
Edit:
I've made a couple changes due to some suggestions and I'm having a slightly different problem than my original problem. After switching from requiring the image to importing the image, I now get a correct file path,
"images/7047aa4de98575625fc771ca68618c28.png". I now have my webpack file-loader outputing to that directory, and I do have an image called images/7047aa4de98575625fc771ca68618c28.png on my filesystem, but I get a 404 NOT FOUND response when I attempt to display the image.
My webpack config is here:
var path = require('path');

module.exports = {
    entry: './src/main/js/app.js',
    devtool: 'sourcemaps',
    cache: true,
    mode: 'development',
    output: {
        path: __dirname,
        filename: './src/main/resources/static/built/bundle.js'
    },
    module: {
        rules: [
            {
              test: /\.(jpg|png|svg)$/i,
              loader: 'file-loader',
              options: {
                outputPath: 'images',
              }
            },
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                use: [{
                    loader: 'babel-loader',
                    options: {
                        presets: ["@babel/preset-env", "@babel/preset-react"]
                    }
                }]
            }
        ]
    }
};

And the relevant part of my code attempting to get the image is here:
// const catImage = require('./data/images/cat.png');
import catImage from './data/images/cat.png';

const root = '/api';

class App extends React.Component {
  render() {
    return (
      <BrowserRouter>

          <Switch>
            <Route path="/" component={Upload} exact />
            <Route path="/share/:key" component={Share} />
            <Route path="/test" component={Test} />
            <Route component={Error}/>
          </Switch>

      </BrowserRouter>
    )
  }
}

class Test extends React.Component {
  render() {
    const gat = catImage;

    return (

    )
  }
}

A: Switching to url-loader instead of file-loader made it work. I do not know why file-loader did not work. Oh well.
var path = require('path');

module.exports = {
    entry: './src/main/js/app.js',
    devtool: 'sourcemaps',
    cache: true,
    mode: 'development',
    output: {
        path: __dirname,
        filename: './src/main/resources/static/built/bundle.js'
    },
    module: {
        rules: [
            {
              test: /\.(jpg|png|svg)$/i,
              loader: 'url-loader',
              options: {
                outputPath: 'images',
              }
            },
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                use: [{
                    loader: 'babel-loader',
                    options: {
                        presets: ["@babel/preset-env", "@babel/preset-react"]
                    }
                }]
            }
        ]
    }
};

Make sure you use either
import image from './path/to/image.png';

OR
const image = require('./path/to/image.png');
const imageSrc = image.default;

You can also do:
const imagePath = require.context('./path/to/imageDirectory', true);
const imageSrc = imagePath('./image.png', true);


text:
Q: Can Excel do basic time calculation on custom time format? I have log from a tool in this format: hh:mm:ss.uuu.
For example: 10:12:34.323
Setting these cells in Excel 2003 to time format with syntax hh:mm:ss.000 is accepted, but any operation, like add/subtract, yelds to #Value! error.
Is there any way for Excel to do calculation on already set custom and recognized time format, without extra effort?

Update with screenshots:

A: I'd expect calculations like
=A1+B1
to work OK - even if your data  is text formatted - the addition should "co-erce" to a valid time value - perhaps you have extra characters in the data? What do you get with
=LEN(A1)
where A1 contains one of your time values - it should be 12

A: You should check that the formats were actually applied to the cells.  In your screenshot you have double quotes around your values so they appear to just be strings.  If they were being properly interpreted I believe you would see something like 0.43836... for the dates instead of "10:31:16.465" in the formula evaluation window.


text:
Q: Using generic as parameter in constructor Kotlin I m using two constructor with different input types one as string and other as generic. The problem is while using Kotlin its only using the string constructor and ignores the generic
class DataResponse<T> {
    var isSuccess: Boolean = false
        private set
    var errorMessage: String? = null
    var data: T? = null

    constructor(success: Boolean, data: T) {
        this.isSuccess = success
        this.data = data
    }

    constructor(success: Boolean, errorMessage: String) {
        this.isSuccess = success
        this.errorMessage = errorMessage
    }
}

usage
    if (apiResponse.code() == 200) {
                    Observable.just(DataResponse<List<ResultDTO>>(true,
 apiResponse.body()?.resultList)) ---> **(error on this line forcing to convert it to string)**
                } else {
                    Observable.just(DataResponse(false, "Something went wrong"))
                }

A: You can give named parameters in kotlin. That is if more than two constructors or functions with same name exists, we can explicitly specify the parameter as named one. Here I suggest to explicity mention the parameter data.
    if (apiResponse.code() == 200) {
        Observable.just(DataResponse<List<ResultDTO>>(true,data=
        apiResponse.body()?.resultList))
    } else {
        Observable.just(DataResponse(false, "Something went wrong"))
    }

A: Currently your DataResponse class represents two different things. One is an error message and the other one is actual data in case of success. isSuccess is redundant too because it is always true when data is non-null and always false if errorMessage is non-null.
I would change the design in the following way:
sealed class DataResponse

class SuccessResponse<T>(val data: T?)

class ErrorResponse(val errorMessage: String)

Now you have two separate classes, both having the same supertype DataResponse. This way you will always know what you are dealing with.
Usage:
when(dataResponse) {
    is SuccessResponse -> TODO("deal with data")
    is ErrorResponse -> TODO("deal with error")
}


text:
Q: Mounting and modifying a loopback file without sudo/root, is it possible? I'm trying to adapt a tutorial into an easy to use script
http://qt-project.org/wiki/RaspberryPi_Beginners_guide.
I'm trying to reduce the need for sudo/root as much as possible (preferably, only for the final dd step).
My questions are:

*

*Can I mount the ext4 file system without sudo/root privileges in any way?

*Can I mount it in a way so that users/groups on the FS are ignored
in some way (so I can run make install without sudo)?
The Filesystem is currently mounted loopback from an offset of a file (i.e. -o loop,offset=62914560).
This file is the image that will be copied onto the SD card used to boot the Raspberry Pi.

A: If your system uses udisks (and polkit allows udisks to mount for non-root users), you can mount the file with:
udisksctl loop-setup -f file.img -o <OFFSET>

<OFFSET> is an integer value to represent the number of bytes at which to start the loopback mount. You can use the -r switch if you want to mount read only.

A: Concerning this one the following comes into my mind.
You can add a line to your /etc/fstab for the device you want to mount as a user with normal privileges.
An example line would look like
/dev/mydevice    /mnt/directory    auto    rw,user    0    0

With this line a normal user can mount mydevice to /mnt/directory and additionally can read from- and write to the device. You only have to invoke
mount mydevice

or
mount /mnt/directory

For an excellent explanation of the syntax of/etc/fstab you should look at

www.tuxfiles.org/linuxhelp/fstab.html

Since the raspberry is an usb device you can achieve this more elegantly with udev by adding a specific udev-rule (auto-mounting etc.). In this case let me now if you want to have a further explanation.

A: You need superuser privileges to be able to mount. But those could be given to you by setuid helper  commands like sudo, mount or fusermount. In /etc/fstab, and admin can grant some mere users to mount specific FS. Some users can be allowed to mount filesystems via fuse (for instance, if the FS is ext, you may be able to use  fuseext.
Or maybe you can do without mounting, by using applications that can write inside a filesystem. For instance, debugfs can write to a ext fs image (create dirs, files, change ownership...), debugfs can be scripted easily You can also use qemu to run a Linux kernel and associated commands to write to that FS.

A: You want libguestfs.  You can use it via guestfish or guestmount, or use the library directly through its C interface or any of the many language bindings, like Python.


text:
Q: Exception raised during rendering: java.lang.System.arraycopy([CI[CII)V Exception details are logged in Window > Show View > Error Log I can't find any other android API in the project. it is showing only API 20 Android 4.4W. how do i overcome from it?

A: Within the eclipse you can change the API version of the design layout. This worked for me.

A: The issue is because you are using the API level 20 for wearable devices. You need to download other sdk through the Android SDK Manager.
In Eclipse, open windows->android sdk manager->select Android 4.4.2 and check Android sdk and ARM system image and click install packages
Now you have the API level 19 source code so eclipse will now be able to render the views
Now go to the graphical layout tab of the layout and change the android version from 20 to 19.

A: In Android Studio you just need to change your graphical layout API from 4.4w to 4.4.2 as in the picture below.

A: If you using Android Studio
1 Open your Build.gradle
2 change values as you need
like this

android {
      compileSdkVersion 17
      buildToolsVersion '19.1.0'
defaultConfig {
    applicationId "com.example.xxx.xxxx"
    minSdkVersion 16
    targetSdkVersion 17
    versionCode 1
    versionName "1.0"
}

3 press Sync Project with gradle file..
4 if you do not have that API it will ask you to download..
  rebuild the project..


text: Q: QGIS: use graph builder to classify multiple images at once I am classifying subsets (Sentinel 1, Sentinel 2, NDVI, and Landsat 8 data) in order to see which image as the highest accruacy. These classifications are taking several days for each of the images. Is it possible to use QGIS graph builder to classify the images simultaneously?


text:
Q: Save an image to a mobile phone gallery from a browser So this seems unlikely purely from a security point of view, but I need to cover my bases. Has anyone come across a method for saving an image in a browser to the user's gallery? In this case, I'm specifically talking about from site served javascript (not phonegap).
While I know you can tap and hold on the image to save, I'd love a button for our less technically inclined users.
The phone ecosystem is diverse, so any phone would work for me. I'm just curious if it's possible.
Some attempts:
Works on desktop, links through on phone (Android)

Hangs when clicked (Android)
save image to user's disk using javascript

A: How about:
function save(){
    document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}

function gotFS(fileSystem) {
    fileSystem.root.getFile("pic.jpg", {create: true, exclusive: false}, gotFileEntry, fail);
}

function gotFileEntry(fileEntry) {
    fileEntry.createWriter(gotFileWriter, fail);
}

function gotFileWriter(writer) {

    var photo = document.getElementById("image");
    writer.write(photo.value);

}

function fail(error) {
    console.log(error.code);
}


text:
Q: Reverse of Chinese Remainder Theorem For the following:
$(102n-51) \not\equiv 2 \pmod {2,3,5,7,11,13,...,\sqrt{102n-51}}$
(That's probably completely incorrect use of symbols, but I mean not equivalent to 2 mod any prime less than $\sqrt{102n-51}$)
here are my questions:

*

*What is the first (smallest) $n$ solution?

*Are there infinitely many $n$ solutions?

*(Most importantly) Is there a way we'd know (be able to prove) there must exist an $n$ solution where $n$ is less than a certain value?

If anything here is unclear, please ask. Also, please feel free to suggest edits to the question (or title) that might make this make more sense, or add pertaining tags. I'm having a hard time classifying this question and even expressing it clearly, but feel it has a lot of value.
EDIT: Thanks for the answers! I still have yet to receive an answer to question 3, of which I had the most interest. As well, I'd like to take things a step further. How about $102n-51$ simultaneously
$\not\equiv 2 \pmod {2,3,5,7,11,13,...,\sqrt{102n-51}}$
and
$\not\equiv 4 \pmod {2,3,5,7,11,13,...,\sqrt{102n-51}}$

A: HINT:
$$(102n - 51) \not\equiv 2 \pmod p$$
For every prime $0<p<\sqrt{102n-51}$. This means that $102n-53$ has no prime factors smaller than  $\sqrt{120n-51}$. It also means that $102n-53$ has no prime factors greater than: $$\dfrac{102n-53}{\sqrt{102n-51}}$$which for larger $n$ basically means that $\lceil\sqrt{102n-51}{}\rceil$ is both prime and the only prime factor of $102n-53$

A: Number $n$ is prime iff it's not divisible by any prime $p \leq \sqrt{n}$.
In your case you are looking for $102n-53$ not being divisible by any prime $p \leq \sqrt{102n-51}$. We can reduce it to $p \leq \sqrt{102n-53} < \sqrt{102n-51}$.
E.g. $n=2$ gives $151$ which is prime.
And yes, there are infinitely many such primes, you can re-write $102n-53=102(n-1)+49$ and apply Dirichlet's theorem on arithmetic progressions because $102$ and $49$ are coprime.
And I believe you can apply Prime number theorem for arithmetic progressions to estimate $n$.


text:
Q: Вывод массива в обратном порядке function yearsBirthDayList() {
 var data = new Array();

 for(i = 1905; i < 1998; i++) {
  data.push([i, i]);
 }

 return data;
}

Массив выводится в порядке:
[[1905,1905]-[1997,1997]]

Как сделать чтобы он выводился в обратном порядке?
[[1997,1997]-[1905,1905]]

A: Первое, что приходит на ум.
var source = [1, 2, 3],
    inverse;

inverse = source.reduce(function (carrier, element) {
    carrier.unshift(element);
    return carrier;
}, []);

// inverse = [3, 2, 1]

upd второе, что приходит на ум:
var source = [1, 2, 3];
source.reverse();

обратите внимание, что в этом случае исходный массив будет модифицирован (в то время как в первом примере создается второй массив). Чтобы создать новый, можно воспользоваться slice с первого же элемента:
var source = [1, 2, 3],
    inverse;

inverse = source.slice(0).reverse();


text:
Q: How do I access an array in an object in an array in JS? I did not find the syntax to do this.
Some unsuccessful attempts:
TILESETS[actualTileSetNO].tiles

One inconvenient but working way:
//access an object which is a specific row of the array

let x=TILESETS[actualTileSetNO];

//access the array that is within the object

let y=x.tiles;

__ update:
My syntax was good, but I think the property was not existing yet (loaded by a promise). It works if I do:
  if (typeof(state.TILESETS[state.actualTileSetNO]) !=='undefined') {
  return state.TILESETS[state.actualTileSetNO].tls}
  else {return null}

I do not see a way to close the case or flag it as an answer.

A: Checkout the following code snippet -
Assuming this might be the array structure.

let arr = [{

  arr1: ['a', 'b', 'c', 'd']
}]

console.log(arr[0].arr1);

if arr is your main array which has a couple of objects in it. Access them by using the index which will fetch you that particular object and within it, to access another array, you can use it by referring it to it's key.

A: If you have an array of objects, you should be able to access the properties of the object using the syntax you described:
TILESETS[actualTileSetNO].tiles;

e.g
const TILESETS = [
    { tiles: [1, 2, 3] },
    { tiles: [2, 4, 5] }
];

console.log(TILESETS[0].tiles[1]);
// prints 2

If this doesn't work for you, perhaps the problem is elsewhere. Could you post more of your code?

A: did you mean this here? let me know if this helps you!
arrName[arrItem].objectPropertyName[subArrItem]

var myArr = [
  {
   a:[1,2,3,4],
   b:[5,6,7,8],
   c:[9,10,11,12]
  },
  {
   d:[13,14,15,16],
   e:[16,18,19,20],
   f:[21,22,23,24]
  }
 ]

 console.log(myArr[1].f[3])


text:
Q: java.sql.SQLException: Column count doesn't match value count at row 1 with Java and MySQL Hi I'm trying to insert in a table the next values. This table has 32 values, the first one is autoincrement so it's no neccesary to put it, but when I execute it I have the next mistake:
java.sql.SQLException: Column count doesn't match value count at row 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2468)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2629)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2719)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2450)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2371)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2355)
at es.uniway.wscloud.WscloudImpl.sincronizarPedidos(WscloudImpl.java:1729)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.axis.providers.java.RPCProvider.invokeMethod(RPCProvider.java:397)
at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:186)
at org.apache.axis.providers.java.JavaProvider.invoke(JavaProvider.java:323)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.handlers.soap.SOAPService.invoke(SOAPService.java:454)
at org.apache.axis.server.AxisServer.invoke(AxisServer.java:281)
at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)

And this is the query:
SQL="INSERT INTO servidores_virtuales (id_pedido,nombre_servidor,duracion_contrato,cpu_cant,ram_cant,"+
                "hdd_cant,hdd_unidad,sv_pvp,cpu_pvp,ram_pvp,hdd_pvp,sv_pvp_dist,sv_pvp_dist,cpu_pvp_dist,ram_pvp_dist,hdd_pvp_dist,"+
                "ip_pvp,ip_pvp_dist,ip_polled_pvp,ip_polled_pvp_dist,ip_custom_pvp,ip_custom_pvp_dist,data_center,cluster,plantilla,"+
                "estado_aprobacion,f_aprobacion,f_provision,es_actualizacion,f_actualizacion,disco_almacenamiento,id_sv_ccis)VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

                int keyServidorV=0;
                System.out.println("Key de pedido es:"+key);
                this.pstm = this.conexion.prepareStatement(SQL,PreparedStatement.RETURN_GENERATED_KEYS);

                this.pstm.setInt(1, key); //Last insert id de pedido
                this.pstm.setString(2, pedido.getDatos_SV()[i].getNombre_servidor());
                this.pstm.setString(3, pedido.getDatos_SV()[i].getDuracion_contrato());
                this.pstm.setInt(4, pedido.getDatos_SV()[i].getCpu_cant());
                this.pstm.setString(5, pedido.getDatos_SV()[i].getRam_cant());
                this.pstm.setString(6, pedido.getDatos_SV()[i].getHdd_cant());
                this.pstm.setString(7, pedido.getDatos_SV()[i].getHdd_unidad());
                this.pstm.setDouble(8, pedido.getDatos_SV()[i].getSv_pvp());
                this.pstm.setDouble(9, pedido.getDatos_SV()[i].getCpu_pvp());
                this.pstm.setDouble(10, pedido.getDatos_SV()[i].getRam_pvp());
                this.pstm.setDouble(11, pedido.getDatos_SV()[i].getHdd_pvp());
                this.pstm.setDouble(12, pedido.getDatos_SV()[i].getSv_pvp_dist());
                this.pstm.setDouble(13, pedido.getDatos_SV()[i].getCpu_pvp_dist());
                this.pstm.setDouble(14, pedido.getDatos_SV()[i].getRam_pvp_dist());
                this.pstm.setDouble(15, pedido.getDatos_SV()[i].getHdd_pvp_dist());
                this.pstm.setDouble(16, pedido.getDatos_SV()[i].getIp_pvp());
                this.pstm.setDouble(17, pedido.getDatos_SV()[i].getIp_pvp_dist());
                this.pstm.setDouble(18, pedido.getDatos_SV()[i].getIp_polled_pvp());
                this.pstm.setDouble(19, pedido.getDatos_SV()[i].getIp_polled_pvp_dist());
                this.pstm.setDouble(20, pedido.getDatos_SV()[i].getIp_custom_pvp());
                this.pstm.setDouble(21, pedido.getDatos_SV()[i].getIp_custom_pvp_dist());
                this.pstm.setString(22, pedido.getDatos_SV()[i].getData_center());
                this.pstm.setString(23, pedido.getDatos_SV()[i].getCluster());
                this.pstm.setString(24, pedido.getDatos_SV()[i].getPlantilla());
                this.pstm.setInt(25, pedido.getDatos_SV()[i].getEstado_aprobacion());
                java.sql.Date f_aprobacionAux = new java.sql.Date(pedido.getDatos_SV()[i].getF_aprobacion().getTime());
                this.pstm.setDate(26, f_aprobacionAux);
                java.sql.Date f_provisionAux = new java.sql.Date(pedido.getDatos_SV()[i].getF_provision().getTime());
                this.pstm.setDate(27, f_provisionAux);
                this.pstm.setBoolean(28, pedido.getDatos_SV()[i].isEs_actualizacion());
                if(pedido.getDatos_SV()[i].getF_actualizacion()!=null){
                    java.sql.Date f_actualizacionAux =new java.sql.Date(pedido.getDatos_SV()[i].getF_actualizacion().getTime());
                    this.pstm.setDate(29, f_actualizacionAux);
                }else{

                  this.pstm.setDate(29, null);

                }
                this.pstm.setString(30, pedido.getDatos_SV()[i].getDisco_almacenamiento());
                this.pstm.setInt(31,pedido.getDatos_SV()[i].getId_servidor_virtual_ccis());

                switch(pedido.getDatos_SV()[i].getEstado_aprobacion()){

                     case 0:{
                         switch(estado_pedido){
                             case 0:{
                                 estado_pedido =1;
                                 break;
                             }
                             case 1:{
                                 estado_pedido =1;
                                 break;
                             }
                             case 2:{
                                 estado_pedido = 1;
                                 break;
                             }

                         }
                         break;
                     }
                     case 1:{
                         switch(estado_pedido){

                            case 0:{
                                estado_pedido = 2;
                                break;
                            }
                            case 1:{
                                estado_pedido =1;
                                break;
                            }
                            case 2:{
                                estado_pedido=2;
                                break;
                            }
                         }
                         break;
                     }

                }
                if(estado_pedido==2){
                    if(f_aprobacion==null){
                        f_aprobacion = pedido.getDatos_SV()[i].getF_aprobacion();
                    }else{
                        if (f_aprobacion.compareTo(pedido.getDatos_SV()[i].getF_aprobacion())<0){

                            f_aprobacion = pedido.getDatos_SV()[i].getF_aprobacion();
                        }else{
                            f_aprobacion = f_aprobacion;
                        }

                    }

                    if(pedido.getDatos_SV()[i].getF_provision()==null){
                        pedido_provisionado = false;
                    }
                    if(f_provision == null){
                        pedido.getDatos_SV()[i].getF_provision();
                    }else{
                        if(pedido.getDatos_SV()[i].getF_provision().compareTo(f_provision)>0){
                            f_provision=pedido.getDatos_SV()[i].getF_provision();
                        }else{
                            f_provision=f_provision;
                        }
                    }

                }

                String [] duracion = pedido.getDatos_SV()[i].getDuracion_contrato().split(" ");
                int cant = Integer.parseInt(duracion[0].trim());
                String unidad = duracion[1].trim().toUpperCase();

                if(unidad_duracion_contrato == ""){
                    unidad_duracion_contrato = unidad;
                    duracion_contrato = cant;
                }else{
                    if (unidad_duracion_contrato != unidad || duracion_contrato != cant){
                        throw new Exception ("Pedido con diferentes duraciones de contrato: "+pedido.getId_pedido());
                    }
                }

                int ejecutadoServiVirtual =  this.pstm.executeUpdate();

                if(ejecutadoServiVirtual==0){
                   try {
                    throw new Exception("Error al grabar Pedidos");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

Please, could you help me with this?. Thanks so much

A: Your SQL query lists 32 columns ("id_pedido" and so on), but only 31 values (the '?'s). The list of columns must match the list of values. If you aren't going to specify a value for a column, then don't include that column in the column list.

A: you are having one less '?' in the values. count it right. you have 32 columns but u only gave 31 '?'
if the first field is an autoincrement, ignore the autoincrementted field

A: If you insert a null for the autoincrement field then mysql will generate the incremented value.

A: Your column id's should match your '?'s. You can remove the 'id_pedido' column id from your list of column id's and that should fix it.

A: Generally this exception occurs when the order of values modified is different than what is actually stored int the table .. Check column indexes.


text:
Q: "Google Cloud App Engine Messaging Starter" Project works fine locally but not deployed Although the JAVA "Google Cloud App Engine Messaging Starter" Project works fine locally with Eclipse, it won't communicate messages while actually deployed.  When I "register" from the Android Emulator, I get a message that everything "registered" successfully.  When I hit "send" on the App Engine side in the html window, nothing happens.  I have Wireshark Sniffer running, and I see messages on the network when I "register" between the Android and the App Engine.  When I try to hit "send" a message via the backend html side, I see no message traffic from the index.html to the cloud nor back down to the Android.  I see no complaints about endpoints in the app engine cloud log files so assume that is working.  Has anyone been able to get the App Engine Messaging Starter Project working recently?  I'm hoping it's not the latest google app engine sdk release.  Thank you.

A: Figured it out.
1) You must run the index.html from the InternalWebBrowser of Eclipse.  You can bring up the InternalWebBrowser by selecting in Eclipse ==> Window->show view->other->general->InternalWebBrowser.
2) Then paste in your Application Default Version URL from your google App Engine "Application Settings" view.
3) Probably can do all this from a better browser but Windows 8 Pro 64-Bit Internet Explorer was giving me the problem in the first place.  It wouldn't execute the endpoint.sendMessage code.  Why, don't know right now.  Maybe microsoft's Azure is jealous, ha.

A: This problem appears to only exist in Windows 8 with any web browser, tried IE10 and Mozilla Firefox.  The javascript endpoint libraries that are not loading, load fine when using Internet Explorer on a Windows Phone 7 and from Windows 7 Pro desktop.  Figures, windows 8 pro is hosed.


text:
Q: Pull records from model in a custom order I have an rails application with user, app and review models. When user visit app show page i am fetching all reviews for an app as @app.reviews
Associations . .
User -> has_many :reviews, has_many :apps
Review -> belongs_to :app, belongs_to :user
App -> has_many :reviews, belong_to :user
I would like to fetch all the reviews with the current_user review at the top/first. How can do it?

A: You could use ActiveRecord for this. You're already using it to get all the reviews for that particular app. You can go further and use:
@app.reviews.where(user_id == current_user.id)

where current_user was your user. The belongs_to and has_many calls put those ids in there for you to use.
Since you plan to do this so that the current_user's reviews are ordered first, you could do these steps:

*

*Get all reviews for the app where the user_id != current_user.id, store in an array.

*Find the reviews for current_user, store in another array.

*Concatenate the two arrays with the current_user reviews first, yielding one array with all of the reviews for the app, but with the current_user reviews ordered first.


text:
Q: Double grouping ?? is it possible? I am trying to modify my reports mysql query, the current query is :
select `companies`.`companynameturkish` AS `Company_Name`, (round(count(`applications`.`company_id`) / (select count(*) from applications where ((`applications`.`appstatus` = '3') ))*100)) AS `Work Load`,
sum(`applications`.`netprice`) AS `Total Cost`,`companies`.`percentage` AS `Firm %`
, round(((sum(`applications`.`netprice`) * 49) / 100),2) AS `Comission`
, round(((sum(`applications`.`netprice`) * `companies`.`percentage`) / 100),2) AS `Benefits`
, round(((sum(`applications`.`netprice`) * 49) / 100),2) - round(((sum(`applications`.`netprice`) * `companies`.`percentage`) / 100),2) AS `Diff`
, count(`applications`.`company_id`) AS `Quantity`
from (`applications` left join `companies` on((`applications`.`company_id` = `companies`.`id`)))
where ((`applications`.`appstatus` = '3') and (`applications`.`recordcreationdate`
like concat(curdate(),'%'))) group by `applications`.`company_id` order by `Work Load` desc

And here is the explain :
id  select_type table   partitions  type    possible_keys   key key_len ref rows    filtered    Extra
1   PRIMARY applications    NULL    ALL company_id  NULL    NULL    NULL    6   16.67   Using where; Using temporary; Using filesort
1   PRIMARY companies   NULL    eq_ref  PRIMARY PRIMARY 4   db.applications.company_id  1   100.00  Using where
2   SUBQUERY    applications    NULL    ALL NULL    NULL    NULL    NULL    6   16.67   Using where

What I am trying to do is to add new column and group by it, that column is : provider type (applications.type), so applications grouped by applications.type left join tbl_provider on applications.type = tbl_provider.id, selecting tbl_provider.provider_name for this column , these are my tables structure to help you know what I am talking about :
CREATE TABLE `applications` (
  `serial` int(11) NOT NULL AUTO_INCREMENT,
  `policy_no` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL,
  `company_id` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
  `dataentry` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `creator_id` int(11) DEFAULT NULL,
  `approved_by` int(11) DEFAULT NULL,
  `type` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `provider_percentage` int(11) DEFAULT NULL,
  `firstname` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `fathername` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `lastname` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `birthdate` date DEFAULT NULL,
  `gender` tinyint(1) DEFAULT NULL,
  `country` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `passportno` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
  `address` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `address_main` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `address_sub` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `length` tinyint(1) DEFAULT NULL,
  `price` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `paid_price` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `netprice` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `saved_price` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `confirmed` tinyint(1) DEFAULT NULL,
  `appstatus` tinyint(1) DEFAULT NULL,
  `startdate` date DEFAULT NULL,
  `enddate` datetime DEFAULT NULL,
  `recordcreationdate` datetime DEFAULT NULL,
  `recordlastediteddate` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `cancel_reason` text COLLATE utf8_unicode_ci,
  `image_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `net_price_deduced` tinyint(1) NOT NULL DEFAULT '0',
  `status_change_1_to_3` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`serial`),
  KEY `company_id` (`company_id`),
  KEY `policy_no` (`policy_no`),
  KEY `type` (`type`),
  FULLTEXT KEY `policy_no_ft` (`policy_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `companies` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `manager_id` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
  `username` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
  `password` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
  `companynamearabic` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `companynameturkish` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `address` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
  `managername` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
  `companyspeciality` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
  `percentage` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `companytelephone` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
  `companyemail` varchar(150) CHARACTER SET latin1 DEFAULT NULL,
  `contactname` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
  `contactphone` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
  `website` varchar(150) CHARACTER SET latin1 DEFAULT NULL,
  `status` tinyint(11) DEFAULT NULL,
  `balancetype` tinyint(11) DEFAULT NULL,
  `companylimit` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
  `balance` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `recordcreationdate` date DEFAULT NULL,
  `recordlastediteddate` date DEFAULT NULL,
  `auto_approve` tinyint(4) DEFAULT NULL,
  `avl2mrkz` tinyint(4) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `tbl_provider` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `provider_name` varchar(225) COLLATE utf8_bin DEFAULT NULL,
  `no_of_slabs` int(11) DEFAULT NULL,
  `age_from` int(11) DEFAULT NULL,
  `age_to` int(11) DEFAULT NULL,
  `provider_percentage` double DEFAULT NULL,
  `provider_income` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

Thank you very much !

A: It sounds like what you want to do is tie in tbl_provider to the existing query, via a LEFT JOIN on applications.type = tbl_provider.id, and adding provider_name from tbl_provider to the SELECT list, and to the GROUP BY clause.
NOTE: With a LEFT JOIN, if there's no matching provider, provider_name will be NULL. It should still appear in the SELECT list, and can still be grouped on, but it seemed worth noting.
Basically, to group on multiple columns, you just need to list all the columns after GROUP BY.
I believe this will do what you're looking for, if the above is correct (query reformatted slightly for readability):
select `companies`.`companynameturkish` AS `Company_Name`
      ,`tbl_provider`.`provider_name`
      ,(round(count(`applications`.`company_id`) / (select count(*) from applications where ((`applications`.`appstatus` = '3') ))*100)) AS `Work Load`
      ,sum(`applications`.`netprice`) AS `Total Cost`
      ,`companies`.`percentage` AS `Firm %`
      ,round(((sum(`applications`.`netprice`) * 49) / 100),2) AS `Comission`
      ,round(((sum(`applications`.`netprice`) * `companies`.`percentage`) / 100),2) AS `Benefits`
      ,round(((sum(`applications`.`netprice`) * 49) / 100),2) - round(((sum(`applications`.`netprice`) * `companies`.`percentage`) / 100),2) AS `Diff`
      ,count(`applications`.`company_id`) AS `Quantity`
  from ((`applications` left join `companies` on (`applications`.`company_id` = `companies`.`id`))
                        left join `tbl_provider` on (`applications`.`type` = `tbl_provider`.`id`))
 where (    (`applications`.`appstatus` = '3')
        and (`applications`.`recordcreationdate` like concat(curdate(),'%'))
       )
 group by `applications`.`company_id`, `tbl_provider`.`provider_name`
 order by `Work Load` desc

I've added tbl_provider.provider_name as the second item in the SELECT list, added the LEFT JOIN to tbl_provider, and added tbl_provider.provider_name as the second item in the GROUP BY as well.
NOTE: code untested, typos possible.


text:
Q: Django: How to use model properties within custom methods in a serializer? from rest_framework import serializers

class UserProfileSerializer(serializers.ModelSerializer):
    """Serializes data for User."""
    url = serializers.URLField(source='profile_url')

    def profile_url(self):
        """Return user profile endpoint."""
        return reverse('user:profile_view', kwargs=self.context.get('id', None))

    class Meta:
        model = User
        fields = ('id', 'url')

How can I access User.id within profile_url? There doesn't appear to be any id parameter within the context or at least I don't think I'm accessing properly.

A: Actually, you may want to change the field on your serializer to be:
url = serializers.SerializerMethodField('profile_url')

This will give the method profile_url an extra parameter, the object that is being serialized. So in your case, this becomes:
def profile_url(self, obj):
    """Return user profile endpoint."""
    return reverse('user:profile_view', args=[obj.id,])


text:
Q: Extra column in bootstrap table Why there is an extra column in the table?

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

       Back

          Sr.
          Name
          Contact
          City
          Action

          1

            Name
          Email Id (Mobile Number)
          City
          <button class="btn btn-large btn-primary" disabled>Waiting for Directory</button>

          2

            Name
          Email Id (Mobile Number)
          City
          Block

Why there is an extra column in the table? see image
Also, why there is scrollbar when screen is small? (It should adjust itself with the screen as I am using table-responsive.)

A: add .table-responsive class to the parent. not on table

    ...

A: Remove .table-responsive or add style attribute on table tag display : table


text:
Q: Generating dialog from a separate thread I have almost completed converting a pyGTK application to pyQT4.
One of the last aspects I am struggling with is generating a dialog from a separate thread.
I have a main GUI and a background thread. On the offchance of thread-specific issues, the thread generates a dialog.
For pyGTK what I do is:
  def update_gui(function, *args, **kargs):
      '''DocString'''
      def idle_func():
          '''DocString'''
          Gdk.threads_enter()
          try:
            function(*args, **kargs)
          finally:
              Gdk.threads_leave()
      GObject.idle_add(idle_func)

  def gui_error(msg):
      '''Simple wrapper for a warning dialog'''
      md = Gtk.MessageDialog(parent=None, message_type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.CLOSE)
      md.set_markup(msg)
      md.run()
      md.destroy()

Called as: update_gui(gui_error,'help')
Is there an equivelent in pyQT4 or do I need to gut what I have to start passing signals?

A:
do I need to gut what I have to start passing signals?

yes you do.
You can always have your "other thread" be QObject based and have a QObject from QApplication's children based object as parent, and call the moveToThread() method but it's better to have the main thread handle GUI, and other threads send signals to the main thread to have it updated.
Take the opportunity of moving from GTK to QT, to actually redesign correctly your application, with real decoupling between the main components of your software.


text:
Q: Dispatch an action from container I'm new to react-redux and i want to dispatch an action from container to component. Here is my code :
Container :
import { connect } from 'react-redux';
import addCountryComponent from '../../views/Country/AddCountry'
import { addCountry } from '../../actions/countryActions'

const mapDispatchToProps = (dispatch) => {
  return {
    addCountry:(country) => dispatch(addCountry(country))
  }
}

const CountryContainer = connect(null, mapDispatchToProps)(addCountryComponent)
export default CountryContainer;

AddCountry Component :
import React, {Component} from 'react';

class AddCountry extends Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    console.log(this.props);
  }
  render() {
    return (
      <div className="animated fadeIn">
asdas
      </div>
    );
  }
}

export default AddCountry;

and Action file
import { ADD_COUNTRY } from './names'

export function addCountry(payload) {
  console.log(payload, "actions")
  return {
    type: ADD_COUNTRY,
    payload,
  }
}

I can't see addCountry as a props, am i missing something ?

A: as you mentioned in the comment you should link your container to your route file.
that means your container gets called when a browser open this /add/country

A: const mapDispatchToProps = dispatch => {
    return {
      addCountry: (country) => dispatch({ type: ADD_COUNTRY ,country})
    }}
TO  used it on click event
you should make  add reducer for this app
example
const balance =(state={country:""},action)=>{
  switch(action.type){
    case ADD_COUNTRY:  return{ country: action.country;}
this.props.addCountry(country)

A: This because of mapDispatchToProps auto-add property addCountry to your addCountryComponent.
const mapDispatchToProps = (dispatch) => {
  return {
    // component that using this function will auto have addCountry in props of component
    addCountry:(country) => dispatch(addCountry(country))
  }
}

// this addCountryComponent using mapDispatchToProps so it have addCountry in props
const CountryContainer = connect(null, mapDispatchToProps)(addCountryComponent)
export default CountryContainer;

A: Did you try using bindActionCreators function of Redux?
import { bindActionCreators } from 'redux';

const mapDispatchToProps = (dispatch) => bindActionCreators({
  addCountry: addCountry,
}, dispatch);


text:
Q: Ubuntu 12.04 - Steam not running I've been using Steam on Linux for quite a while now and never had any problems. Recently though, in the past few days, Steam seems not to start anymore- or at least, I can't see it running and I can't access any of my games.
I tried reinstalling it, but to no avail.
If I try to run "steam" in terminal, this is what I get:
Running Steam on ubuntu 12.04 64-bit
STEAM_RUNTIME is enabled automatically

and then nothing happens.
If I try opening it with STEAM_RUNTIME=0 steam, I get:
Running Steam on ubuntu 12.04 64-bit
STEAM_RUNTIME is disabled by the user

Error: You are missing the following 32-bit libraries, and Steam may not run:

libpangoft2-1.0.so.0
libpango-1.0.so.0
libgtk-x11-2.0.so.0
libgtk-x11-2.0.so.0
libgdk-x11-2.0.so.0
libpangocairo-1.0.so.0
libgdk_pixbuf-2.0.so.0
libcairo.so.2
libpango-1.0.so.0
libnss3.so
libnssutil3.so
libsmime3.so
libplc4.so
libnspr4.so

So I'm quite at a loss as to what has happened here. I haven't changed anything in my configuration, and I'm not even sure where to find such libraries.
What can I do, since a removal and a reinstall didn't work?
Small update: I tried opening Playonlinux (my WoW installation stopped working now too), and I received an error message that basically said I no longer had any 32bit libraries and that my games could not run properly.
So now the question is- how do I get them back? :)
SECOND UPDATE: I tried reinstalling the ia32-libs, and this is the outcome:
    sudo apt-get install ia32-libs
    Reading package lists... Done
    Building dependency tree
    Reading state information... Done
    Some packages could not be installed. This may mean that you have
    requested an impossible situation or if you are using the unstable
    distribution that some required packages have not yet been created
    or been moved out of Incoming.
    The following information may help to resolve the situation:

    The following packages have unmet dependencies:
     ia32-libs : Depends: ia32-libs-multiarch
    E: Unable to correct problems, you have held broken packages.

So then I tried running sudo apt-get install ia32-libs-multiarch , and I got this:
    Some packages could not be installed. This may mean that you have
    requested an impossible situation or if you are using the unstable
    distribution that some required packages have not yet been created
    or been moved out of Incoming.
    The following information may help to resolve the situation:

    The following packages have unmet dependencies:
     ia32-libs-multiarch:i386 : Depends: gstreamer0.10-plugins-good:i386 but it is not going to be installed
                        Depends: gtk2-engines:i386 but it is not going to be installed
                        Depends: gtk2-engines-murrine:i386 but it is not going to be installed
                        Depends: gtk2-engines-pixbuf:i386 but it is not going to be installed
                        Depends: gtk2-engines-oxygen:i386 but it is not going to be installed
                        Depends: ibus-gtk:i386 but it is not going to be installed
                        Depends: libcanberra-gtk-module:i386 but it is not going to be installed
                        Depends: libgail-common:i386 but it is not going to be installed
                        Depends: libgtk2.0-0:i386 but it is not going to be installed
                        Depends: librsvg2-common:i386 but it is not going to be installed
    E: Unable to correct problems, you have held broken packages.

I think it's pretty obvious at this point that my 32libs are either gone or no longer recognized, but I have no idea why.

A: Somehow either you have missing libraries or Steam don't know where they are. You can solve the first by running:
sudo apt-get install libpango-1.0-0 libpangoft2-1.0-0 libgtk2.0-0 libpangocairo-1.0-0 libgdk-pixbuf2.0-0 libcairo2 libnss3-1d libnss3 libnspr4-0d

Once you have done this, try again.

A: I just encountered this issue as well. I had steam relocated to a ntfs formatted drive to be read by Windows. I had symbolicaly linked ~/.local/share/Steam to the other folder and I think that was the issue. I put the Steam files back and only linked the SteamApps folder and then it worked fine.


text:
Q: Why is mount is forcing me to specify -t ext4 for one partition, but not the other? I have two very similar partitions, /dev/sdb1 (labeled 'bigb') and /dev/sdc1 (labeled 'bigc'). I used to be able to mount both of them using mount -n -L bigX /mnt/donottouch/localX (with X being b or c). However, mount has recently started requiring me to specify -t ext4 but only on bigc.
bigb mounts just fine:
# mount -n -L bigb  /mnt/donottouch/localb -vvv
mount: fstab path: "/etc/fstab"
mount: mtab path:  "/etc/mtab"
mount: lock path:  "/etc/mtab~"
mount: temp path:  "/etc/mtab.tmp"
mount: UID:        0
mount: eUID:       0
mount: spec:  "/dev/sdb1"
mount: node:  "/mnt/donottouch/localb"
mount: types: "(null)"
mount: opts:  "(null)"
final mount options: '(null)'
mount: you didn't specify a filesystem type for /dev/sdb1
       I will try type ext4
mount: mount(2) syscall: source: "/dev/sdb1", target: "/mnt/donottouch/localb", filesystemtype: "ext4", mountflags: -1058209792, data: (null)
/dev/sdb1 on /mnt/donottouch/localb type ext4 (rw)

But then bigc errors out:
# mount -n -L bigc  /mnt/donottouch/localc -vvv
mount: fstab path: "/etc/fstab"
mount: mtab path:  "/etc/mtab"
mount: lock path:  "/etc/mtab~"
mount: temp path:  "/etc/mtab.tmp"
mount: UID:        0
mount: eUID:       0
mount: spec:  "/dev/sdc1"
mount: node:  "/mnt/donottouch/localc"
mount: types: "(null)"
mount: opts:  "(null)"
final mount options: '(null)'
mount: you didn't specify a filesystem type for /dev/sdc1
       I will try all types mentioned in /etc/filesystems or /proc/filesystems
mount: you must specify the filesystem type

...unless I specify -t ext4:
# mount -n -L bigc  /mnt/donottouch/localc -vvv -t ext4
mount: fstab path: "/etc/fstab"
mount: mtab path:  "/etc/mtab"
mount: lock path:  "/etc/mtab~"
mount: temp path:  "/etc/mtab.tmp"
mount: UID:        0
mount: eUID:       0
mount: spec:  "/dev/sdc1"
mount: node:  "/mnt/donottouch/localc"
mount: types: "ext4"
mount: opts:  "(null)"
final mount options: '(null)'
mount: mount(2) syscall: source: "/dev/sdc1", target: "/mnt/donottouch/localc", filesystemtype: "ext4", mountflags: -1058209792, data: (null)
/dev/sdc1 on /mnt/donottouch/localc type ext4 (rw)

Mount claims that it will try "all types mentioned in /etc/filesystems or /proc/filesystems", but it clearly isn't doing that, given that those two files contain ext4:
# cat /etc/filesystems
ext4
ext3
ext2
nodev proc
nodev devpts
iso9660
vfat
hfs
hfsplus

# cat /proc/filesystems
nodev   sysfs
nodev   rootfs
nodev   bdev
nodev   proc
nodev   cgroup
nodev   cpuset
nodev   tmpfs
nodev   devtmpfs
nodev   binfmt_misc
nodev   debugfs
nodev   securityfs
nodev   sockfs
nodev   usbfs
nodev   pipefs
nodev   anon_inodefs
nodev   inotifyfs
nodev   devpts
nodev   ramfs
nodev   hugetlbfs
        iso9660
nodev   pstore
nodev   mqueue
nodev   rpc_pipefs
nodev   nfs
nodev   nfs4
        ext4
nodev   fuse
        fuseblk
nodev   fusectl
nodev   autofs
nodev   nfsd
        ext3

Besides, why would it decide to try ext4 for bigb, but try all filesystem types for bigc?
To add to the weirdness, blkid is able to detect bigc as ext4:
# blkid -o value -s TYPE /dev/sdb1
ext4
# blkid -o value -s TYPE /dev/sdc1
ext4
# mount -V
mount from util-linux-ng 2.17.2 (with libblkid and selinux support)

tune2fs -l shows that both partitions are essentially the same except for the inode size:
# tune2fs -l /dev/sdb1
tune2fs 1.41.12 (17-May-2010)
Filesystem volume name:   bigb
Last mounted on:          /mnt/donottouch/localb
Filesystem UUID:          2ceadc5b-c302-43d1-b289-047069a15537
Filesystem magic number:  0xEF53
Filesystem revision #:    1 (dynamic)
Filesystem features:      has_journal ext_attr resize_inode dir_index filetype needs_recovery extent sparse_super large_file uninit_bg
Filesystem flags:         signed_directory_hash
Default mount options:    (none)
Filesystem state:         clean
Errors behavior:          Continue
Filesystem OS type:       Linux
Inode count:              122101760
Block count:              488378000
Reserved block count:     24418900
Free blocks:              101141916
Free inodes:              118086875
First block:              0
Block size:               4096
Fragment size:            4096
Reserved GDT blocks:      907
Blocks per group:         32768
Fragments per group:      32768
Inodes per group:         8192
Inode blocks per group:   1024
Filesystem created:       Fri May 13 18:08:33 2011
Last mount time:          Fri Jul 19 11:59:32 2013
Last write time:          Fri Jul 19 11:59:32 2013
Mount count:              4
Maximum mount count:      39
Last checked:             Thu Mar 14 15:11:01 2013
Check interval:           15552000 (6 months)
Next check after:         Tue Sep 10 15:11:01 2013
Lifetime writes:          439 GB
Reserved blocks uid:      0 (user root)
Reserved blocks gid:      0 (group root)
First inode:              11
Inode size:               512
Required extra isize:     28
Desired extra isize:      28
Journal inode:            8
Default directory hash:   half_md4
Directory Hash Seed:      ad841c26-0111-4f32-bab5-e8ebc9616f18
Journal backup:           inode blocks

# tune2fs -l /dev/sdc1
tune2fs 1.41.12 (17-May-2010)
Filesystem volume name:   bigc
Last mounted on:          /mnt/donottouch/localc
Filesystem UUID:          74d41e82-d431-4b3d-ae1a-01dcb363a047
Filesystem magic number:  0xEF53
Filesystem revision #:    1 (dynamic)
Filesystem features:      has_journal ext_attr resize_inode dir_index filetype needs_recovery extent sparse_super large_file uninit_bg
Filesystem flags:         signed_directory_hash
Default mount options:    (none)
Filesystem state:         clean
Errors behavior:          Continue
Filesystem OS type:       Linux
Inode count:              122101760
Block count:              488378000
Reserved block count:     24418900
Free blocks:              103460007
Free inodes:              118032588
First block:              0
Block size:               4096
Fragment size:            4096
Reserved GDT blocks:      907
Blocks per group:         32768
Fragments per group:      32768
Inodes per group:         8192
Inode blocks per group:   512
Filesystem created:       Wed Apr 27 14:55:53 2011
Last mount time:          Fri Jul 19 12:01:47 2013
Last write time:          Fri Jul 19 12:01:47 2013
Mount count:              6
Maximum mount count:      35
Last checked:             Sat Mar  2 14:09:26 2013
Check interval:           15552000 (6 months)
Next check after:         Thu Aug 29 15:09:26 2013
Lifetime writes:          381 GB
Reserved blocks uid:      0 (user root)
Reserved blocks gid:      0 (group root)
First inode:              11
Inode size:               256
Required extra isize:     28
Desired extra isize:      28
Journal inode:            8
Default directory hash:   half_md4
Directory Hash Seed:      f36ed43e-46b4-473c-8af0-07dc2a8d90c8
Journal backup:           inode blocks

Some extra system info:
# cat /etc/system-release
Scientific Linux release 6.4 (Carbon)
# uname -ar
Linux ml44 2.6.32-358.14.1.el6.x86_64 #1 SMP Tue Jul 16 14:24:33 CDT 2013 x86_64 x86_64 x86_64 GNU/Linux

lsblk --fs seems to hiccup on bigc:
# lsblk --fs /dev/sdb1
NAME FSTYPE LABEL UUID                                 MOUNTPOINT
sdb1 ext4   bigb  2ceadc5b-c302-43d1-b289-047069a15537 /mnt/donottouch/localb
# lsblk --fs /dev/sdc1
NAME FSTYPE LABEL UUID MOUNTPOINT
sdc1                   /mnt/donottouch/localc
# e2label /dev/sdc1
bigc

Neither of them are in /etc/fstab or /etc/mtab. They are both clean according to e2fsck. Any ideas? The only significant recent change I can think of is an update from Scientific Linux 6.1 to 6.4.

A: i think the partition type of sdb1 is set to 83, which indicates a Linux fs like Ext4. While sdc1 seems to be set to some other type, according to your output of lsblk.
you can modify the partition type via utilities like fdisk or cfdisk. if i remember correctly, in fdisk you can change it by using the t command and then entering 83.


text:
Q: Heroku Python App Suddenly Giving R15 Error I'm using free heroku dynos and postgres, running a python flask app. It often cut it close on the memory limits of free dynos (the app loads a few models upon startup), but for eight months it was running no problem. Then today, I saw this error:
2021-04-15T08:28:41.566146+00:00 heroku[web.1]: State changed from crashed to starting
2021-04-15T08:28:55.333917+00:00 heroku[web.1]: Starting process with command `gunicorn app:app`
2021-04-15T08:28:57.226420+00:00 app[web.1]: [2021-04-15 08:28:57 +0000] [4] [INFO] Starting gunicorn 19.9.0
2021-04-15T08:28:57.226786+00:00 app[web.1]: [2021-04-15 08:28:57 +0000] [4] [INFO] Listening at: http://0.0.0.0:7490 (4)
2021-04-15T08:28:57.226838+00:00 app[web.1]: [2021-04-15 08:28:57 +0000] [4] [INFO] Using worker: sync
2021-04-15T08:28:57.229746+00:00 app[web.1]: [2021-04-15 08:28:57 +0000] [10] [INFO] Booting worker with pid: 10
2021-04-15T08:28:57.313381+00:00 app[web.1]: [2021-04-15 08:28:57 +0000] [11] [INFO] Booting worker with pid: 11
2021-04-15T08:28:58.983920+00:00 heroku[web.1]: State changed from starting to up
2021-04-15T08:29:01.760373+00:00 heroku[web.1]: Process running mem=512M(100.0%)
2021-04-15T08:29:01.788242+00:00 app[web.1]: [2021-04-15 08:29:01 +0000] [42] [INFO] Booting worker with pid: 42
2021-04-15T08:29:01.800651+00:00 heroku[web.1]: Error R15 (Memory quota vastly exceeded)
2021-04-15T08:29:01.802395+00:00 heroku[web.1]: Stopping process with SIGKILL
2021-04-15T08:29:01.912435+00:00 heroku[web.1]: Process exited with status 137
2021-04-15T08:29:01.984054+00:00 heroku[web.1]: State changed from up to crashed
2021-04-15T08:30:57.809476+00:00 app[api]: Starting process with command `ps:scale web=2` by user large.adam.m@gmail.com
2021-04-15T08:31:14.882047+00:00 heroku[run.4863]: Awaiting client
2021-04-15T08:31:14.899189+00:00 heroku[run.4863]: Starting process with command `ps:scale web=2`
2021-04-15T08:31:15.029551+00:00 heroku[run.4863]: State changed from starting to up
2021-04-15T08:31:19.037705+00:00 heroku[run.4863]: Process exited with status 127
2021-04-15T08:31:19.083172+00:00 heroku[run.4863]: State changed from up to complete
2021-04-15T08:33:16.656240+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=ludothemes.herokuapp.com request_id=17839d00-978a-4e4e-b188-cb1570d871f7 fwd="107.212.209.19" dyno= connect= service= status=503 bytes= protocol=http
2021-04-15T08:33:22.257162+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=ludothemes.herokuapp.com request_id=f7a25e76-f51c-479a-a922-4a5dce350d5c fwd="107.212.209.19" dyno= connect= service= status=503 bytes= protocol=http
2021-04-15T08:36:21.885333+00:00 heroku[web.1]: State changed from crashed to starting
2021-04-15T08:36:34.035395+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=ludothemes.herokuapp.com request_id=381addaf-a75b-4c7a-9309-126029119c4f fwd="107.212.209.19" dyno= connect= service= status=503 bytes= protocol=http
2021-04-15T08:36:39.535412+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=ludothemes.herokuapp.com request_id=a8f0edf8-87e6-4a8a-8aa6-4f83e01661df fwd="107.212.209.19" dyno= connect= service= status=503 bytes= protocol=http
2021-04-15T08:36:40.641472+00:00 heroku[web.1]: Starting process with command `gunicorn app:app`
2021-04-15T08:36:42.379884+00:00 app[web.1]: [2021-04-15 08:36:42 +0000] [4] [INFO] Starting gunicorn 19.9.0
2021-04-15T08:36:42.380270+00:00 app[web.1]: [2021-04-15 08:36:42 +0000] [4] [INFO] Listening at: http://0.0.0.0:43156 (4)
2021-04-15T08:36:42.380320+00:00 app[web.1]: [2021-04-15 08:36:42 +0000] [4] [INFO] Using worker: sync
2021-04-15T08:36:42.383371+00:00 app[web.1]: [2021-04-15 08:36:42 +0000] [10] [INFO] Booting worker with pid: 10
2021-04-15T08:36:42.429343+00:00 app[web.1]: [2021-04-15 08:36:42 +0000] [11] [INFO] Booting worker with pid: 11
2021-04-15T08:36:42.740845+00:00 heroku[web.1]: State changed from starting to up
2021-04-15T08:36:46.581577+00:00 heroku[web.1]: Process running mem=512M(100.0%)
2021-04-15T08:36:46.607496+00:00 app[web.1]: [2021-04-15 08:36:46 +0000] [42] [INFO] Booting worker with pid: 42
2021-04-15T08:36:46.632959+00:00 heroku[web.1]: Error R15 (Memory quota vastly exceeded)
2021-04-15T08:36:46.635253+00:00 heroku[web.1]: Stopping process with SIGKILL
2021-04-15T08:36:46.702243+00:00 heroku[web.1]: Process exited with status 137
2021-04-15T08:36:46.883019+00:00 heroku[web.1]: State changed from up to crashed
2021-04-15T08:44:56.645111+00:00 heroku[web.1]: State changed from crashed to starting
2021-04-15T08:45:09.196127+00:00 heroku[web.1]: Starting process with command `gunicorn app:app`
2021-04-15T08:45:10.572619+00:00 app[web.1]: [2021-04-15 08:45:10 +0000] [4] [INFO] Starting gunicorn 19.9.0
2021-04-15T08:45:10.572997+00:00 app[web.1]: [2021-04-15 08:45:10 +0000] [4] [INFO] Listening at: http://0.0.0.0:44998 (4)
2021-04-15T08:45:10.573055+00:00 app[web.1]: [2021-04-15 08:45:10 +0000] [4] [INFO] Using worker: sync
2021-04-15T08:45:10.575990+00:00 app[web.1]: [2021-04-15 08:45:10 +0000] [10] [INFO] Booting worker with pid: 10
2021-04-15T08:45:10.672926+00:00 app[web.1]: [2021-04-15 08:45:10 +0000] [11] [INFO] Booting worker with pid: 11
2021-04-15T08:45:10.792978+00:00 heroku[web.1]: State changed from starting to up
2021-04-15T08:45:14.493337+00:00 heroku[web.1]: Process running mem=512M(100.0%)
2021-04-15T08:45:14.513393+00:00 app[web.1]: [2021-04-15 08:45:14 +0000] [42] [INFO] Booting worker with pid: 42
2021-04-15T08:45:14.538602+00:00 heroku[web.1]: Error R15 (Memory quota vastly exceeded)
2021-04-15T08:45:14.539922+00:00 heroku[web.1]: Stopping process with SIGKILL
2021-04-15T08:45:14.549012+00:00 heroku[web.1]: Process running mem=264M(51.6%)
2021-04-15T08:45:14.636653+00:00 heroku[web.1]: Process exited with status 137
2021-04-15T08:45:14.682557+00:00 heroku[web.1]: State changed from up to crashed
2021-04-15T08:45:14.691912+00:00 heroku[web.1]: State changed from crashed to starting
2021-04-15T08:45:33.819016+00:00 heroku[web.1]: Starting process with command `gunicorn app:app`
2021-04-15T08:45:35.480103+00:00 app[web.1]: [2021-04-15 08:45:35 +0000] [4] [INFO] Starting gunicorn 19.9.0
2021-04-15T08:45:35.480524+00:00 app[web.1]: [2021-04-15 08:45:35 +0000] [4] [INFO] Listening at: http://0.0.0.0:5640 (4)
2021-04-15T08:45:35.480582+00:00 app[web.1]: [2021-04-15 08:45:35 +0000] [4] [INFO] Using worker: sync
2021-04-15T08:45:35.483462+00:00 app[web.1]: [2021-04-15 08:45:35 +0000] [10] [INFO] Booting worker with pid: 10
2021-04-15T08:45:35.568432+00:00 app[web.1]: [2021-04-15 08:45:35 +0000] [11] [INFO] Booting worker with pid: 11
2021-04-15T08:45:36.044752+00:00 heroku[web.1]: State changed from starting to up
2021-04-15T08:45:41.085020+00:00 heroku[web.1]: Process running mem=512M(100.0%)
2021-04-15T08:45:41.116608+00:00 heroku[web.1]: Error R15 (Memory quota vastly exceeded)
2021-04-15T08:45:41.118394+00:00 heroku[web.1]: Stopping process with SIGKILL
2021-04-15T08:45:41.118709+00:00 app[web.1]: [2021-04-15 08:45:41 +0000] [42] [INFO] Booting worker with pid: 42
2021-04-15T08:45:41.135141+00:00 heroku[web.1]: Process running mem=244M(47.7%)
2021-04-15T08:45:41.171322+00:00 heroku[web.1]: Error R15 (Memory quota vastly exceeded)
2021-04-15T08:45:41.175932+00:00 heroku[web.1]: Stopping process with SIGKILL
2021-04-15T08:45:41.201559+00:00 heroku[web.1]: Process exited with status 137
2021-04-15T08:45:41.251165+00:00 heroku[web.1]: State changed from up to crashed
2021-04-15T08:52:00.055423+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=ludothemes.herokuapp.com request_id=e9db949e-c3db-4cbe-b770-2ee66deabc8d fwd="107.212.209.19" dyno= connect= service= status=503 bytes= protocol=http
2021-04-15T08:52:05.682515+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=ludothemes.herokuapp.com request_id=dd0f05d4-a907-4f1b-b51f-15a7374e96ab fwd="107.212.209.19" dyno= connect= service= status=503 bytes= protocol=http

I get R15 errors, but it seems to not get to twice the limits of the free dynos. Did something change in heroku or python that would affect how my app is loading all of a sudden?
Any suggestions of things to look into would be appreciated!

A: Exactly the same problem for me - my app was running for several months using free dynos, there was no problem going at 180% memory usage, but since 2 days ago it's failing:
Process running mem=512M(100.0%)
Error R15 (Memory quota vastly exceeded)
Stopping process with SIGKILL

I was hopeful that this incident might be related, but unfortunately they have closed it.

A: This seems to have been an issue with Heroku and to now be fixed. I've sent Heroku a ticket and received the following reply yesterday:

It looks like this was related to a new infrastructure rollout our engineering team is conducting. They've recently put in a fix to correctly calculate R15 errors correctly so you shouldn't experience any additional issues. We apologize for any inconvenience this has caused, please let us know if you have any questions.

I confirm that things are working on my app at least. Hope it's the same to you.


text:
Q: Specifying multiple patterns in a restriction in a XSD I have following XSD element:
<xsd:element name="password">
    <xsd:simpleType>
        <xsd:restriction base="xsd:string">
            <!-- Length check -->
            <xsd:pattern value=".{9,12}" />
            <!-- Format check -->
            <xsd:pattern value=".*\d{2,}.*" />
            <xsd:pattern value=".*[A-Z]{1,}.*" />
            <xsd:pattern value=".*[a-z]{1,}.*" />
            <xsd:pattern value=".*\p{Punct}.*" />
        </xsd:restriction>
    </xsd:simpleType>
</xsd:element>

I want to apply each of those patterns individually. It should first check that length is proper. If so then check that it has at least 2 digits and so on. Instead, it concatenates all the expressions together and tries to apply them together.
This is very poor design. If only one pattern is allowed <xsd:restriction> should define the cardinality of <xsd:pattern> to be 1. Allowing multiple <xsd:pattern> gives the impression that multiple patterns are supported.
Is there a way to apply multiple patterns to a XSD element?

A: Multiple patterns per restriction are supported, but they do not mean AND; they mean OR:

Note: An XML <restriction> containing more than one <pattern> element
gives rise to a single ·regular expression· in the set; this ·regular
expression· is an "or" of the ·regular expressions· that are the
content of the <pattern> elements.

If you want multiple regex constraints to apply concurrently, write them in a single <pattern>.
For min/max length constraints, rather than using <pattern>, consider using <minLength> and <maxLength> facets.


text:
Q: How do I add The Simpson's characters to Lego Dimensions? I tried to register Bart and Krusty, with my brother. However, we can only get them to register as blank toys.
What can I do to fix this?

A: When building new Lego Dimension toys, it's important to use the correct base.  Bart's base has a picture of his slingshot on it, and Krusty's has his bow tie.
If Bart and Krusty are both showing up as blank toys, chances are you mixed their bases up with the bases for their vehicles.  If you put them on the correct bases, they should be recognized by the game.  Then you can build the vehicles and register them to their bases.
If you don't have Bart or Krusty's base, you may have ended up with a defective fun pack, and you should talk to whoever you bought it from.


text:
Q: Check if number belongs to a series I have two series
$0,3,4,7,8,11,12,\ldots$
$1,2,5,6,9,10,13,14,\ldots$
If I give a number to a function it should return whether the number belongs to first series on second series
For ex:
3 - First Series
13 - Second Series
So what is simple and fast.

A: As requested in comments and combining my and Sahiba Arora's comments:
If you take the integers modulo $4$, i.e. the remainder on division by $4$, then

*

*those in the first sequence are equivalent to $0$ or $3$ mod $4$

*those in the second sequence are equivalent to $1$ or $2$ mod $4$


text:
Q: GitHub and using SSH keys I know there are lots of links about this topic and some official ones. I have tried several SO answers too but I am still at a loss.

*

*I have created a ED25519 SSH private key (PPK file) and public key (PUB file).

*My key has a passphrase.

*I have added my public key to GitHub.

*I have added my PPK key to Putty Pageant.

*I have changed the repository to use the SSH key URL as identified on GitHub.

But it will not push and came up with a port 22 issue. After research I found and answer that said to create a config file and put this in it:
Host github.com
  Hostname ssh.github.com
  Port 443

then, I tried this command:
ssh -vT git@github.com
It found my key and asked for the passphrase. It worked, although it does say this:
Hi xxxxx! You've successfully authenticated, but GitHub does not provide shell access.
debug1: channel 0: free: client-session, nchannels 1
Transferred: sent 2160, received 2304 bytes, in 0.2 seconds
Bytes per second: sent 9143.6, received 9753.2
debug1: Exit status 1

It has that comment about the shell? Anyway, I then go into TortoiseGit Git settings and confirm it is using my "noreply" email address, has the SSH git URL and that I have selected the PPK PuttyLink file.
Despite all of this, I can't push to the remote server. Tried for 3 days. :(
What step am I missing?

A: The configuration file .ssh/config is not honored by PuTTY. Switch to OpenSSH or configure a session in PuTTY or use the url ssh://git@ssh.github.com:443/....
cf. https://tortoisegit.org/support/faq/#howsshdifferentport


text:
Q: What steps should i follow to find the root cause of a table getting locked in mysql? One of the table in mysql DB is getting locked.
Please let me know the steps that i should follow to find the root cause behind it i.e. who is locking the table and when ?
Thanks,
Sachin

A: First, check that the table is locked - does it appear in the results of:
mysql> SHOW OPEN TABLES WHERE in_use;

If it is currently locked, from the command line, run:
# mysqladmin debug -u <user> -p

(<user> is most likely root, depending on your set-up)
Now check your error log (this is inside the data directory by default, find the location by checking your my.cnf file). You should find details of the process doing the locking.
The relevant bit of the output looks like:
Current locks:
lock: 0x7f759da38e90: write
write     : 0x7f759da97a00 (54:12);

From within the database (with a user with the SUPER privilege) run SHOW PROCESSLIST to find out which session the logs are referring to. In the example above, you want the process ID 54 (identified by the (54:12)).


text:
Q: Release APK made based on master or current branch I'm wondering when you Generate Signed APK if Android studio does this based on the master branch version of the project or the current checked out branch?
I make sure to merge everything to master and generate from there anyway but I'm just curious.

A: Android Studio will generate the signed APK based on the checked out branch.
Source: tried it out.


text:
Q: Definition of global field This is very embarrassing thing to ask but what is a definition of global field? Every text or internet sources says either a number field or function field over finite field. (Yes, I understand there is nothing wrong with this but I would like to know the 'axiomatic' definition)
Thanks,

A: I glanced at the paper, and here's a summary. There are two axioms imposed on a field $k$ which are necessary and sufficient (these are theorems in the paper) for the field to be global (i.e. a number field or a finitely generated extension of a finite field of transcendence degree $1$):
Axiom (1): There is a set $\mathfrak{M}$ of places of $k$ (equivalence classes of absolute values) and absolute values $\vert \cdot\vert_\mathfrak{p}\in\mathfrak{p}$ for each $\mathfrak{p}\in\mathfrak{M}$ such that for each $\alpha\neq 0$ in $k$, $\vert \alpha\vert_\mathfrak{p}=1$ for all but finitely many $\mathfrak{p}$, and we have the product formula
$$\prod_{\mathfrak{p}\in\mathfrak{M}}\vert \alpha\vert_\mathfrak{p}=1.$$
Axiom (2) The set $\mathfrak{M}$ contains at least one place $\mathfrak{p}$ which is either discrete with finite residue field or Archimedean.
Theorem 2 of the paper says that algebraic number fields and algebraic function fields satisfy the two axioms, with the every member of the set set of places in each case satisfying Axiom (2) (not just the one place required by Axiom (2)). Theorem 3 says that a field satisfying both axioms is a global field (the converse of Theorem 2).
I think it's probably safe to say that this axiomatic characterization, while nice, is not what most number theorists adopt as the definition of a global field.


text:
Q: Running multiple commands in irb I am using Mechanize to crawl a site that requires login.  The following code logs me in.
require 'mechanize'

agent = Mechanize.new
agent.get 'http://www.specialsite.com'

agent.page.form.txtEmail = 'myemail@email.com'
agent.page.form.txtPassword = 'myPassword'
agent.page.form.add_field! "__EVENTTARGET","btnLogin"
agent.page.form.add_field! "__EVENTARGUMENT",""
agent.page.form.submit

agent.page.link_with(:text => "Special Link").click

agent.page.form.txtSearch = "Search Text"
agent.page.form.add_field! "__EVENTTARGET","lbtnSearch"
agent.page.form.add_field! "__EVENTARGUMENT",""
agent.page.form.submit

My question is, how do I run this code in the ruby IRB so that I can have access to the objects it defines like 'agent' to experiment with and generate the rest of the code I need?
I have tried 'load'.  It runs the commands but it doesn't make the objects like 'agent' available.

A: write this stuff in a textfile as it is, open IRB and type:
File.open("your_file","r").readlines.each{|line| eval(line)}

Does this help?
EDIT: the Textfile must exist in the same directory where you fire up IRB. General advantage: it is way easier to modify something in a textfile than to fiddle in a huge IRB one-liner.

A: Use pry:
require 'pry'
... your code
binding.pry

When you run the script it will stop at binding.pry and you have an irb-like repl (but better) where you can evaluate objects. Use exit to continue or exit-program to quit.

A: Since that is all repeatable code and you should try and implement DRY(Don't Repeat Yourself) when ever you can.  I would through all this in a class and have a method that returns agent.  Then in irb  you would require the class and set your irb variable to class getmethod.  And this way you already have the start of class that you will use for your project lator

A: I agree with @pguardiaro to use Pry
But here is how you do it in IRB:
binding.eval(File.read("your_file.rb"), "your_file.rb"


text:
Q: PHP+BillDesk payment gateway integration issue I am trying to integrate BillDesk payment gateway with my PHP website. I am getting this below error when I run my simple PHP code
{"status":422,"error_type":"invalid_data_error","error_code":"GNIDE0004","message":"Invalid Content-type header"}
Here is my PHP code. Please note this is only for testing purpose
<?php
$str = "<MerchantId>|order45608988|NA|300.00|NA|NA|NA|INR|NA|TypeField1|<ClientID>|NA|NA|TypeField2|Txtadditionalinfo1|Txtadditionalinfo2|http://google.com";

$checksum = hash_hmac('sha256',$str,"<secretkey>", false);
$checksum_value = strtoupper($checksum);

echo '<form action="https://pguat.billdesk.io/payments/ve1_2/orders/create" method="post" id="billdesk_payment_form">';
echo '<input type="hidden" name="MerchantId" value="<MerchantId>"/>';
echo '<input type="hidden" name="CurrencyType" value="INR"/>';
echo '<input type="hidden" name="SecurityId" value="<ClientID>"/>';
echo '<input type="hidden" name="txtCustomerID" value="order45608988" />';
echo '<input type="hidden" name="txtTxnAmount" value="300.00" />';
echo '<input type="hidden" name="txtAdditionalInfo1″ value="" />';
echo '<input type="hidden" name="RU" value="http://returnURL.com" />';
echo '<input type="hidden" name="CheckSumKey" value="<secretkey>"/>';
echo '<input type="hidden" name="CheckSum" value="'.$checksum_value.'"/>';
echo '<input type="hidden" name="msg" value="'.$str.'" />';
echo '</form>';

echo '';
?>

I have referenced the BillDesk docs and I am not getting exactly what changes I have to do.
Thank you in advance.

A: /* Billdesk has changed payment gateway. sample as given below */

/****
 config.php
*****/

    $MerchantID = "ABCDEF01";
    $ClientID = "abcdef01";
    $responseurl = "https://www.merchantwebsite.com/ru.php";
    $secretkey = 'xxxxxxxxxxxxxxxxxxxxxxxx';
    $returnURL = "https://www.merchantwebsite.com/paymentresponse.php";
    $billdesk_URL = "https://pguat.billdesk.io/payments/ve1_2/orders/create";

/****
 process.php
*****/

    use Firebase\JWT\JWT;

    /*****************************************/
        // Build headers
    /*****************************************/

    $headers = ["alg" => "HS256", "clientid" => $ClientID, "kid" => "HMAC"];

    $payload = [
      "mercid" => $MerchantID,
      "orderid" => $transaction_id,
      "amount" => $totalamount,
      "order_date" => $date_atom,
      "currency" => "356",
      "ru" => $responseurl,
      "additional_info" => [
        "additional_info1" => $CustomerID,
        "additional_info2" => $PaymentFor,
        "additional_info3" => "NA",
        "additional_info4" => "NA",
        "additional_info5" => "NA",
        "additional_info6" => "NA",
        "additional_info7" => "NA",
      ],
      "itemcode" => "DIRECT",
      "device" => [
        "init_channel" => "internet",
        "ip" => $ipaddress,
        "mac" => $macaddress,
        "imei" => $imei,
        "accept_header" => "text/html",
        "user_agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0",
        "fingerprintid" => $fingerprintid
      ]
    ];

    /*****************************************/
        // Encode payload
    /*****************************************/

    $curl_payload = JWT::encode($payload, $secretkey, "HS256", null ,$headers);

    /*****************************************/
        // Submit to Billdesk
    /*****************************************/
    $ch = curl_init( $billdesk_URL );
    $ch_headers = array(
        "Content-Type: application/jose",
        "accept: application/jose",
        "BD-Traceid: $transaction_id",
        "BD-Timestamp: $servertimeYYYYMMddHHmmss"
    );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $ch_headers);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $curl_payload);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

    $result = curl_exec($ch);
    curl_close($ch);

    /*****************************************/
        // Billdesk Response
    /*****************************************/

    $launch_billdesk = false;
    try {
        $result_decoded = JWT::decode($result, $secretkey, array('HS256'));
        $result_array = (array) $result_decoded;

        if ($result_decoded->status == 'ACTIVE') {
            $transactionid = $result_array['links'][1]->parameters->bdorderid;
            $authtoken = $result_array['links'][1]->headers->authorization;

            $launch_billdesk = true;   //write js code to launch sdk

        } else { // Response error
            echo "Response error";
        }

    } catch (\Exception $e) {
        echo "

Return signature validation FAILED: $e";
    }

/****
 paymentresponse.php
*****/

    use Firebase\JWT\JWT;

    /*****************************************/
        // Read POST data
    /*****************************************/
    $tx = "";
    if(!empty($_POST)) {
        $tx_array = $_POST;
        if (isset($tx_array['transaction_response'])) {
            $tx = $tx_array['transaction_response'];
        }
    } else {
        echo "

Invalid call
";
        die();
    }

    /*****************************************/
        // Signature validation
    /*****************************************/
    try {
        $result_decoded = JWT::decode($tx, $secretkey, array('HS256'));
        $result_array = (array) $result_decoded;
        $result_json =  json_encode($result_array,JSON_PRETTY_PRINT);
    } catch (\Exception $e) {
        //echo $e;
        echo "

Invalid response
";
        die();
    }

    /*****************************************/
        // Process info
    /*****************************************/
    if ($result_decoded->transaction_error_type == 'success') {

        $orderid = $result_decoded->orderid;
        $transaction_date = $result_decoded->transaction_date;
        $transactionid = $result_decoded->transactionid;    //payment transaction id
        $charge_amount = $result_decoded->charge_amount;

        /*  SAVE TO DB and send receipt     */
        $success = updateTransactionToDB($result_array);
        GenerateReceiptEmail($orderid, 1, $draftreceipt);

        echo "
Transaction was successful....
";
        echo "Transaction Date: $transaction_date
";
        echo "Transaction ID: $transactionid
";
        echo "Charge Amount: ₹$charge_amount
";

    } else { // Error
        $txerror = $result_decoded->transaction_error_type;
        $txid = $result_decoded->transactionid;
        echo "
Transaction FAILED....
";
        echo "Transaction Date: $transaction_date
";
        echo "Transaction ID: $transactionid
";
        echo "Charge Amount: ₹$charge_amount
";
        echo "Failure Reason: ₹$transaction_error_desc
";
    }


text:
Q: Qual melhor maneira de sincronizar dados app desktop com webapi? Tenho minha aplicação desktop que precisa enviar dados (só enviar) para uma webapi, esses dados não pode-se enviar repetivamente e também após enviado, não enviar novamente, a app desktop será em .net(wpf) a webapi também asp.net webapi.
A aplicação desktop estará em uma máquina com internet precária, então pode haver falha de envio a todo momento, conexão totalmente instavel.
Existe alguma biblioteca que me auxilie nessa sincronização? Lembrando que é apenas de envio(após enviado, não enviar mais).

A: Uma biblioteca, não sei se existe. Mas é fácil contornar isso.
Você terá que criar um identificador (caso já não exista) e uma propriedade para saber se já foi enviado. Quando você enviar um item, é só verificar se já não foi sincronizado. Senão foi enviado, envie, se der tudo certo, altere a propriedade informando que o item já foi enviado.
public class ObjetoSincronizado
{
    public ObjetoSincronizado()
    {
        this.SyncId = Guid.NewGuid();
    }

    public Guid SyncId { get; set; }

    public bool Sincronizado { get; set; }
}

Do lado da API, sempre que você receber um objeto, verifique se o mesmo já não existe pelo identificador, no caso acima, a propriedade SyncId, se ele já existir, você ignora a informação. Assim não haverá problema se receber duas vezes o mesmo item.


text:
Q: Stock price prediction, choosing amount of time in the future using scikit learn I'm trying to use machine learning to predict stock prices. I'm having issues choosing how long out to predict, I want to be able to predict out 100-200 days in the future. It seems like my code is cutting off the last 200 days and adding it's prediction there, instead of adding a additional 200 days of the prediction. For example if I have 1000 days of data I want the 1000 and the 200 0f the prediction, right now it's cutting off the last 200 and making it's prediction there instead. To make my question easier to understand, say I have a data set with integers 1,2,3,4,5,6,7,8,9,10, how do I tell the predict method I want the next 2, 10 or 20 integers in the series? I'm just starting out following a tutorial, and doing a bad job of it, it kind of just says put this here and that there, not much insight on what everything is doing. Not sure if LinearRegression is the best way to do it, would be happy with any insight you can provide, Thank you!
import pandas as pd
import math`enter code here`
import numpy as np
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from matplotlib import style

df = pd.read_csv('spyqqqq.csv')

df = df[['Open','High','Low','Adj Close','Volume']]

df['label'] = df['Adj Close'].shift(-200)

df.dropna(inplace=True)

X = np.array(df.drop(['label'],1))

y = np.array(df['label'])

X = preprocessing.scale(X)

X_lately = X[:-200]

X_train, X_text, y_train, y_text =  cross_validation.train_test_split(X,y, test_size=0.1)

clf = LinearRegression()

clf.fit(X_train, y_train)

accuracy = clf.score(X_text,y_text)

forcast = clf.predict(X_lately)

print("accuracy ",accuracy)
print("forcast ",forcast)

plt.plot(forcast,linestyle='solid',ms=0,color='blue')

plt.show()


text:
Q: SwiftUI list of different UI elements - fail I'm trying to present a list, of witch the first item is a NavigationLink, because its configuration needs some extra options to be defined. All other operations can be run w/o special parameters.
(Code stripped down a bit):
let operations = ["start", "stop", "set_marker", "save_map", "get_status"]

NavigationView {
    VStack {
        Form {
            Section(header: Text("Header")) {
                List(operations, id: \.self) { operation in
                    if operation == "start" {
                        NavigationLink(destination: DetailView(operation: operation)) {
                            Text(operation.uppercased())
                        }
                    } else {
                        Button(action: {
                            switch operation {
                            case "stop":
                                break
                            default:
                                break
                            }
                        }) {
                            Text(operation.uppercased()).foregroundColor(.black)
                        }
                    }
                }
            }
        }
    }
}

The thing compiles fine and displays fine too. At runtime I can click all "plain buttons" and it works. For the "start" entry I can open the second window just once. After return the "start" button does not react anymore. Any ideas?

A: Disregard. Seems to be an issue on emulator and in preview only.


text:
Q: How to show result of rake task in view file in Rails App I'm trying to create a parser based on Rails App and I use for this 'nokogiri'. I watched railscast by Ryan Bates about this but I don't understand how he integrated task with view.
For example: In my view file I press the button - task starts to collect information and shows this information on the same page. How can I do this?
My example task:
desc "example"
task :parsing => :environment do
  require 'rubygems'
  require 'nokogiri'
  require 'open-uri'

  page = Nokogiri::HTML(open('http://en.wikipedia.org/wiki/HTML'))
  page.css('div#content div#bodyContent table.infobox tr th').each do |el|
    puts el.text
  end
end

Or maybe I shouldn't use for parser rake task? Maybe I should put my parser in controller or in model or in helper?