text:
Q: Finding the min and max number of an array When I run this program, it finds the max number but always prints 0.0 as the minimum.
When I use Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY instead of setting smallest and largest to x[0], it works correctly.
Using Math.min and Math.max also gives me the same error but works with Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY as well. I looked at several other similar questions and I'm not allowed to use Array.sort or any of the other suggestions people post.
I just want to know why setting both variables to x[0] only ever works to find the largest number, whether I declare that variable first, second or set it equal (Double largest, smallest = x[0]).
public class MaxAndMin {
    public static void main (String[] args) {
        Scanner s= new Scanner(System.in);
        System.out.println("How many numbers would you like to enter?");
        int n= s.nextInt();

        double[] x= new double[n];
        double smallest= x[0]; //double smallest= Double.POSITIVE_INFINITY;
        double largest= x[0]; //double largest= Double.NEGATIVE_INFINITY;

        for (int i=0; i<x.length; i++) {
            x[i]= kbd.nextDouble();

            if (x[i] > largest) {
                largest = x[i];

            } else if (x[i] < smallest) {
                smallest = x[i];
            }
        }
        System.out.println("Smallest number: " + smallest + " Largest number: " + largest);
    }
}

A: When you initialize smallest and largest, you haven't put any values into x, so its elements are just the default values that the array was created with, i.e. zero.
Hence, you will only find a smaller smallest value if one is less than zero (or a larger largest value if one is greater than zero).
You should use the POSITIVE_INFINITY and NEGATIVE_INFINITY to initialize the values, since all values are smaller and larger than these respectively.

Alternatively, you can initalize smallest = largest = x[0] in the for loop when i == 0. However, the former approach is preferable, since it does not require checking i == 0 on every iteration.

Alternatively, you can move the first assignment out of the loop:
x[0] = smallest = largest = kbd.nextDouble();
for (int i = 1; i<x.length; i++) {
  x[i] = kbd.nextDouble();
  ...

This avoids checking i == 0 repeatedly, but you have to duplicate the kbd.nextDouble(). I'd still use the first approach.


text:
Q: Total number of li is not counting under ul I'm trying to count li in ul list, but don't know why its not counting
My html code:

Home

About Us

Services

Our Team

Portfolio

Clients

Blog

Contact

My Jquery function:
 var licount = $("ul#nitsmenu > li").length;
 console.log(licount);
 for (i = 0; i < licount; i++) {
    var lielem = $("#nitsmenu li").text();
    var element = $(lielem).text();
    $("#nitspopupmenu").html("

" + lielem + "");
 }

Even each function is not executing:
$("#nitsmenu li").each(function (i, lielem)

I don't know how it works. Even I'm using correct selectors. Please help. I've included the jquery function 1.12.2

A: Your code works well. You can work from the below
<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>

Home

About Us

Services

Our Team

Portfolio

Clients

Blog

Contact

A: You need to execute your code only when the document has loaded. This construct will do that:
$(function () {
    // your code comes here
});

Now, your code has several issues:
    var lielem = $("#nitsmenu li").text();

This line appears in a loop, yet it will always return the text of the first li element.
    var element = $(lielem).text();

This is wrong, you use the LI's text content (see above) as if it is an element (selector). That will not work.
    $("#nitspopupmenu").html("

" + lielem + "");

Here you inject HTML that is not valid: it has several unclosed tags. But more importantly: you overwrite the HTML in each iteration, and so only the last iteration will determine which the HTML is of #nitspopupmenu.
Here is suggested code, although I don't know what you actually wanted to put in nitspopupmenu:
$(function () {
    var html = '';
    $("ul#nitsmenu > li").each(function () {
        // 'this' refers to current LI element
        var txt = $(this).text();
        // collect HTML
        html += "
"
                 + txt + "
";
    });
    // Put HTML only once:
    $("#nitspopupmenu").html("
" + html + "
");

});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Help with a event handler that doesn't fire HALP! This is my first attempt at this kind of thing. It seems that the function won't fire when the event happens.
(Eventually, what's supposed to happen is that when the event
Mage::dispatchEvent('nextbits_form_save_after',array('form_data'=>$params, 'form_model'=>$formModel));
occurs, the form data will be routed to appropriate people based on the data contained in the form.....)
I haven't written that code yet, but I don't see the observer catching the event and doing anything at all. What is the problem with my event/observer structures?
Observer.php:
[\app\code\local\Westcott\EmailRouter\Model\Observer.php]
<?php

class Westcott_EmailRouter_Model_Observer {

    public function Notify_by_Mail($observer){

        if (isset($observer['form_data'])) {
            $form_data = $observer['form_data'];
            //$form_model = $observer['form_model'];

            foreach ($form_data as $key =>$fd) {
                //Do something with the form data
                echo "K: ".$key." => ".$fd."
";
            }
            /*
            foreach ($form_model as $key =>$fm) {
                //Do something with the form data
                echo "K: ".$key." => ".$fm."
";
            }
            */
        } else {
            //Do something else with the form data...
        }

    }

    echo "Hello!!";
}

Westcott_EmailRouter.xml:
[\app\etc\modules\Westcott_EmailRouter.xml]
<?xml version="1.0"?>
<config>
  <modules>
    <Westcott_EmailRouter>
        <active>true</active>
        <codePool>local</codePool>
    </Westcott_EmailRouter>
  </modules>
</config>

config.xml:
[\app\code\local\Westcott\EmailRouter\etc\config.xml]
<?xml version="1.0"?>
    <config>
        <modules>
            <Westcott_EmailRouter>
                <version>0.1.0</version>
            </Westcott_EmailRouter>
        </modules>
        <global>
            <models>
                <emailrouter>
                    <class>Westcott_EmailRouter_Model</class>
                </emailrouter>
            </models>
            <events>
                <nextbits_form_save_after>
                    <observers>
                        <Westcott_EmailRouter>

                            <class>westcott_emailrouter/observer</class>
                            <method>Notify_by_Mail</method>
                        </Westcott_EmailRouter>
                    </observers>
                </nextbits_form_save_after>
            </events>
        </global>
    </config>

A: Hello There are issue in  events tags... model class declaretion
also  Notify_by_Mail is not exiting in observer.php
....
<observers>
                        <westcott_emailRouter>

                            <class>emailrouter/observer</class>
                            <method>doNotifyBySubmittedContent</method>
                        </westcott_emailRouter>
                    </observers>
...

A: First make sure the event your observing exits:
grep -rin -B2 -A2 "Mage::dispatchEvent" app/* > events.txt

View events.txt and search for nextbits_form_save_after
Second, as others mentioned your observer method isn't defined in your Observer.php
<method> should be doNotifyBySubmittedContent instead.
You can also get a list of events with a quick core hack:

*

*Where can I find a complete list of Magento events?
You may also want to verify that the eventDispatch you're trying to observer is in fact being called during the stack as well.
* EDIT *

$observer will not have ['form_data'] you'll need to get the Event Request.
$request = $observer->getEvent()->getRequest()->getParams();
if(is_set($request['form_data'])) {

* EDIT #2 *

Just realized I had getParams() as the dispatched Event is magic getter/setter NOT a URI request.
Something like this should work if you're sure the event is being dispatched and form data is present:
$event = $observer->getEvent();
$formData = $event->getFormData(); // magic get/set
$formModel = $event->getFormModel(); // magic get/set
zend_debug::dump($formData);
zend_debug::dump($formModel);


text:
Q: Reply-to header in contact form PHP // Subject of your email
$subject = $_REQUEST['subject'] . ' - Personal website contact form submittion.';
// Recipient's E-mail
$to = 'recipient@domain.com';

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Sender's E-mail
$headers .= "From: Contact Form (Domain.com) <no-reply@domain.com>";
$message .= 'Name: ' . $_REQUEST['name'] . "
";
$message .= 'Email: ' . $_REQUEST['email'] . "
";
$message .= 'Message: ' . $_REQUEST['message'] . "
";

if (@mail($to, $subject, $message, $headers)) {
    // Transfer the value 'sent' to ajax function for showing success message.
  echo 'sent';
} else {
  // Transfer the value 'failed' to ajax function for showing error message.
  echo 'failed';
}

How do I put reply-to header here?
Reply-to email should be the email that person enters while filling up the form, I don't know PHP can anyone help me out? thanks

A: <?php
$subject = $_REQUEST['subject'] . ' - Personal website contact form submittion.'; // Subject of your email
$to = 'recipient@domain.com'; //Recipient's E-mail

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: Contact Form (Domain.com) <no-reply@domain.com>\r\n"; // Sender's E-mail
$headers .= "Reply-To: ".$_REQUEST['email']."<". $_REQUEST['email'].">\r\n" .
$message .= 'Name: ' . $_REQUEST['name'] . "
";
$message .= 'Email: ' . $_REQUEST['email'] . "
";
$message .= 'Message: ' . $_REQUEST['message'] . "
";

if (@mail($to, $subject, $message, $headers))
{
    // Transfer the value 'sent' to ajax function for showing success message.
    echo 'sent';
}
else
{
    // Transfer the value 'failed' to ajax function for showing error message.
    echo 'failed';
}
?>


text:
Q: How to find the inverse arc in the configuration space The following Figure shows the function from configuration space (Torus) to operational space (Annulus).

There is a naturally defined continuous function from configuration space $(\theta_A, \theta_B)$ to operational space $f(\theta_A, \theta_B)$. If any of $\theta_A$ and $\theta_B$ varies, chalk at the end of rod B draws an 'arc',
Supposing we have an arc in operational space and we want to find its inverse arc in configuration space. Here are two simple examples:

The problem is how can we find the arc of the configuration space (i.e. $\theta_A=f(\theta_B)$ for the following two operational space?:

All I have approached is a little knowledge:
$1-$ the coordinate $(x,y)$ of the end point can be determined through:
$x={l_A}{\cos\theta_A}+{l_B}{\cos(\theta_A+\theta_B)}$ and $y={l_A}{\sin\theta_A}+{l_B}{\sin(\theta_A+\theta_B)}$.
$2-$ The polar equation of the left picture is $r^2−2{l_B}r\cos(\theta)+{l_B}^2={l_A}^2$. But $\theta$ is in operational space, nothing to say about $(\theta_A,\theta_B)$ in configuration space (?)
How it is possible to find the relation between $\theta_A$ and $\theta_B$ such that results in the mentioned arcs?
I don't have any clue how to solve it. I would highly appreciate any helps. Thank you.

A: I'll write $(x, y)$ or $(r, \theta)$ for the coordinates of the point in the operational space, respectively in cartesian or polar coordinates.
First important remark : the map $(\theta_A, \theta_B) \mapsto (x,y)$ shears and then flatten the torus onto the annulus. The shearing part is bijective, and the "flattening" is two-to-one, except on the boundary of the annulus where it is one-to-one. Hence, there will be in general two possible choices of $(\theta_A, \theta_B)$ for any given position of the chalk. If $(\theta_A, \theta_B)$ works, then by symmetry, so does $(2\theta-\theta_A, -\theta_B)$.
To make things a bit clearer, I'll write $a$, $b$ instead of $l_A$, $l_B$.
I - Finding $\theta_B$
By Al-Kashi's theorem (the law of cosine),
$$r^2 = a^2+b^2+2ab\cos(\theta_B).$$
Among the two possible set of parameters for a given position, there is always exactly one with $\theta_B \in [0, \pi]$. I choose to compute this position. Then:
$$\theta_B = \arccos \left( \frac{r^2-a^2-b^2}{2ab} \right),$$
and:
$$\sin(\theta_B) = \frac{\sqrt{(r-a+b)(r+a-b)(a+b-r)(a+b+r)}}{2ab}.$$
I think this formula can also be deduced from the law of sine and Heron's formula for the area. If you choose the other value of $\theta_B$, which lies in $[-\pi, 0]$, then $\sin(\theta_B)$ becomes the opposite of the value above.
II - Finding $\theta_A$
Now, let's develop the equations giving $x$ and $y$:
$$\begin{cases}
x & = & a \cos (\theta_A) + b \cos (\theta_A+\theta_B) \\
y & = & a \sin (\theta_A) + b \sin (\theta_A+\theta_B)
\end{cases}$$
becomes:
$$\begin{cases}
x & = & [a + b \cos (\theta_B)] \cos (\theta_A) - b \sin(\theta_B) \sin(\theta_A) \\
y & = &  b \sin (\theta_B) \cos (\theta_A) + [a + b \cos (\theta_B)] \sin (\theta_A)
\end{cases}$$
If we replace $\cos(\theta_B)$ by its expression we found at the beginning, we see that each column has norm $r$. So, by dividing by $r$, we get:
$$\begin{pmatrix}
\cos(\theta) \\ \sin(\theta)
\end{pmatrix}
= \begin{pmatrix}
\frac{a+b\cos(\theta_B)}{r} & -\frac{b \sin(\theta_B)}{r} \\
\frac{b \sin(\theta_B)}{r} & \frac{a+b\cos(\theta_B)}{r}
\end{pmatrix}
\begin{pmatrix}
\cos(\theta_A) \\ \sin(\theta_A)
\end{pmatrix}$$
Since the 2x2 matrix is a rotation matrix, it is enough to transpose it to get its inverse, whence:
$$\begin{pmatrix}
\cos(\theta_A) \\ \sin(\theta_A)
\end{pmatrix}
= \begin{pmatrix}
\frac{a+b\cos(\theta_B)}{r} & \frac{b \sin(\theta_B)}{r} \\
-\frac{b \sin(\theta_B)}{r} & \frac{a+b\cos(\theta_B)}{r}
\end{pmatrix}
\begin{pmatrix}
\cos(\theta) \\ \sin(\theta)
\end{pmatrix}.$$
From here, finding $\theta_A$ is just a matter of computing an angle from its sine and cosine.
III - Parametrization of the circle
If you have an arc in operational space and you want to compute a time-dependent parametrization $(\theta_A, \theta_B) (t)$ which follows the arc you want, all you have to do is to compute pointwise $\theta_B$ and $\theta_A$ with the recipe above. However, it can be quite tedious, especially for the special case where everything can be made explicit.
I won't deal with your arc $p_2$, as I don't have an equation for this curve. That said, let's have a look at $p_1$. It is a circle of radius $a$ and center $(b, 0)$. Since it makes a full turn around the origin, the parameter $\theta_A$ must also make a turn. I'll assume that one can do so monotonically, i.e. one can take $\theta_A (t)= t$. Let $f(t)$ be the value of $\theta_B$ at time $t$. Then:
$$\begin{cases}
x (t) & = & a \cos (t) + b \cos (t+f(t)) \\
y (t) & = & a \sin (t) + b \sin (t+f(t))
\end{cases}$$
But since $(x,y)$ belongs to the circle,
$$(x-b)^2+y^2=a^2$$
Replace $x$ and $y$ by the functions of $t$, develop, simplify a lot, and get:
$$b(1-\cos(f(t)+t)) + a(\cos(f(t))-\cos(t)) = 0,$$
which, with the help of some trigonometric formula, yields:
$$\sin \left(\frac{f(t)+t}{2} \right) \left[ b \sin \left(\frac{f(t)+t}{2} \right) - a \sin \left(\frac{f(t)-t}{2} \right) \right] = 0.$$
The equation above has one obvious solution: $f(t) = -t$. Hence, if you input $(\theta_A, \theta_B) (t) = (t, -t)$, you will draw the curve $p_1$. The second branch is more delicate to compute. By developping the sine, we get:
$$(a+b) \sin \left(\frac{t}{2} \right) \cos \left(\frac{f(t)}{2} \right)  = (a-b) \cos \left(\frac{t}{2} \right) \sin \left(\frac{f(t)}{2} \right),$$
whence:
$$\tan \left(\frac{f(t)}{2} \right)  = \frac{a+b}{a-b} \tan \left(\frac{t}{2} \right).$$
Finally, we get:
$$f(t) = 2 \arctan \left( \frac{a+b}{a-b} \tan \left(\frac{t}{2} \right) \right),$$
which is well-defined for $t \neq \pi$ (but that is not a problem, as $f(\pi) = \pi$ necessarily).

A: In complex numbers, your planimeter measures $f(\theta_A, \theta_B) = A e^{i \theta_A} + B e^{i(\theta_A + \theta_B)} $.  There doesn't seem to be any restriction on the angle so $0 \leq \theta_A, \theta_B < 2\pi$.  Maybe it will be easier to use $\theta_{B'} = \theta_A + \theta_B$ and the configuration space will still be the same torus "twisted".
Your image will be the Minkowski sum of the two circles of radius $A$ and $B$ and the result is that $f$ is a 2-1 map from the torus to an annulus.  except at the edges where it's 1-1.  It's like loooking at a donut with radii $A,B$ from the top.

How to compute $f^{-1}$ ?
The $f(\theta_A + \delta , \theta_{B'} + \delta) = e^{i\delta}f(\theta_A , \theta_{B'} )  $.  This means rotating the annulus is the same as moving diagonally in the donut in the NE diagonal direction $(1,1)$.
The radius can be computed from the Law of cosines: $|f(\theta_A, \theta_B)| = A^2 + B^2 + 2AB \cos \theta_B $

A reasonable thing to do would be draw the torus in 3D and plug into the equation of your circle of interest.
$(\theta,\phi) \mapsto (  (A + B \sin \theta) \cos \phi, (A + B \sin \theta ) \sin \phi, B \cos \theta) $


text:
Q: Flutter: How do I make an image overlay? Is there any way for me to overlay images(wherein you use a background image and you put another image in front of it) in flutter?. Ive tried doing it in columns inside of a container, but it doesnt seem to be working. Any advices or tips? I appreciate all the help :)

A: Try out below example for more idea:-
Stack(
  children: <Widget>[
    Container(
      width: 100,
      height: 100,
      color: Colors.red, // replace it with image
    ),
    Container(
      width: 90,
      height: 90,
      color: Colors.green,// replace it with image
    ),
    Container(
      width: 80,
      height: 80,
      color: Colors.blue, // replace it with image
    ),
  ],
)


text:
Q: C - Dynamic array of 'struct' elements Based in this post I tried to do a dynamic array but, istead of a int array, an array of an struct designed in the program.
I can't make it work and I'd like to know where are my mistakes (mostly beacuse of working with pointers)
Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

//////////////////////////////////////

typedef struct {

  int group[8];
  uint64_t points;

} BestGroup;

//////////////////////////////////////

typedef struct {
  BestGroup *array;
  size_t used;
  size_t size;
} Array;

void initArray(Array *a, size_t initialSize) {
  a->array = (BestGroup *)malloc(initialSize * sizeof(BestGroup));
  a->used = 0;
  a->size = initialSize;
}

void insertArray(Array *a, int group_add, uint64_t points_add) {
  // a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
  // Therefore a->used can go up to a->size
  if (a->used == a->size) {
    a->size *= 2;
    a->array = (BestGroup *)realloc(a->array, a->size * sizeof(BestGroup));
  }

  int i;

  for (i = 0; i < 8; i++)
  {
    a->array[a->used][i].group[i] = group_add;
  }
  a->array[a->used].points = points_add;
  a->used++;
}

void freeArray(Array *a) {
  free(a->array);
  a->array = NULL;
  a->used = a->size = 0;
}

///////////////////////////////////////////////////////////////////////////////

int main()

{
    Array a;
    int i;
    int list[8] = {0, 1, 2, 2, 4, 5, 6, 7};

    initArray(&a, 5);  // initially 5 elements
    for (i = 0; i < 100; i++)
      insertArray(&a, list, i);  // automatically resizes as necessary
    printf("%d\n", a.array.group[1]);  // print 2nd element
    printf("%lu\n", a.used);  // print number of elements
    freeArray(&a);
}

A: There are 3 typos:
void insertArray(Array *a, int group_add, uint64_t points_add)

should be
void insertArray(Array *a, int *group_add, uint64_t points_add)

You want to add an array of elements, so you have to give the function a pointer to the elements.
you edited this part while I wrote this answer to compensate the compile time error because of the first typo:
a->array[a->used][i].group[i] = group_add[i];

or (your second version):
a->array[a->used][i].group[i] = group_add;

should be
a->array[a->used].group[i] = group_add[i];

a->array[a->used] is already an object of the struct, no need to dereference it once again.
and last but not least
printf("%d\n", a.array.group[1]);

should be
printf("%d\n", a.array->group[1]);

a.array is an array, so to get the first element, you can do a.array->group... or a.array[0].group...
a complete version: https://ideone.com/0WiXwO


text:
Q: Android Nearby Connection API not available for specific devices I am building an Android app making communication between two devices.
For this purpose, I am using Google Nearby Connection API and everything is working fine so far.
But specifically on Xiaomi 10X pro, the advertising cannot be established.
Following error is returned:
 com.google.android.gms.common.api.ApiException: 17: API: Nearby.CONNECTIONS_API is not available on this device.
    at com.google.android.gms.common.api.internal.zad.zaa(Unknown Source:4)
    at com.google.android.gms.common.api.internal.zaf.zaa(Unknown Source:16)
    at com.google.android.gms.common.api.internal.GoogleApiManager$zaa.zac(Unknown Source:175)
    at com.google.android.gms.common.api.internal.GoogleApiManager$zaa.onConnectionFailed(Unknown Source:95)
    at com.google.android.gms.common.api.internal.GoogleApiManager$zaa.connect(Unknown Source:219)
    at com.google.android.gms.common.api.internal.GoogleApiManager$zaa.zaa(Unknown Source:112)
    at com.google.android.gms.common.api.internal.GoogleApiManager.handleMessage(Unknown Source:145)
    at android.os.Handler.dispatchMessage(Handler.java:103)
    at com.google.android.gms.internal.base.zap.dispatchMessage(Unknown Source:8)
    at android.os.Looper.loop(Looper.java:224)
    at android.os.HandlerThread.run(HandlerThread.java:67)

The code used to advertise is not far from the Google documentation:
private fun startAdvertising() {
    AdvertisingOptions.Builder()
      .setStrategy(Strategy.P2P_POINT_TO_POINT)
      .build()
      .also { options ->
        Nearby
          .getConnectionsClient(context)
          .startAdvertising(
            "card",
            "com.app.my",
            connectionLifecycleCallback,
            options
          )
          .addOnSuccessListener {
            FL.d("Advertising with success")
          }
          .addOnFailureListener { e: Exception? ->
            FL.e("Advertising failed", e)
          }
      }
  }

I am digging the internet since but with no success.
I cannot figure why Nearby Connection API would not be available for this specific device / model.
Has anybody already encountered such issue ?

A: As stated by @Xlythe, the device was bought on Chinese market and thus did not have Play Services installed at first.
After adding Play Store and Play Services, everthing works like a charm.


text:
Q: MultiValueDictKeyError in sending an attachment

I look at Django official documentation and tried to do what is written there.
View.py:
if request.POST:
    form = EscalationForm(request.POST, request.FILES)
    if form.is_valid():
        escalation_message = form.save(commit=False)
        handle_uploaded_file(request.FILES['file'])
        escalation_message.save()

And handle_uploaded_file is exactly the same;
def handle_uploaded_file(f):
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

EscalationForm.py:
class EscalationForm(forms.ModelForm):
    class Meta:
        model = EscalationMessage

and my model is:
class EscalationMessage(models.Model):
    file = models.FileField(null=True, blank=True, upload_to='.')

Also, I added these into my settings.py;
FILE_UPLOAD_HANDLERS = [
    "django.core.files.uploadhandler.MemoryFileUploadHandler",
    "django.core.files.uploadhandler.TemporaryFileUploadHandler"
]

However when I tried to send attachment it gave
File "/Users/mk/Documents/interaction/views.py", line 169, in create_escalation_message
    escalation_message.file = EscalationMessage(file=request.FILES['file'])
  File "/Users/mk/Documents/venvs/lib/python2.7/site-packages/django/utils/datastructures.py", line 322, in __getitem__
    raise MultiValueDictKeyError(repr(key))
MultiValueDictKeyError: "'file'"

I am new in web development and I am writing a mini-demo. I was trying to send a message with an attachment and I searched an example however, it gave this error. Do you have any idea about the error?
Thank you

A: File uploads must use POST method. Change your form tag to:
<form action="" method="post" class="escalation-form" enctype="multipart/form-data">


text:
Q: How can I export a mongo database handler in Node.js? I am new to Node and Mongo, I was trying to connect to a mongo database in one file and export the database handler to many other files, so that I need not to connect to the database in all files which need a connection to it. Here is how I attempted to do it
// db.js
var client = require('mongodb').MongoClient
var assert = require('assert')
var url = 'mongodb://localhost:27017/test'

client.connect(url, (err, db) => {
  assert.equal(err, null)
  module.exports = db
})

After exporting the db handler, I tried to access methods on it in another file as follows
var db = require('./db')
console.log(db.collection('col'))

but it throws a TypeError, saying that db.collection is not a function. How can I access the methods on db handler in other files?

A: you need to export function and it need callback1. when  the wanted parameter can't get, set the callback1 to callback2 about the async function.
db.js
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
let callback, db;
// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  db = client.db(dbName);
  callback(db)

  client.close();
});

module.exports = function(cb){
  if(typeof db != 'undefined' ){
    cb(db)
  }else{
    callback = cb
  }
}

other.js
const mongo = require("./db");
mongo((db) => {
     //here get db handler
})

A: Probably best bet is to just export an init() function with a callback and then call that before you use the other db methods.  Otherwise you could try to check that its initialized at the top of each db access method but that is probably not actually a more maintainable solution since it makes it more complicated.


text:
Q: My flutter builds not showing in App Store connect I archive my flutter app dozen of times but It's always like this

I tried a few solutions: Add App icon, update Xcode, enable bitcode but nothing works.
Thanks.


text:
Q: Where to put constants, parameters, etc. in Python code for research? Context: I'm currently implementing a predictive model of some environmental process. Imagine a model that computes some ecosystem's reaction to different temperatures if you want.
This is the first time I do something like this in Python, and I am kinda usure about how to organize my files. I have read related questions, but they mostly seem to be about different use-cases and/or deal with more in-depth questions, not about where to put constants, parameters, etc.
To give you an example of what I have now:
constants.py:
# these should never be touched
CONST1 = 1
CONST2 = 2
# etc

parameters.py:
# these can and should be changed by the user
par1 = 1
par2 = 2
par3 = 3
# etc

model.py:
# here are the model's functions
import constants as c

def fun1(par1, par2):
    res1 = c.CONST1 * par1 + par2
    return res1

def fun2(par2, par3):
    res2 = c.CONST2 * par2 + par3
    return res2
# etc

main.py:
# this file is used to run the model
import model as m
import parameters as p

res1 = m.fun1(p.par1, p.par2)
res2 = m.fun2(p.par2, p.par3)
# plot results etc

Is it a good idea to keep constants, parameters and functions in separate files like this, or should at least the constants be global variables in model.py since I don't touch them anyway? Is the "extreme case" of a one-file-solution (constants, parameters, models and a main-function in one .py) considered bad style? What about variables that pretty much any function uses (e.g. time, or the constants that I import in model.py): Should I explicitly pass them to every function, or can/should I make them global?
TL;DR: If there is any best practice for how to organize projects like this, please help a newbie programmer out.

A: This question is primarily opinion-based, but I'll give this a try.
If you don't want to give the user access to constants, only to parameters, you are pretty much doing it right (one file for constants and a separate one for params).
If you don't mind the user being able to change constants, I would advise to have a single file named settings.py, from where you import your constants and whatnot. Remember that Python allows selective importing, which means that if you only need 1 constant inside one of your .py files, you can import that single constant, so it's not a matter of efficiency. I would not keep all constants in a single file, unless the project is small.
Apart from that, I would also advise that you store model-specific variables / constants as static properties inside the model class. For example, we could have a school grade model defined like this:
class GradeModel(BaseModel):
    GRADE_TYPES = (
        (1, 'Exam'),
        (2, 'Final Paper'),
    ) # this is just an example

    id = IntFieldType()
    student_id = IntFieldType()
    type = ChoiceType(choices=GRADE_TYPES)
    value = IntFieldType()

This way, you could call the grade type constant as GradeModel.GRADE_TYPES. Note that the above code is more like pseudo-code, because models are primarily dependent on which framework / library you're using, but you get the gist of it.


text:
Q: How to find the origins of a Threading.ThreadHelper.ThreadStart() method I have a .NET 3.5 client/server application that is accessed via RDP on a local network running on a windows 2003 server.  When using one portion of the product, the screen freezes periodically when none of the code I've written is actually executing.  I've run a profiler on the server using the latest source code, etc. and when the delay happens (10 second delay), there is no processor time being used, and no code of mine executed.
Using the Profiler I found a Stack Trace beginning with the generic Threading.ThreadHelper.ThreadStart() method.  It doesn't tell me what originated the method call, and until I know that I don't know how I'm going to find what's gone wrong.  The stack trace follows down through methods such as System.Net.ServicePoint.ReleaseAllConnectionGroups() and System.Net.Sockets.Socket.Close(int timeout).  We use web service calls, but none of them are asynchronous and none of them are being called anywhere near the time of the delay.
There is a delay caused by some kind of network timeout, but I can't tell from where I'm originating the call.  I'm hoping if I can determine where the Threading... method originates, I can figure out what's going wrong.  I have no idea where to start.

A: Don't look at a thread you didn't start, that one can't freeze the window updates.  Look at your main thread, find out what it is blocking on.  If that doesn't help, post the actual stack trace of that thread in your question instead of describing it.

A: Apart from the OP's reasons for asking this question I was able to see the stack trace of the original thread using Visual Studio's Threads window accessible through main menu:
 Debug->Windows->Threads


text:
Q: Какой сервис использовать для отлова краша и ошибок в Android Используя Fabric для дебажинга удаленных телефонов. Если возникают ошибки то я получаю их. На днях столкнулся с не приятной ситуацией. Приложение высылает логи в том случае если приложение запустилось.
Есть ли сервис или библиотека для отлова краша, чтобы она работала после того как краш случится.
Допустим запустил приложение и сразу получил ошибку прямо на старте "Приложение остановленно".
В таком случае FABRIC.IO НЕ РАБОТАЕТ!. И как быть теперь((

A: Недавно занимался разбором данного вопроса. Советую https://console.firebase.google.com (вообще много чего умеет) и https://www.bugtags.io/
В случае второго - в классе унаследованного application в методе onCreate() вы инициализируете и запускаете эту утилиту. Если краш случился до инициализации - то естественно врятле отловит, но можно уже сказать, что скорее всего проблема на стороне пользователя


text:
Q: How to create a custom Pane for use in SceneBuilder where controls layout correctly I am trying to provide some default behavior to a standard Pane in Java FX.  I would like to use this Pane in SceneBuilder.  For some reason the layout isn't working as I would expect.
I created the following component:
public class GroupBox extends Pane {
    public void configureGroupBox(String title) {
           //Perform needed set up here.....
    }
}

I have exported this control into a JAR file and imported that control into SceneBuilder.  I am able to select this control in SceneBuilder and add it to my FXML.
However, the problem starts when I attempt to add controls within it.  Even though this extends a javafx.scene.layout.Pane the layout engine of SceneBuilder is pushing all controls to the top left and overlapping them, rather than having no layout instructions.
Is what I am trying to do possible?  If so, is there something else I need to do?  At this point, my control is just an empty extension of the Pane class.
Thanks.

A: That is a Scene Builder limitation.
SB provides full operation for builtin containers only (i.e. the ones that are part of JavaFX). For custom containers, it provides limited operations: typically SB allows to drop a component inside but not to move it (because it considers that extending Pane does not imply free positioning of children).


text:
Q: Why is downloading over USB so slow? Why does downloading to flash memory over USB seem to be disastrously slower than to the hard drive?
I was downloading a file from rapidshare.com using the Firefox addon DownThemAll. First I tried downloading directly to my USB flash drive over USB 2.0, which has a theoretical bandwidth of 480 Mbit/s, but the download got stuck at about 20 kb/s.
When I tried downloading the same file to a different location, /tmp on the hard drive, the download easily reached speeds of over 1MB/s.
How can you explain this difference if the bottleneck can't possibly be the USB 2.0 bus?

A: It's a Firefox bug :-(
https://bugzilla.mozilla.org/show_bug.cgi?id=623866
It's been around for a while, but nobody cares enough to fix it.

A: USB flash drives are often very slow, pitifully slow. It's really that simple. It doesn't matter how fast the USB is if the flash is slow. The typical USB flash drive is an 8-lane superhighway that leads to a narrow alley.
I've actually seen USB flash drives that benchmark at 100KB/s. Though these days even the cheap ones typically hit 3MB/s.

A: The theoretical bandwidth limit of 480mbps for USB2.0 is simply the available bandwidth, not the actual speed devices perform at. The speed that USB devices perform at are based on the performance of the device itself. If you have a slower (read: CHEAPER) flash drive, it will run like garbage. If you properly research and find a flash drive with good performance, you will get that. Just like any device that is used for data transfer, it has speed ratings and speficifications.
Example: http://www.memoryexpress.com/Products/MX29701 (Rated for UP TO 27MB/s write, UP TO 25MB/s read)


text:
Q: traefik multiport endpoint routing I have a docker in a swarm mode and the image, that uses ports 80 for websockets and 8000 port for http.
This config makes traefik to sticky loadbalance between them, but i need different mappings - 443 TLS for http@8000 port and 80 TLS for ws@80 port.
Strictly. Probably with different LB modes on each.
Anyone can explain the way this can be achieved?
Thanx!
Initial wrong webapp container labels:
deploy:
  labels:
    - "traefik.backend.loadbalancer.stickiness=true"
    - "traefik.backend.loadbalancer.swarm=true"
    - "traefik.backend=webapp"
    - "traefik.docker.network=webapp-out"
    - "traefik.entrypoints=http,https"
    - "traefik.frontend.passHostHeader=true"
    - "traefik.ws.frontend.rule=Host:host.domain.local"
    - "traefik.ws.port=80"
    - "traefik.web.frontend.rule=Host:host.domain.local"
    - "traefik.web.port=8000"
    - "traefik.enable=true"

A: Try changing web in
- "traefik.web.frontend.rule=Host:host.domain.local"
- "traefik.web.port=8000"

to something else, the name is used by the deprecated web provider.

A: There is a backend mess with load balancer with sticks to one node.
The right way to have a different backends to serve requests from different entryPoints:
deploy:
  labels:
    - "traefik.backend.loadbalancer.stickiness=true"
    - "traefik.backend.loadbalancer.swarm=true"
    - "traefik.backend=no_matter"
    - "traefik.docker.network=webapp-out"
    - "traefik.entrypoints=http,https"
    - "traefik.frontend.passHostHeader=true"
    - "traefik.port=80" #No matter this section. It will be discarded.
    - "traefik.ws.frontend.rule=Host:host.domain.local"
    - "traefik.ws.backend=ws_app"
    - "traefik.ws.backend.loadbalancer.stickiness=true"
    - "traefik.ws.backend.loadbalancer.swarm=true"
    - "traefik.ws.frontend.entryPoints=http"
    - "traefik.ws.port=80"
    - "traefik.web.frontend.rule=Host:host.domain.local"
    - "traefik.web.frontend.entryPoints=https"
    - "traefik.web.backend=web_app"
    - "traefik.web.backend.loadbalancer.stickiness=true"
    - "traefik.web.backend.loadbalancer.swarm=true"
    - "traefik.web.port=8000"
    - "traefik.enable=true"


text:
Q: Proper way to terminate a process in python when it may lock resources I use simple method from mans:
process_one.start()

# process work here and may call lock, and when it locked some resources
# we call terminate, is it ok?

process_one.terminate()
process_one.join()

I am afraid if use that scheme it may lock program. For example if process_one will call another processes and threads inside.
Do you know a way to terminate it properly: with "sub"processes and even when it lock some res inside subprocesses ant subthreads?


text:
Q: How to take JMC output into a file? I want to log the output of Java mission control console in a file (txt or xml) so that I can get the file for putting it into Splunk.
.
Referring to https://docs.oracle.com/javacomponents/jmc-5-5/jmc-user-guide/logging.htm#JMCCI129 I tried to made the changes, but it did not work.
Does anyone know how to do this?
Thanks in advance.


text:
Q: How to subtract values of two columns and add to a new column in text file using awk/bash script I want to subtract the values from two columns and add result into a new column (at the very end) using awk or bash. the data is in a txt file.
I tried
awk 'BEGIN {OFS="\t"} NR == 1 {$20 = "tr_pe"} NR >=2 {$20= $5-$11}1' <filename

or
awk OFS="\t" \{$(NF+1)=$5-$11}1' filename.txt

The first code did the subtraction but saved it in column 2 instead of at the end, and I realised that it actually did not get saved to the txt.file. Second one did some calculation but it was not accurate
What I want to do - subtract values from column 5 with column 11 and save it under header tr_pre (which falls into column 20 at the end of all the 19 columns in the file). Columns are separated by tab.

A: You could use next after line 1 to continue the iteration. To print the result at the end, you can print the whole line using $0 followed by the value that you want at the end.
cat filename.txt

c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 c16 c17 c18 c19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

For example
awk 'BEGIN {OFS="\t"}
{$1=$1}
NR == 1 {
  print $0, "tr_pre"
  next
}
{
  print $0, $5-$11
}' filename.txt > output.txt

output.txt
c1  c2  c3  c4  c5  c6  c7  c8  c9  c10 c11 c12 c13 c14 c15 c16 c17 c18 c19 tr_pre
1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19  -6

A: Based on your description, this should solve your problem.
awk 'BEGIN {FS=OFS="\t"} NR == 1 {print $0, "tr_pre"} NR >=2 {print $0, $5 - $11}' filename.tsv > file_with_new_tr_pre_column.tsv

If there are other confounding factors, please provide a minimal reproducible example

A: $ awk '{print $0 "\t" (NR==1?"tr_pre":$5-$11)}' oldfile > newfile


text:
Q: Connecting GitHub to Shiny Server I am trying to set up a shiny server with the manual of Dean Attali. So far I made the shiny server work. This should be proofed by the fact that the "Welcome to Shiny Server" page shows up when I navigate to the server ip. The problem is that I cannot connect my shiny server to GitHub like in step 8.2 of the manual. I tried it a several times now, but I am getting this error message:

error: src refspec master does not match any.
error: failed to push some refs to 'origin'

This is my code:
sudo apt-get -y install git
cd /srv/shiny-server
git init
echo "# shiny-server" >> README.md
git commit -m "first commit"
git config --global user.email "user@user.com"
git config --global user.name "gituser"
git remote add origin git@github.com:gituser/shiny-server.git

The email address "user@user.com" and the user name "gituser" are just dummies.
I already deployed the fitting key in the repository settings in GitHub.
Hope that you can help me! Thanks in advance :)

A: There is a step missing here:

git init
echo "# shiny-server" >> README.md
git commit -m "first commit"

The missing step is a git add, to add the README.md to Git.
Without the git add step, git commit did nothing. As such, the repository doesn't have any commits, and therefore there's nothing to push,
resulting in the error that you observed.
This way it will work:
git init
echo "# shiny-server" >> README.md
git add --all
git commit -m "first commit"


text:
Q: How can I unjoin a join table relationship in rails/console? I have Users who have and belong to many Objects.
So if I type :
User.find(2).objects

A series of objects will return.
How can I clear the relationship this User has with those objects, but not delete the objects.

A: All I know is to hit this from both sides like so :
First this :
@a = User.find(2)
@a.clear
@a.save

Then this :
Object.all.each{|a| a.users.delete(User.find(2)) if a.users.include?(User.find(2))}

A: Set the relationship to an empty array.
User.find(2).tap do |u|
  u.objects = []
  u.save!
end


text:
Q: Transfer of Firefox passwords (across different versions) I'm using Firefox 60.2.2, but I have to go down to an old version (52-56) to use some add-on that's not compatible anymore.
I created another user profile, since I had the impression using the same profile across versions could mess things around. However, I need to use my username/passwords in my old version.
I thought that transfering the key.db and logins.json would suffice, but that's not the case.
How can I transfer password from the upgraded version to an old version?

A: For transferral of the profile, passwords, bookmarks, etc use firefox sync. You will need to create the account on the older version, then login to sync on the newer version.

A: I understand that you are another victim of the Firefox decision to drop the XUL
add-on format, now called "Legacy", in favor of WebExtensions,
which are very similar to Google Chrome extensions.
I suggest using a Firefox-fork that still supports the old format.
My favorite is
Pale Moon.
You could use the
Pale Moon profile backup tool
to transfer your Firefox profile to Pale Moon, and there wouldn't be any
conflict since the two profiles will be kept in separate folders.


text:
Q: Can someone please explain how Dodelson derives his formula for the neutron to proton ratio during BBN? On page 66 of Modern Cosmology by Dodelson, we have the formula for the change in neutron to proton ratio as a function of time:$$\frac{dXn}{dt}=\lambda_{np}\left\{(1-X_n)e^{-\frac{Q}{T}}-X_n\right\}$$Everything in the derivation up to this point is pretty clear.  Then there's an explanation that there are complicated time dependencies in the formula, which appears to be true because Mathematica is unable to numerically solve this formula, so we attempt to simplify the evolution parameter by:$$x=\frac{Q}{T}$$Now this is the part where I get lost.  The author states that the left hand side becomes $\dot x \frac{dX_n}{dx}$ The equation then becomes:$$\frac{dx}{dt} \frac{dXn}{dx}=\lambda_{np}\left\{(1-X_n)e^{-x}-X_n\right\}$$  So now all we need is an expression for $\frac{dx}{dt}$.  Expanding the steps explicitly, we have:
$$x\equiv \frac{Q}{T}$$
$$\frac{dx}{dt}=-\frac{Q\space\dot T}{T^2},Q=x\space T$$
$$\frac{dx}{dt}=-\frac{x\space\dot T}{T},T=\frac{T_0}{a}$$
$$\frac{dx}{dt}=\frac{x\space\dot a}{a},H=\frac{\dot a}{a}$$
$$\frac{dx}{dt}=x\space H$$Substituting, we get:
$$x\space H \frac{dXn}{dx}=\lambda_{np}\left\{(1-X_n)e^{-\frac{Q}{T}}-X_n\right\}$$$$\frac{dXn}{dx}=\frac{\lambda_{np}}{x\space H}\left\{(1-X_n)e^{-\frac{Q}{T}}-X_n\right\}$$So how does the author get this formula for (3.27)?$$\frac{dXn}{dx}=\frac{x \lambda_{np}}{H(x=1)}\left\{(1-X_n)e^{-\frac{Q}{T}}-X_n\right\}$$How did the Hubble Function $H$ get moved into the denominator and why is it evaluated at $x=1$ instead of at $x$?

A: In the radiation era, $H^2 \sim a^{-4}$ because of the Friedmann equation. Meanwhile the temperature scales with the scale factor as $T \sim a^{-1}$, so $H \sim T^{2}$ during the radiation era. Since $x \sim T^{-1}$, we have $H \sim x^{-2}$. Note that in the definition $x=Q/T$, $Q$ is the neutron-proton mass difference and is temperature independent.
Putting this scaling relation in the form of an equation, we find
\begin{equation}
H(x) = \frac{H(x=1)}{x^2}
\end{equation}
which is what you need to connect your formula with Dodelson's Eq. (3.27).


text:
Q: Differentiate look of Radiofield and Checkbox field in Sencha Touch 1.1 By default, Sencha Touch 1.1 provides a radiofield and a checkboxfield which show a check mark (tick).  Because of this design, there is no visual way to differentiate between them.

How can I change the look of the radiofield so that it looks like a traditional radio button?

A: I added my own styles to change the look of the checkbox.
.x-field .x-input-radio:after, .x-field .x-input-radio:checked:after {
    content: "";
    position: absolute;
    width: 1.25em;
    height: 1.25em;
    top: 50%;
    left: auto;
    -webkit-transform: rotate(0deg) skew(0deg);
    -webkit-transform-origin: 50% 50%;
    -webkit-border-radius: 2em;
    right: 1.1em;
    border: .45em solid;
    margin-top: -0.75em;
}
.x-field .x-input-radio:checked:after {
    border-color: #06346a;
}
.x-field .x-input-radio:after {
    border-color: #dddddd;
}

A: .x-field .x-input-radio:after,
.x-field.x-item-disabled .x-input-radio:checked:after {
    content: "";
    position: absolute;
    width: 1.4em;
    height: 1.4em;
    top: 50%;
    left: auto;
    right: 1.1em;
    -webkit-mask-image: url();
    margin-top: -0.7em;
    border-radius: 15px;
}
.x-field .x-input-radio:checked:after {
    content: "";
    position: absolute;
    top: 50%;
    left: auto;
    right: 1.1em;
    -webkit-mask-image: url();
    margin-top: -0.7em;
    border: 5px solid #dddddd;
    border-radius: 15px;
}

Link: http://tjwebb.wordpress.com/2012/03/24/how-to-override-the-default-sencha-touch-2-radio-field-style/


text:
Q: How can I save the same parameters from different for loops? I have a for loop that works in function of x and y.
So, finally the for loop gives me results like z, a, b.
I want to save x, y , z, a and b sequentially, changing x and y.
First, I did this to save the first parameters (x=0.1, y=10) and its results ("yes", z, a , b).
saveRDS(paste(x,y,"yes",z,a,b),file=paste("exer.RData"))
readRDS(file="exer.RData")
# [1] 0.2 10 yes 0.675791369732277 -0.52120086986903 0.353252113912809

And then, to save the next results, I tried to do this:
result<-NULL
result<-c(result,readRDS(file="tfm.RData"))

And get this error:
Error: object 'result' not found

I think that it's necesary to use a for loop and not the above, I tried this:
res<-paste(x,y,"yes",z,a,b)
for(i in 1:length(res)){
  saveRDS(i,file=paste0(names(res[i]),".rda"))}

I'm new in R, I hope you can help me. Thanks!


text:
Q: Instant payment success status for recurring payment's first cycle I have a recurring payment scenario and the checkout flow depends on the payment success status for the first billing cycle. I'm using PayPal's REST API and I have got below questions.

*

*Just after a recurring payment agreement is executed, is there any way I can get the payment success status instantly apart from using PDT or IPN?

*When charging a setup fee apart from the recurring payments, does the IPN/PDT notification for setup fee come before the first billing cycle payment notification?


text:
Q: Can a Mac act as Bluetooth receiver for sound? This is my setup to play music:

*

*Mac with iTunes

*2 Airport Express' connected to two pair of active
B&O speakers

I also have a turntable/record player that I want to use wirelessly with this setup. I therefore just ordered a Bluetooth transmitter. Now the question is if my Mac can receive A2DP (low latency AptX) from this device with its built in Bluetooth support or do I need to buy a separate receiver for the computer?
My plan is to use Rogue Amoeba's Line In app and redirect the sound from my turntable/Bluetooth combo to my Airport Express' but while waiting for my transmitter to arrive I have googled and it looks like a Mac can't act as a Bluetooth A2DP server. However, I also have a small portable Bluetooth speaker and that can act as a speaker phone and in Line In I can select this speaker both as output destination and input source, which seems to indicate that my Mac actually can receive sound from a Bluetooth source.

A: I found a solution using Airplay instead of Bluetooth, but I guess that is better anyway. The solutions is described in detail here
http://davidbo.livejournal.com/795.html
(page is added to Wayback Machine in case it disappears).


text:
Q: How to filter points in MapBox heatmap based on a property value? Say I have a basic mapbox heatmap. the geojson that makes the vector tile that this heatmap is built from looks soemething like this:
{"type":"FeatureCollection",
    "features":[
         {"type":"Feature","properties":{"dbh":0, "icon-type": "bike"},"geometry":{"type":"Point","coordinates":[-79.91746,40.44356]}},
         {"type":"Feature","properties":{"dbh":12, "icon-type": "bike"},"geometry":{"type":"Point","coordinates":[-79.94606,40.44961]}},
         {"type":"Feature","properties":{"dbh":6, "icon-type": "cat"},"geometry":{"type":"Point","coordinates":[-79.96474,40.46283]}},
         {"type":"Feature","properties":{"dbh":2, "icon-type": "dog"},"geometry":{"type":"Point","coordinates":[-80.00949,40.42532]}}
     ]
}

I understand how to display a heatmap as per the tutorial here:
https://docs.mapbox.com/help/tutorials/make-a-heatmap-with-mapbox-gl-js/
Notice though that each of the Features in the geojson have an icon-type property. I want to dynamically tell my heatmap to only display points from the data with a certain icon-type value such as "bike" or "cat".
How can i achieve this?

A: You can achieve this using a filter in the layer config, as used in this exmple.
In your case, it would be something like:
map.addLayer({
  id: 'heatmap-layer',
  type: 'heatmap',
  source: 'your-source',
  paint: { ... },
  filter: ['==', ['get', 'icon-type'], 'cat']
});

'==' only allows features for which the next two parameters are equal.
'get' is used to access feature properties, so ['get', 'icon-type'] resolves to the icon-type property of the feature.
'cat' is a string litteral.


text:
Q: Gaze tracking with a webcam (openCV and C++) I'm trying to realize a tool that returns the 2D coordinates of the point that the user is looking at. To do that I'm using openCV, c++ language and a low-cost webcam. I have the 2D coordinates of the center of the two pupils (leftPupil, rightPupil) but I don't know how to find the user's gaze.
I suppose that some information is missing but I don't know the right formula to estimate the gaze.
Is it mandatory to add a laser to get the distance of the user from the webcam? Must I analyze the geometric form of the pupil (if they are circles or elipses)? In this case, how can I detect the case in which they are eliptic or round?
Thank your for your ideas


text:
Q: Python - Sending __doPostBack (To join groups in Roblox) Roblox is a game, and you can also make groups (Like Clans in other games).
I am making a program that goes through these group pages, and checks to see if they have an owner. If there is not an owner, then join the group to become the owner.
I am doing this to collect some data from non-owned groups.
Lastly, I'd like it to leave the group once the data is collected.
Here is the "Join Group" button:
<div id="ctl00_cphRoblox_JoinGroup" class="btn-neutral btn-large" onclick="__doPostBack('JoinGroupDiv', 'Click');" style="margin-top: 10px;">
    Join Group
</div>

Here is the snippet of code I've tried:
import requests
s = requests.session()
Join_Group = dict('JoinGroupDiv', 'Click')
s.post('http://www.roblox.com/Groups/Group.aspx?gid=40', data=Join_Group)

I get the following error:
Traceback (most recent call last):
  File "C:\Users\User\Desktop\Group.py", line 18, in <module>
    Join_Group = dict('JoinGroupDiv', 'Click')
TypeError: dict expected at most 1 arguments, got 2

I'm pretty sure that I'm not supposed to be sending a Post request to the page, as to join the group, it does an onClick event.
EDIT 1:
Here is my updated code:
import requests
s = requests.session()
Join_Group = {"__EVENTTARGET":"ctl00_cphRoblox_JoinGroup", "__EVENTARGUMENT":"JoinGroupDiv"}
s.post('http://www.roblox.com/Groups/Group.aspx?gid=40', data=Join_Group)

But I don't quite know what to pass as the eventArguement. I don't get any errors, but when I load the page in Google Chrome it doesn't say I've tried to join.
EDIT 2:
I've also tried this:
import requests
s = requests.session()
Join_Group = {"__EVENTTARGET":"ctl00_cphRoblox_JoinGroup", "__EVENTARGUMENT":{"JoinGroupDiv","Click"}}
s.post('http://www.roblox.com/Groups/Group.aspx?gid=40', data=Join_Group)

EDIT 3:
So what I have here is the updated Join_Group with all of the necessary fields, but not all of the information. I don't know where to get the information.
Join_Group = {"__EVENTTARGET":"JoinGroupDiv", "__EVENTARGUMENT":"Click", "__LASTFOCUS":"", "__VIEWSTATE":"a lot of mumbo jumbo", "__VIEWSTATEGENERATOR":"It is 3D1CCC47 but that might change per post", "__EVENTVALIDATION":"some more mumbo jumbo"}

Here is a correct sample POST, but I don't know where it gets that information for __VIEWSTATE, __VIEWSTATEGENERATOR, and __EVENTVALIDATION.
__EVENTTARGET=JoinGroupDiv&__EVENTARGUMENT=Click&__LASTFOCUS=&__VIEWSTATE=fM9l9%2BTw8z%2FRNbMArorqQ7HQ2w3soDiNp5gJOc5sNNQPEzEzApHiWLOHghGcAriUGv6pCVCi15my4%2BUxUozLVQyGx%2Fiq%2FU9BxRdN80kWJgMyiIyZYtSnfsvlFkqmrHaLIMNKag4eYwnKi5K3TP6JpP5xAxfNIOjekh6vpSa84YVL6eOwPsh5vqlHSN9VjFlwjA1r7AJVZkoeVliUz7vpK1f7DM6lDnOWBtFaAc66xxe2SIoLcjdMlfrVJpJADRjLTEfLp6PNARua3FLJKDezN7WOekGOlSIXHHrzAFlyMY0uZflFykzc9E3zE%2FldijdHWJnIoBVNW1c7fl2ehrbbv%2BAQWpeWqMagkuGNWOmFD6SHPixWLVNgNMlVLXrVKtLEMp3jmXLR40vqdv3bpCkJTLqA9M1XpKsBJlX5szlJlqJzYleD8NncUA8sO2sqiRhnk%2BZURIHV0EQRdPdzJIWMuENZZr%2FPKRl6MNekpZHOtF6wcWQYd4oRYptUjwzWQupbovVnaAyehNLMJbJi6sARkiXAQMC1kUyHpMQVrEdC69%2FNPEW8Cy6QIffUW1d0VBzVuK2hNJV1IgsbqEJZ56HXTtQCz4rJRlATwum2%2BcDS1ITfjA1JWuXwkbFON73TDPFsuz4fOhpVdmNvgN%2B%2F9h4YhmlxlsP3Ud%2BIfuPgzm4b%2FymVzdK%2FBOag7SjO9YRbqH6%2BrIXeXUmPf332sRw4twDy6LhqYxQmzBcr%2BLF4O0%2FTWW1N1pbusZ2p5nyVwaQEQd1FFeVTz5UXNvIUqA89x%2FWzrNHRUEdbR4ZQh5%2B9Eefd0IzIYza6TgRnWYknClVK1sq0qZ7bM1xhJfCsH3xCpWpVNqRqUZvOcWl8JH8aTrs2PhkkDU2%2Flto%2BlcsKG95lV06xukVyfa%2B2uzH%2FVp1Pph2jGLvMHTfLFdgt8jymryMt84jWtg8g%2F9N%2B%2Fb%2B69Pf4OuqLKx0md6Z6gOo4erBMvjrxSwWZxPBf%2BX674CclYnPpBsQjprvRMYGGGUtO957breZv5yQ0zWEB86BWHN6%2Fp6GJ%2Fb3TpeCEgEIKWB6VXxIt9EV7Ls9DrSb43eYSfUDKiBqpKcSD59g5W98rxrm%2FJhrzUnGQsVS4GRNR%2FquTJeWOc4NFIeyULqyLxLECaeXSPoqKe1ijkZc2cz%2FIDLNnmKY%2BMte7JslLswmWC469aL5%2BGMlgC%2FRJ%2BDhxZVbgOfAy7WZ4CoPtpoM2ixT5l5%2Ffg%2F1Z9jlRM4SAdU6XuC%2FnIJjYRBjZtA2IHE4xl87bgR8noUW%2FpMUmWeJrrScXuNpOKKhGoeM1XBg%2BiCZbFQ6oIihzGdqsvW4YQ3i%2BdzJEQvO%2FabotjD6zgekjvonlWOXTiSFXRS9h1JhyPFjMUdooDCkB7%2BtvuMj%2BUXUX2TccPtt%2BHdZpwtRVwzzf96J7bcs%2F1FaYhDsoJO01SqEtUAFWVqLO004kauPB6uJc%2FDSlBDqGI2hY02ORAl6BfyHVT4vxW8YDv55kD0R2hJhBtfhHsvQaEvrOR2BFHIB9hp5G2KW6zDuCWthVckhjUDsBDzOzc%2FDYtcBHCw8oWVXAbX%2BEjJNwHH2CVXVFO7HRSg3LEjRmqX1Hu72wXCp%2FlV3PCa%2FZcytUhuwMl%2B4PaqzD%2BQcTM0bm8JXylJAuksYMqQNkb9D%2BukLxyzADwfYFWy3aEJI1bVu0S0s6SJlLhGL1Z1E8x3sVh6vrMwYV6lZXzAU3BjYBgozfNvWpUDbM7bRJmEgBIgJFZJImFKs%2FwltOI6XACd1E%2BHQXchinr%2FHFYX2JW7uawkF0eJ7uNcYQ9O0pw9UNPWTOdVP855V3JIJZA0HvKt99Sn2Q%2FHgTWBAFmjefEI73B0wEGqIjPCTPJfljbcouvH6DfzttfGItUJ5g2lAN2H6lr%2F2UuRpjaJa3X924BF6WlIr%2FZ0JoAwxWvw1dvd00BCBamThc%2BK515yzwo5uYFKBlyt%2BQz9y%2FAf2mfRlI%2Bg%2BBV7b3LipC%2B66gfY6HJwOxNniy67qD1pkgKMRT6xeP8h86IOHUDyaG54RIMQAkYDSOyhUlKbMEsVbhq%2Fuqo9wvVq9djLSB%2BUcjpes%2Bfsn%2FyDdTl3nCWHd3xDC6MywPSvb%2F7pvhriQmpPjiXHhrvaMpWdecsXEF60kB3Hl5gm6klilE4ZkbcwakkSdGUVYn0b2mbM%2B7gq2lopcmTzAJuPAZI%2Fdp%2BnfT9mMywge6d1RP%2BCFBWCZdSXUjHHGvuWBPg2u8yfF7lQGOq7avsR%2BXZ2pi2afwwgzEyoHoxPYSfXn3J5%2FSkAINRE8rjbxK2n2qCRXSUlex1fp38OrPHK9TODFHPuq0whQQ2JYgq2IHXeUUiysJ1j5cub8JfZkoOEAm2TwnExVx9Fvvq3SadMWKKW8yOwZ6u%2BSLJUKu%2FtSzD6cXtiCbDpoZTe9LAeAgD%2FH9CDsvgX6sm6m441qf2glcOg01GsiLi%2BcVOGy14oT0I%2F0qtAjZS5qQskhMFNhrPudHgXgIw8%2BC81KK396oDN5JccahOO2Zuxkgiv3BtWO%2Fp8RBzrkPLR3hK2hj%2FVcSdwe0VUvq7%2FBNKyoRUsTN0tLWk6uvsce8P5avqG0VXXnUYuhvQTRBd88QACFMQW47kINvBq0N%2Ba8byLHlN8Kq%2BogTeBDuTn7CKOlOxi1ryxYm%2BUtzP4Ep0XBfrYba9Ztyp9L4Il0aNXElYudeV7i1NGwjh5FRgvYOPLQwTs7kHCIIUgpcYcX4oUUwdvyyZUDnzGPuWUhu1E0RELWiV89%2BJIiCrw4SKdohI86thnXhR9Ye%2FciOOjq8%2Foo0Vl9lq2Re2uJttZ9l99cCi54xFIPS1celZfZYKxR%2B2HTaB3EZ4z7%2FvdvQJ8BqXTWlfLTUh6M1wDJvZJPJkHBILh8sHMdew3NT2NSfF7dIzXIdg%2F8h5Pyy7NCQEXYn0nhlEecjuL3%2FOD4ccd4nq7FvoA9RcSLkpVg4OUy7KsQgfxwdp3KLrgJFowsqb5oN6zBojmWpFXhqaSSQFM3jsDQ6eCtxruTKTFqXc0eb23enSXNJoEIk%2BMQnwbycOYZomJ05Bi0dQrCEwMQ6jG%2Fq6pH2qfNiA5hoVHZww5miQHEHCT4vw0mTRky9d%2FuUNgjpZlK28iKV%2BT7i%2Ftq6UJ8ldEi%2FeFIpJUNi2tjQtQk2qrBw3L%2FN0Z7c%2BdkzqXxAByQCXuCA5v1Zt4yJKoC0763V6rrKU9JaIyeNAl4arqk%2BZ%2BQxfY6Ia6MmCpaGrzn4yHRnxnR52TEbn%2FhWM3LTzNeghmRphtKi4AereUSOJXbQOrdtVEG0uVF6ZNhX7DWYQ7BVI%2Bw5bN4Cp%2FBL9WxjD0s0WetzoRor0vL7IUHIzkoQkJHlBnCXXHh6Mif6Rzgm8O%2FfEgalGqhScqAwlXE5JYeZpm%2BusCO4gC0PE%2BSJzWQy63gHq5q3semEMn1cje95%2FIO5No09ZPoYkqAVd7XSBsVrYu%2BQhoGR8h95PcKeW7q2SVRanFCzC%2FhNALnQBh9qs78L23MiioERyE8D%2BnLi0K6l2Gba1BJ5tkbTaFynhuRWyq%2Bacvjbno5gPXVINSPoVf%2BbpZYSmgbZCAIrctXgInQuNBaWTzWICeJxKctTmaEIO6kXBB7y1p%2BzDpqVr4hjMkjZTS9mz8YLuU4eSAMhYD59GJZQi6mVkR1U8C9OsV6O%2BXOvnDQVWjrqQGIpVmfRv0B6sCtrBd%2BAX6N4TkaRfVehaW39%2BgnBB6SpTc0IZZ4apy%2BHXiOqVfLuABrL6JN6gH29V%2BRsd%2BybvouJRxdb47mxv7trl6JOwINUbERqsLQAPjrr54wBtS4LlRkvfBZpDAM7yCK%2FRpeT%2BjuC1X9i1p3CwL74V%2FN5Q5LxlA51Z9oxciOohCy4GkawbMSE8qor5%2BPwM4bNn%2FM%2FhgxmaOYRsoQZ4ZaEcRpAI5Vi4A3sIyYIdCbUvMmAKrEW%2FUeRhShapsCjLxcXeNuumWDCOHpJfVt3n8K0q6Ona%2FU4VkupnBbdK6Yo2%2FdBt64Zhmuzl3Pp9tnCmbYeuq%2BmR4B7PkCVNibRS0%2Fe8JI2S2mtSKb8XLVk%2BhmOXBxJ7sscsa%2FMjtWICOMVjg7fGYcwEXSUeJbVKMoCY1Jv7B6k4KV2sO9yruESkscm%2By3bV1rOFQgoQ2BFCS%2F1XwvFCWBoa4hoMgs1yVihXN7mRz61taqiPLqVoHNTSA4wOQtgS1xsYThYlZDpKyltNnFrs%2BB42yjByPn8qyR91eoobFYzjBvxnVrDg4DX58kJ2VumhFRe4NPg29seqk64Ps%2BbLUFDiCV39CVrsriWGR4G91xCeZpcv5NABou3M3RareJeoTTAmpBD3KUA3orZ8xRAUuFOkC9nDPJujH9nI117UMgScL9t9Rx7eB6l6jEt7KiMocEoRGHOMnSQJz28bbidFQWx0z0H67%2FcwOwSq0P71fDojxRc8Uhyk9yZKFfCiQ5HN6WnBS0u4O61hYDHO4oioPrFh4VvxdeYXf5Wz%2BDQFtdqUzYhC%2FlA%2FLWAWJF8WkQ%2BX7NEKUh3JO%2BxxFZJaJH28xgd4E5jnTT92orjalpTwTZ1y2Pm%2FsVUKyLm8oXhD9N2nTi%2FB2oey0H6Dn1Charhyc1MiS9dYLICym1zFBcTAQt6Our9D96Z20LRDi5UYci%2FxUDVJrwsBgREMxT4tXx41XsCJhkAxYvL1coY7HHmlgQUg6RDruY21h85VBJQeyNX0GkNUqXTaW5lTPRPflsIIbs80L0UX%2FZc6coyvlnWmkl3e93liSifT4eWW7AhhCAdXXZRKX2ZTzHKWnHzuXHoeP6MSHmSw6lA4Shi3VHv8TAmK4aumANtqASpxPw0I0rXy1U6dXW2UMj8FHEJP8pZ6BX5smKqMQaB6JuWP1pZCPgINg%3D%3D&__VIEWSTATEGENERATOR=3D1CCC47&__EVENTVALIDATION=qv5aJzTc3fM%2BcENN%2BTP2DgRs4ocXUM4qLJNP%2FtEv4q0xMardTbzlDm9uqRxoi%2BfRFn8e%2FC0PuVHiCvBR2xRuCXu%2BBQLORcJ%2BQ%2FANICydWIh6GamZbMbX0BfCN%2BuVKQqW8v1HzL9oN9IOmupGv9F%2BvyxGsToAR94w6szmvNNYvcmQKqcflo2K04UZh1lqzC7ScOHIhyMJb4xooM4oTg3qlmISKwYKDPhVgVgzU4zvzFueU2kToA0DykBBodt8%2BJcKHXbxt4UkL%2FBAZvHssrUeFA9OtAECcG4T3r68EB632IBprg8m9uiVX1wP%2BB8yQQdpQjBtYfT9rBHblz1HvaAu1mcRB0E%3D&ctl00%24cphRoblox%24GroupSearchBar%24SearchKeyword=Search+all+groups&ctl00%24cphRoblox%24rbxGroupRoleSetMembersPane%24dlRolesetList=2343447&ctl00%24cphRoblox%24rbxGroupRoleSetMembersPane%24RolesetCountHidden=2&ctl00%24cphRoblox%24rbxGroupRoleSetMembersPane%24currentRoleSetID=2343447&ctl00%24cphRoblox%24GroupWallPane%24GroupWallPager%24ctl01%24PageTextBox=1

EDIT 3:
s = requests.session()
login_data = dict(username='USERNAMEHERE', password='PASSWORDHERE')
s.post('https://www.roblox.com/newlogin', data=login_data)

page = s.get('http://www.roblox.com/Groups/Group.aspx?gid=403577')
soup=BeautifulSoup(page.content, "html.parser")
VIEWSTATE=soup.find(id="__VIEWSTATE")['value']
VIEWSTATEGENERATOR=soup.find(id="__VIEWSTATEGENERATOR")['value']
EVENTVALIDATION=soup.find(id="__EVENTVALIDATION")['value']

Join_Group = dict(__EVENTTARGET="JoinGroupDiv", __EVENTARGUMENT="Click", __LASTFOCUS="", __VIEWSTATE=VIEWSTATE, __VIEWSTATEGENERATOR=VIEWSTATEGENERATOR, __EVENTVALIDATION=EVENTVALIDATION)
join = s.post('http://www.roblox.com/Groups/Group.aspx?gid=403577', data=Join_Group)
print join

A: Your error is because this is not valid dict construction. You either need a literal (like {'foo': 'bar'}) or, if using the constructor, keyword arguments dict(foo='bar').
You should do a POST as that's what __doPostBack() does - post back to the same page/URL that's been served, see What is a postback?.
To determine what actually needs to be set for the POST, you should understand the __doPostBack() function.
Those arguments are used to populate hidden form fields called __EVENTTARGET and __EVENTARGUMENT.
You can read an explanation about this here:
http://www.codeproject.com/Articles/667531/doPostBack-function
Edit: It's also worth noting that, when interacting with an application in this manner, you also need to be aware of any other state that's being managed and passed to the server. There are cookies, viewstate etc. to be considered. It's best to go through the process in a browser and inspect/record the requests with the developer tools to help you determine what data is required.
Edit 2: I see that Roblox has an API. You're much better off using this if/where possible rather than interacting with their UI.
See http://wiki.roblox.com/index.php/Web_APIs#Group_APIs
If this isn't letting you get access to a list of groups (I don't see a search here at a glance) then you might consider a hybrid approach.
Edit 3: For the scraping-type approach, you may want to consider Beautiful Soup for parsing the page/form and extracting the values being added by ASP.NET -
http://www.crummy.com/software/BeautifulSoup/


text:
Q: What could cause an object's attribute to not be read from the database? Right, this is the most bizarre bug I have ever come across.
I have a field in my resource called hashed_password, of datatype string. Nothing can be read from it. It's insane.
users table
id | username | created_at | updated_at | hashed_password

example data
37 | john harris | 2013-09-24 |  2013-09-24 | eba082ff45517c06b

users index
<% @users.each do |user| %>

    <%= user.id %>
    <%= user.username %>
    <%= user.password.inspect %>
    <%= user.hashed_password.inspect %>
    <%= user.created_at %>
    <%= user.updated_at %>
    <%= link_to 'Show', user %>
    <%= link_to 'Edit', edit_user_path(user) %>
    <%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %>

<% end %>

html
1
john harris
nil
nil
2013-09-24
2013-09-24
It's sitting right there in the database, but it just cannot be read. It's so weird. It only exists as nil.
The only thing different about it and the other columns is that its set programatically. Here's the User controller:
require "digest/sha1"
class User < ActiveRecord::Base
    attr_accessor :password

    before_create :hashed_password

    def self.authenticate(username, password)
        logger.info "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-"
        logger.info "user " + username

        user = find_by_username(username)

        logger.info "user id: " + user.id.to_s
        logger.info "user username: " + user.username.to_s
        logger.info "user hashed_password: " + user.hashed_password.to_s
        logger.info "user created_at: " + user.created_at.to_s
        logger.info "user updated_at: " + user.updated_at.to_s
        logger.info "*-*-*-*-*-*-*-*-"
        logger.info "entered hashed password " + Digest::SHA1.hexdigest(password)

        if user && user.hashed_password == Digest::SHA1.hexdigest(password)
            logger.info "SUCCESS"
            user
        else
            nil
        end
    end

    def hashed_password
        if password.present?
            self.hashed_password = Digest::SHA1.hexdigest(password)
        end
    end

But once it's in the database that shouldn't make a difference, should it? It simply refuses to be read. Also, the log file:
Started POST "/sessions" for 127.0.0.1 at 2013-09-25 08:06:45 +0100
Processing by SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"p5tDog8wOD6+H3fSFZpDXkMxNzFxej3tay6slVmIF5Y=", "username"=>"john harris", "password"=>"[FILTERED]", "commit"=>"Log in"}
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
user john harris
  [1m[35mUser Load (0.0ms)[0m  SELECT "users".* FROM "users" WHERE "users"."username" = 'john harris' LIMIT 1
user id: 37
user username: john harris
user hashed_password:
user created_at: 2013-09-25 07:06:28 UTC
user updated_at: 2013-09-25 07:06:28 UTC
*-*-*-*-*-*-*-*-
entered hashed password eba082ff45517c06bd365c2fde1fc77cda7a8f6f
  Rendered sessions/new.html.erb within layouts/application (1.0ms)
Completed 200 OK in 11ms (Views: 8.0ms | ActiveRecord: 0.0ms)

Note the blankness of the user hashed_password: entry. What is going on? Once data is in the database, it should be able to be read no matter how it got there. So weird.
The only thing I can think is that hashed_password is a keyword and rails does something stupid to it. That's all I can think. Completely at a loss.

A: Your callback method for setting hashed_password has the same name with attribute,  rename it to something unique, as it overrides attribute accessor.


text:
Q: How to create a list of index values based on 2 lists in prolog I'm trying to work on an assignment, however am really stuck on this section. What I need to do is write a predicate called matching with three parameters, all lists. The third list must contain the index of the positions in which the first two lists contain the same value. I really don't know where to start on this so any help would be much appreciated!

A:
The third list must contain the index of the positions in which the first two lists contain the same value.

First important:

The third list must contain the index of the positions in which the first two lists contain the same value.

Use unification. As predicate:
same_value(X, X).

The third list must contain the index of the positions in which the first two lists contain the same value.

lists_same_value([X|_], [Y|_]) :- same_value(X, Y). % succeed
lists_same_value([_|Xs], [_|Ys]) :-                 % skip head
    lists_same_value(Xs, Ys).                       % recursive definition

Simplify and unify in head:
lists_same_value([X|_], [X|_]).     % succeed
lists_same_value([_|Xs], [_|Ys]) :- % skip head element
    lists_same_value(Xs, Ys).       % recursive definition

The third list must contain the index of the positions in which the first two lists contain the same value.

Add accumulator for current index, succeed when heads are same element, and look in rest of list.
lists_same_value_index([X|_], [X|_], N, N).      % succeed
lists_same_value_index([_|Xs], [_|Ys], N0, N) :- % skip head element
    succ(N0, N1),                                % next index
    lists_same_value_index(Xs, Ys, N1, N).       % recursive definition

Instantiate accumulator:
lists_same_value_index(Xs, Ys, N) :-
    lists_same_value_index(Xs, Ys, 0, N).

Use it with bagof to find all solutions:
?- bagof(N, lists_same_value_index([a,b,c,a,c,d,c], [a,c,c,a,d,d,c], N), Ns).
Ns = [0, 2, 3, 5, 6].

and no this is not the same as the solution with the two nth0 of course, see:
?- numlist(1, 100, L), time( bagof(N, lists_same_value_index(L, L, N), Ns) ).
% 314 inferences, 0.000 CPU in 0.000 seconds (98% CPU, 1785481 Lips)
L = [1, 2, 3, 4, 5, 6, 7, 8, 9|...],
Ns = [0, 1, 2, 3, 4, 5, 6, 7, 8|...].

?- numlist(1, 100000, L), time( bagof(N, lists_same_value_index(L, L, N), Ns) ).
% 300,014 inferences, 0.052 CPU in 0.052 seconds (100% CPU, 5765387 Lips)
L = [1, 2, 3, 4, 5, 6, 7, 8, 9|...],
Ns = [0, 1, 2, 3, 4, 5, 6, 7, 8|...].

and then with nth0:
?- numlist(1, 100, L), time( findall(N, ( nth0(N, L, E), nth0(N, L, E) ), Ns) ).
% 2,181 inferences, 0.001 CPU in 0.001 seconds (100% CPU, 3329847 Lips)
L = [1, 2, 3, 4, 5, 6, 7, 8, 9|...],
Ns = [0, 1, 2, 3, 4, 5, 6, 7, 8|...].

?- numlist(1, 100000, L), time( findall(N, ( nth0(N, L, E), nth0(N, L, E) ), Ns) ).
% 1,667,166,681 inferences, 151.139 CPU in 151.244 seconds (100% CPU, 11030703 Lips)
L = [1, 2, 3, 4, 5, 6, 7, 8, 9|...],
Ns = [0, 1, 2, 3, 4, 5, 6, 7, 8|...].

A: As @Capellic suggested you can use findall/3 and nth1/3 predicates:
common_elemnts_pos(L1,L2,Pos):-
           findall(X, (nth0(X,L1,Elem), nth0(X, L2, Elem)) , Pos).

The above simply says that find all positions X that the element in L1 is Elem and element in L2 is Elem, so the have same element.
Example:
?- common_elemnts_pos([1,3,4,5,7,9],[1,2,4,5,8,9],Pos).
Pos = [0, 2, 3, 5].

It is also easy to do a pure recursive solution like:
common_elemnts_pos(L1,L2,Pos):- common_elemnts_pos(L1,L2,Pos,0).

common_elemnts_pos([],_,[],_).
common_elemnts_pos(_,[],[],_).
common_elemnts_pos([H|T],[H|T1],[CurrentPos|T2],CurrentPos):-
                               N_CurrentPos is CurrentPos+1,
                               common_elemnts_pos(T,T1,T2,N_CurrentPos).
common_elemnts_pos([H|T],[H1|T1],T2,CurrentPos):-
                               dif(H,H1), N_CurrentPos is CurrentPos+1,
                               common_elemnts_pos(T,T1,T2,N_CurrentPos).

Example:
?- common_elemnts_pos([1,3,4,5,7,9],[1,2,4,5,8,9],Pos).
Pos = [0, 2, 3, 5] ;
Pos = [0, 2, 3, 5] ;
false.
?- common_elemnts_pos([1,3,4,5,7,9],[1,2,4,5,8,9],Pos).
Pos = [0, 2, 3, 5] ;
false.

In first test above there are two same solutions because both base cases are valid. If you want only one you could replace:
common_elemnts_pos([],_,[],_).
common_elemnts_pos(_,[],[],_).

with base case:
common_elemnts_pos([],[_|_],[],_).
common_elemnts_pos(_,[],[],_).


text:
Q: Posicionamiento relativo de elementos en diferentes SVG Estoy desarrollando un pequeño juego en HTML en el que diferentes objetos vuelan por la pantalla proyectando una sombra en el suelo. Los dibujos son en SVG y los creo y animo usando d3.js.
El problema que tengo con esto es que cada pareja objeto-sombra está en un SVG. Entonces cuando dos objetos están cerca, la sombra de uno se proyecto sobre la del otro (cuando teóricamente en el juego estarían en el mismo plano) y es un efecto que quiero evitar.
Aquí se puede ver el problema. El avión rosado proyecta la sombra por encima del avión azul:

.avion {
  width:250px;
  height:250px;
  position:absolute;
}

.avion .sombra {
  fill:rgba(0,0,0,0.25);
  stroke:rgba(0,0,0,0);
  stroke-width:0;
  filter:url(#blur);
}

.avion .objeto {
  stroke:rgba(0,0,0,0);
  stroke-width:0;
}
<svg viewBox="0 0 250 250" class="avion" style="top:50px;left:60px;">
  <defs>
    <filter id="blur" x="-50%" y="-50%" width="200%" height="200%">
      <feGaussianBlur stdDeviation="8" />
    </filter>
  </defs>
  <path class="sombra" d="M 100,50 115,65 115,110 195,150 115,150 115,200 135,220 102,220 102,225 98,225 98,220 65,220 85,200 85,150 5,150 85,110 85,65Z" />
  <path class="objeto" fill="#00aadd" d="M 125,0 140,15 140,60 220,100 140,100 140,150 160,170 127,170 127,175 123,175 123,170 90,170 110,150 110,100 30,100 110,60 110,15Z" />
</svg>

<svg viewBox="0 0 250 250" class="avion" style="top:10px;left:180px;">
  <defs>
    <filter id="blur" x="-50%" y="-50%" width="200%" height="200%">
      <feGaussianBlur stdDeviation="8" />
    </filter>
  </defs>
  <path class="sombra" d="M 100,50 115,65 115,110 195,150 115,150 115,200 135,220 102,220 102,225 98,225 98,220 65,220 85,200 85,150 5,150 85,110 85,65Z" />
  <path class="objeto" fill="#aa0066" d="M 125,0 140,15 140,60 220,100 140,100 140,150 160,170 127,170 127,175 123,175 123,170 90,170 110,150 110,100 30,100 110,60 110,15Z" />
</svg>

Lo que querría es que ambos objetos queden por encima de las sombras. ¿Hay alguna manera de hacer eso? ¿Sería mejor usar otra estrategia (p.e. canvas) en lugar de elementos SVG? ¿O un único SVG con múltiples grupos?
Intenté aplicar estilos CSS directamente en los path para que las sombras se pusieran en una capa inferior (z-index:1) y los objetos en una capa superior (z-index:2). Pero no funcionó.
Pensé en separar la sombra y el objeto en dos SVG, y tener todas las sombras en una sección con un z-index inferior, y todos los objetos en otra sección con un z-index superior. Esto parece sí funcionar, pero no sé si es conveniente (o eficiente) porque entonces tendría que animar el doble de elementos.

A: Veo una tarea bastante compleja conseguir eso de la manera que pretendes.
Mi recomendación es que mires algún framework o librería para juegos como Fhaser.io, no la he usado pero he oído que da bastante buen resultado. Si necesitas mucho 'juego' de profundidad y sombras mi recomendación es que te inclines hacia WebGL en lugar de SVG, ThreeJS es bastante sencillo de utilizar, hay muchísima docu y da un rendimiento estupendo, magnífico, excelente.


text:
Q: Microsoft outlook API Anyone knows if outlook mail API have a way to retrieve the user mail signature, to use on mail.send?
I already saw the documentation regarding to mail, contacts, settings etc but didn't found anything.

A: There's no method or property in the Outlook Object Model to read signatures.  The signatures are actually stored as files - just read them from the \AppData\Roaming\Microsoft\Signatures folder.  There will be three file variations for each signature, one for text, RTF and HTML.


text:
Q: Check if application was opened by tapping a notification I am having some problems with the behavior push notifications in my app.
If the app is not running (not even in the background), when I touch a notification I can parse its payload and do a custom action, by reading the "launchOptions" dictionary.
When my app is running in the background, I am not being able to detect when a user foregrounds the app by tapping the notification, as application:didReceiveRemoteNotification:fetchCompletionHandler: is called immediately in the background, and when I foreground the app I have no way to check if it was done by tapping the app icon or the notification.
I know this is possible because Facebook's Messenger app does this - if I tap the notification it brings me to the chat, else it brings me to where I was previously.
Thanks.

A: If the user taps the app icon, application:didReceiveRemoteNotification:fetchCompletionHandler does not get called.
If they tap the notification, application:didReceiveRemoteNotification:fetchCompletionHandler does get called and application.applicationState will be UIApplicationStateInactive.
Check out this answer for a code snippet that you can use to quickly see this in action to have it make more sense.
Also, to achieve your goal be sure to do any updating of views when the application state is UIApplicationStateInactive, not UIApplicationStateBackground. The application state will be UIApplicationStateBackground when the push notification comes in. The application state will be UIApplicationStateInactive only when the user launches the app by tapping the notification.
I've seen a lot of answers with if statements like
if (application.applicationState != UIApplicationStateActive) { ... }

but that won't allow you to distinguish between a push notification being delivered and the user tapping a notification.


text:
Q: Any ideas why submit button don't work Simple submit button form with 2 radio buttons.
   But I can't simply submit -submit button don't work.
   I am newbie in laravel and bootstrap. help me please?

    <form method="POST" class="form-inline" action="{{action('OrderController@submitOrder')}}">
        <input type="hidden" name="_token" value="{{csrf_token()}}">

                    <input type="radio" name="type" value="cash" checked> Деньги

                    <input type="radio" name="type" value="card"> Карта
                    <input class="btn btn-success" type="submit" value="Отправить">

       </form>

A: Instead of <input class="btn btn-success" type="submit" value="Отправить"> try <button class="btn btn-success" type='submit'> Отправить </button>


text:
Q: Trying to retreive time_t equals to 1 sec. from tm equals Thu Jan 01 00:00:00 1970 Why is forward conversion from time_t, equaled to 1, to tm valid, whereas backward is not?
#include <ctime>
#include <map>
using namespace std;
int main() {

    time_t timer = 1;
    tm *timerSt = gmtime(&timer);
    cout << asctime(timerSt) << endl;   //Thu Jan 01 00:00:01 1970
    timer = mktime(timerSt);
    cout <<"timer 0: "<< timer << endl; //timer 0: -1
}


text:
Q: Sencha Touch 2.0 Dataview in Panel I have a problem I have been struggling with for quite a while now so hopefully someone can help me out here.
Say you have this DataView object:
Ext.define('Score.view.GameInfoPanel', {
    extend: 'Ext.DataView',

    config: {
        store: {
            fields: ['Name', 'Score'],
            data: [
                {Name: 'test', Score: '1'},
                {Name: 'test2', Score: '100'}
            ]
        },
        itemTpl: '{Name} - {Score}',
        fullscreen: false
    }
});

I thought I could use an instance of this DataView on different Panels like this:
var gameInfo = Ext.create('Score.view.GameInfoPanel',  {
    xtype: 'gameInfo',
    scrollable: false,
    fullscreen: false,
    height: 100,
    flex: 2,
});

Ext.define('Score.view.PlayerView', {
    extend: 'Ext.Panel',
    xtype: 'playerview',

    requires: [
        'Score.view.GameInfoPanel'
    ],

    config: {
        title: 'Player Info',
        iconCls: 'user',

        layout: 'vbox',
        scrollable: true,

        items: [
            {
                docked: 'top',
                xtype: 'toolbar',
                id: 'toolbarId',
                title: 'Player Info',
            },
            {
                xtype: 'panel',
                html: 'before',
                flex: 1
            },
            gameInfo,
            {
                xtype: 'panel',
                html: 'after',
                flex: 3
            }
        ]
    }
});

When would show this panel in Safari I see that the DataView is in the page/panel but it is hidden. The problem is probably that x-item-hidden is set for this DataView instance. After struggling with this for hours I have no clue why this is and how to solve this. The only suggestions I could find is that I should set the height of the DataView and make it not scrollable. All of that does not seem to work. So any feedback would be very much appreciated!

A: http://www.senchafiddle.com/#2Ig9U
That sample code works just fine.
"I thought I could use an instance of this DataView on different Panels like this:"
This might be a clue. Last time I tried creating and referencing the -same- object in an extjs project I ran into something similar. What you should rather do is use an alias, and instantiate it via a widget.
more or less:

       Ext.define('Score.view.GameInfoPanel', {
        extend: 'Ext.DataView',
        alias:'widget.scoreViewGameInfoPanel', //widgets use lazy loading
        config: {
            store: {
                fields: ['Name', 'Score'],
                data: [
                    {Name: 'test', Score: '1'},
                    {Name: 'test2', Score: '100'}
                ]
            },
            itemTpl: '{Name} - {Score}',
            fullscreen: false
        }
    });

    Ext.define('Score.view.PlayerView', {
        extend: 'Ext.Panel',
        xtype: 'playerview',

        requires: [
            'Score.view.GameInfoPanel'
        ],

        config: {
            title: 'Player Info',
            iconCls: 'user',

            layout: 'vbox',
            scrollable: true,

            items: [
                {
                    docked: 'top',
                    xtype: 'toolbar',
                    id: 'toolbarId',
                    title: 'Player Info',
                },
                {
                    xtype: 'panel',
                    html: 'before',
                    flex: 1
                },
                Ext.widget('scoreViewGameInfoPanel',{

//coz sencha hated the
//same object in 2 places last i looked

                    scrollable: false,
                    fullscreen: false,
                    height: 100,
                    flex: 2
                }),
                {
                    xtype: 'panel',
                    html: 'after',
                    flex: 3
                }
            ]
        }
    });

If you actually need the -same- panel in 2 places for selecting and stuff, then I'm not too sure.

A: It took a while but I finally solved it. There were a few problems with the initial code.
In the definition of the GameInfoPanel the configuration attribute 'fullscreen' should not be used. I am not exactly sure why. But from what I understood is that the view(s) in which this view is used already set this attribute. By setting it again, even when it is set to false, it will hide the view.
Furthermore the 'xtype' attribute should be set. In this case I set it to 'gameinfo'. This is because you then can configure this view in the PlayerView. Also by setting the 'id' you can refer to this instance of the GameInfoPanel in your controller. So the PlayerView looks like this in the end:
Ext.define('Score.view.PlayerView', {
  extend: 'Ext.Panel',
  xtype: 'playerview',

  requires: [
      'Score.view.PlayerInfoPanel',
      'Score.view.GameInfoPanel'
  ],

  config: {
      title: 'Player Info',
      iconCls: 'user',
      layout: 'vbox',
      scrollable: true,

      items: [
          {
              docked: 'top',
              xtype: 'toolbar',
              id: 'toolbarId',
              title: 'Player Info'
          },
          {
              xtype: 'playerinfo',
              id: 'currentPlayerInfoId',
              flex: 1,
              scrollable: false
          },
          {
              xtype: 'gameinfo',
              id: 'currentGameInfoId',
              flex: 2,
              scrollable: false
          }
       ]
    }
});


text:
Q: Cannot send DIO post request with multiple form-data body json and image with Flutter I am currently try to send a post request that works in Postman :
curl --location --request POST 'https://demo-recofaciale.openground.fr/visitors/' \
--form 'visitor="{\"uuid\": \"611633d2766081d524d5fbc3\", \"locale\": \"fr\", \"name\": \"Xxxx XXXXXXX\", \"photoUrl\": \"\"}";type=application/json' \
--form 'photoFile=@"/C:/Users/xxxxxx/Pictures/my-photo.jpeg"'

with Flutter (Flutter 2.2.3) and his Dio (dio: ^4.0.0) package, but I did'nt succeed.
Here is what I tried:
      var dio = dio_package.Dio();

      File imageFile = File(photo.path!);
      String? id = client == null ? _session.user!.id : client.id;
      String name = client == null
          ? "${_session.user!.firstName} ${_session.user!.lastName}"
          : "${client.firstName} ${client.lastName}";

      var file = await dio_package.MultipartFile.fromFile(imageFile.path,
          filename: basename(imageFile.path),
          contentType: MediaType("image", basename(imageFile.path)));

      var formData = dio_package.FormData.fromMap({
        "visitor": json
            .encode({"uuid": id, "locale": "fr", "name": name, "photoUrl": ""})
      });

      formData.files.add(MapEntry('photoFile', file));

      dio.options.baseUrl = _config.url!;
      await dio.post(
        "/visitors",
        data: formData,
      );

this code returned error Content type 'application/octet-stream' not supported | Status: 415
If anyone has already get thies errors, thanks for advance for your help


text:
Q: Expand unblanced data.frame of values relating two ID variables to balanced matrix Consider data.frame consisting of two ID variables and a third variable, relate, indicating the relationship (e.g. a covariance) between each pair of ID variables:
options(stringsAsFactors = FALSE, digits = 2)
set.seed(1)
(example <- data.frame(v1 = LETTERS[rep(c(2,3,1,4,7),
                                       times = c(3,2,2,1,2))],
                      v2 = LETTERS[c(2:4, 4:5, 4:5, 5,8,9)],
                      relate = rnorm(10)))

   v1 v2 relate
1   B  B  -0.63
2   B  C   0.18
3   B  D  -0.84
4   C  D   1.60
5   C  E   0.33
6   A  D  -0.82
7   A  E   0.49
8   D  E   0.74
9   G  H   0.58
10  G  I  -0.31

These data are unbalanced in that not every pairwise relationship is accounted for and not every in v1 is in v2 and vice versa.
The goal is to expand these data into a symmetric matrix where all the unique values in both v1 and v2 comprise the row and column names and the entries are the corresponding values of relate (if it exists, else NA). In other words, to populate the below matrix with values of relate:
vars <- with(example, unique(c(v1, v2)))
matrix(nrow = length(vars),
       ncol = length(vars),
       dimnames = list(vars, vars))
   B  C  A  D  G  E  H  I
B NA NA NA NA NA NA NA NA
C NA NA NA NA NA NA NA NA
A NA NA NA NA NA NA NA NA
D NA NA NA NA NA NA NA NA
G NA NA NA NA NA NA NA NA
E NA NA NA NA NA NA NA NA
H NA NA NA NA NA NA NA NA
I NA NA NA NA NA NA NA NA

However, the ready made solutions I've tried so far (data.table::dcast, reshape2:dcast) produce the following unbalanced results:
 data.table::dcast(example, v1~v2, value.var = 'relate')
  v1     B    C     D    E    H     I
1  A    NA   NA -0.82 0.49   NA    NA
2  B -0.63 0.18 -0.84   NA   NA    NA
3  C    NA   NA  1.60 0.33   NA    NA
4  D    NA   NA    NA 0.74   NA    NA
5  G    NA   NA    NA   NA 0.58 -0.31

Is there an efficient way to instead obtain a balanced, symmetric matrix of values from a set of ID-pairs and relating values?
One solution that occurs to me is to manually populate the above symmetric matrix of NA values using mapply and defining a subsetting function, but that seems unnecessarily cumbersome.

A: We can convert the 'v1/v2' columns to factor with levels specified as the unique elements in the unlisted 'v1/v2' columns in 'example', and then do dcast with drop=FALSE
library(data.table)
un1 <- unique(unlist(example[1:2]))
setDT(example)[, paste0("v", 1:2) := lapply(.SD, factor, levels = un1),
            .SDcols = v1:v2]
dcast(example, v1~v2, value.var = "relate", drop = FALSE)
#   v1     B    C  A     D  G    E    H     I
#1:  B -0.63 0.18 NA -0.84 NA   NA   NA    NA
#2:  C    NA   NA NA  1.60 NA 0.33   NA    NA
#3:  A    NA   NA NA -0.82 NA 0.49   NA    NA
#4:  D    NA   NA NA    NA NA 0.74   NA    NA
#5:  G    NA   NA NA    NA NA   NA 0.58 -0.31
#6:  E    NA   NA NA    NA NA   NA   NA    NA
#7:  H    NA   NA NA    NA NA   NA   NA    NA
#8:  I    NA   NA NA    NA NA   NA   NA    NA


text:
Q: docusignapi error calling UpdateNotificationSettings: { User Lacks Permission to resource Using an demo account and my accountID, I am trying to change the Notification settings on an envelope I am creating using the REST API. I get the error below. Is this a settings issue with my account, or a problem with the way I am creating the envelope?

Error calling UpdateNotificationSettings: {
   "errorCode": "USER_LACKS_PERMISSIONS",
   "message": "This user lacks sufficient permissions to access this resource."
  }

Code:
Recipients recipients = new Recipients { Signers = new List<Signer>(signers) };
EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition
{
    EmailSubject = "Review and sign the document",
    Documents = new List<Document>(documents),
    Recipients = recipients,
    Status = "sent"
};
ApiClient apiClient = new ApiClient(basePath);
apiClient.Configuration.AddDefaultHeader("Authorization", "Bearer " + accessToken);
EnvelopesApi envelopesApi = new EnvelopesApi(apiClient.Configuration);
EnvelopeSummary results = envelopesApi.CreateEnvelope(accountId, envelopeDefinition);

Expirations exp = new Expirations("14", "true", "2");
EnvelopeNotificationRequest enr = new EnvelopeNotificationRequest(exp, null, null);

string envelopeId = results.EnvelopeId;

envelopesApi.UpdateNotificationSettings(accountId, envelopeId, enr);

A: It looks like you're sending the envelope and then trying to change the expiration settings while it's live.
You might have better results adding that expirations to the envelope definition prior to the CreateEnvelope() call. Try this instead:
Recipients recipients = new Recipients { Signers = new List<Signer>(signers) };
EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition
{
    EmailSubject = "Review and sign the document",
    Documents = new List<Document>(documents),
    Recipients = recipients,
    Status = "sent"
};

Expirations exp = new Expirations("14", "true", "2");
envelopeDefinition.Notification = new Notification(expirations)

ApiClient apiClient = new ApiClient(basePath);
apiClient.Configuration.AddDefaultHeader("Authorization", "Bearer " + accessToken);
EnvelopesApi envelopesApi = new EnvelopesApi(apiClient.Configuration);
EnvelopeSummary results = envelopesApi.CreateEnvelope(accountId, envelopeDefinition);


text:
Q: why iterator is not throwing concurrentmodification exception? why does this method not throw a concurrent modification?
if if(next.equals("3") it does not. However, i change it to equals("1") it does. what is happening here?
    private void checkConcurrentModification(){

        Map<String, Integer> map = new HashMap<>();

        map.put("1", 1);
        map.put("2", 2);
        map.put("3", 3);

        Iterator<Entry<String, Integer>> iterator = map.entrySet().iterator();

        while(iterator.hasNext()){
            String next = iterator.next().getKey();
            map.put(next, 1);
            if(next.equals("3")){ //does not throw exception
 //if(next.equals("1")){ //throws exception
                map.put("4", 4);
            }
        }

        for(Entry<String, Integer> entry : map.entrySet()){
            System.out.println("entry key and value" +entry.getKey() + " : " +entry.getValue());
        }

    }

prints:
entry key and value1 : 1
entry key and value2 : 1
entry key and value3 : 1
entry key and value4 : 4

A: This depends on the the implementation of HashMap.
If you run this under Java 7, then with the if (next.equals("3")) it will throw a ConcurrentModificationException, and with 1, it won't.
If you run this under Java 8, then with 3 it will not throw the exception, and with 1, it will.
The reason for this is that when you iterate the map under Java 7, the first key is going to be the 3 and the last is 1. So you are modifying the value while you still have other values to iterate.
Under Java 8, the first key in the iteration is 1 and the last is 3.
If you modify the map when you have encountered the last key, it will not check that modification, because it only checks it the next time you try to call next(), but after the last value, hasNext() returns false, so next() is not called and the exception is avoided.

A: The ConcurrentModificationException is not thrown until you try to access iterator.next().getKey(); after changing the map within the loop. In the example "3" is the last key in the original map and the loop is exited before the exception is thrown. For every key in the original map except the last one, the exception will be thrown.

A: ConcurrentModificationException is thrown when the iterator reach the next map key, if you added a new key to the map at the previous step. So you only get the exception if the key you test is not the last one in the map. In your case 3 is for sure the last one.
Note: As HashMap has no order, on one machine 3 might be last, on others 1 or 2 might be.


text:
Q: Как решить проблему с Imagemagick на Ubuntu 16.04? Делаю проект и начались проблемы с imagemagick. На сайте,когда нажимаешь на кнопку Upload, выбираешь картинки, далее жмешь Save и ниже должны красиво отобразиться картинки, а вместо этого просто пусто.
Сам же imagemagick я установил. Paperclip версии 5.0.0.
Вот так должно выглядеть:

Моя модель photo.rb:
class Photo < ApplicationRecord
  belongs_to :room

  has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end

И самое удивительно, что когда стоят styles в модели, то картинки не загружаются и бьет ошибку в консоле:
Paperclip::Errors::NotIdentifiedByImageMagickError

Но как только удаляешь из модели строку стилей:
class Photo < ApplicationRecord
      belongs_to :room

      has_attached_file :image
      validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end

Вот что пишут логи:
    Started PATCH "/rooms/2" for 127.0.0.1 at 2017-04-20 01:41:54 -0700
Processing by RoomsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"LMHlWcnFi7NlGh37ZgNGKORN4VPeM4nLbAyQ3Zka4dCgG0jq2yMK/7aiJwDwka3pvI9xVnC1up3jy2iuwvdQFg==", "room"=>{"home_type"=>"Apartament", "room_type"=>"Private", "accommodate"=>"4", "bed_room"=>"2", "bath_room"=>"2", "listing_name"=>"fdg", "summary"=>"gfgf", "address"=>"gfgfgdf", "is_tv"=>"1", "is_kitchen"=>"0", "is_internet"=>"0", "is_heating"=>"0", "is_air"=>"1", "price"=>"30", "active"=>"0"}, "images"=>[#<ActionDispatch::Http::UploadedFile:0x00000005cbbce0 @tempfile=#<Tempfile:/tmp/RackMultipart20170420-53416-12vrrk9.jpg>, @original_filename="067c8ec7_original.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"images[]\"; filename=\"067c8ec7_original.jpg\"\r\nContent-Type: image/jpeg\r\n">], "commit"=>"Save", "id"=>"2"}
  [1m[36mRoom Load (12.5ms)[0m  [1m[34mSELECT  "rooms".* FROM "rooms" WHERE "rooms"."id" = $1 LIMIT $2[0m  [["id", 2], ["LIMIT", 1]]
  [1m[36mUser Load (4.8ms)[0m  [1m[34mSELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2[0m  [["id", 1], ["LIMIT", 1]]
  [1m[35m (1.0ms)[0m  [1m[35mBEGIN[0m
  [1m[36mUser Load (2.4ms)[0m  [1m[34mSELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2[0m  [["id", 1], ["LIMIT", 1]]
  [1m[35m (4.4ms)[0m  [1m[35mCOMMIT[0m
  [1m[35m (1.2ms)[0m  [1m[35mBEGIN[0m
Command :: PATH=/usr/local/bin/identify:$PATH; file -b --mime '/tmp/e451414538be5739f78f86efdac7993c20170420-53416-1qdbl6k.jpg'
Command :: PATH=/usr/local/bin/identify:$PATH; identify -format '%wx%h,%[exif:orientation]' '/tmp/e451414538be5739f78f86efdac7993c20170420-53416-mv0yk3.jpg[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
Command :: PATH=/usr/local/bin/identify:$PATH; identify -format '%wx%h,%[exif:orientation]' '/tmp/e451414538be5739f78f86efdac7993c20170420-53416-mv0yk3.jpg[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
Command :: PATH=/usr/local/bin/identify:$PATH; file -b --mime '/tmp/e451414538be5739f78f86efdac7993c20170420-53416-q86bu3.jpg'
  [1m[35m (2.1ms)[0m  [1m[35mCOMMIT[0m
Redirected to http://localhost:3000/rooms/2/edit
Completed 302 Found in 786ms (ActiveRecord: 33.1ms)

Started GET "/rooms/2/edit" for 127.0.0.1 at 2017-04-20 01:41:55 -0700
Processing by RoomsController#edit as HTML
  Parameters: {"id"=>"2"}
  [1m[36mRoom Load (0.9ms)[0m  [1m[34mSELECT  "rooms".* FROM "rooms" WHERE "rooms"."id" = $1 LIMIT $2[0m  [["id", 2], ["LIMIT", 1]]
  [1m[36mUser Load (6.5ms)[0m  [1m[34mSELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2[0m  [["id", 1], ["LIMIT", 1]]
  [1m[36mUser Load (1.8ms)[0m  [1m[34mSELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2[0m  [["id", 1], ["LIMIT", 1]]
  Rendering rooms/edit.html.erb within layouts/application
  [1m[36mPhoto Load (5.0ms)[0m  [1m[34mSELECT "photos".* FROM "photos" WHERE "photos"."room_id" = $1[0m  [["room_id", 2]]
  Rendered photos/_list.html.erb (20.5ms)
  Rendered rooms/_form.html.erb (87.0ms)
  Rendered rooms/edit.html.erb within layouts/application (91.9ms)
  Rendered nav/_navbar.html.erb (2.8ms)
  Rendered nav/_message.html.erb (1.1ms)
Completed 200 OK in 548ms (Views: 489.1ms | ActiveRecord: 14.3ms)

Все картинки загружаются. Помогите решить проблему, тк эти стили мне необходимы в будущем.