text:
Q: Laravel x Flask - Client error: `POST http://127.0.0.1:5000/run` resulted in a `400 BAD REQUEST` response: I have 2 systems that created from Laravel & Flask
Laravel - http://127.0.0.1:8000/
Flask - http://127.0.0.1:5000/
When I'm trying to send form data post request together with file from Laravel to Flask via Guzzle, I got this error message.
"""
Client error: `POST http://127.0.0.1:5000/run` resulted in a `400 BAD REQUEST` response:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>

Bad Request

The brows (truncated...)
"""

If using POSTMAN, no issue at all

Laravel code
$client = new \GuzzleHttp\Client();
            $options = [
                'multipart' => [
                    [
                        'name'     => 'file',
                        'contents' => file_get_contents(storage_path('app/public/config/'.$service->config, 'r' ))
                    ],
                    [
                        'name'     => 'service_id',
                        'contents' => $id
                    ],
                    [
                        'name'     => 'email',
                        'contents' => auth()->user()->email
                    ]
                ]
            ];
            $response = $client->post('http://127.0.0.1:5000/run', $options);

Flask code
@app.route('/run', methods=['POST'])
def run():
    service_id = request.form.get("service_id")
    email = request.form.get("email")
    file = request.files['file']

The error message happened because of the file. It exists but cant sent.
Update: I changed from file_get_contents into fopen. The client-side Flask successfully intercepted my request but on server side Laravel, still loading like never-ending story...


text:
Q: Error when creating private subnets within AWS VPC I am currently trying to create a VPC with multiple subnets in AWS.  Unfortunately, whenever I go to design the subnets within the VPC I am getting errors. This is my VPC design:
VPC: 10.82.0.0/16
Private Subnets:

*

*10.82.96.0/21

*10.82.119.0/21

*10.82.194.0/21

*10.82.212.0/21

The Error I get is the following for each subnet CIDR except 10.82.96.0/21:

Must be a valid CIDR block.

What am I doing wrong? I just want to create multiple private subnets in this VPC.

A: A /21 is quite an unusual netmask to be using. It contains 2048 IP addresses.
The netmask for /21 would be:
11111111.11111111.11111000.00000000

Only the zeroes are allowed to change. In binary, 100000000000 is equivalent to 2048 in decimal and 1000 in binary is 8 in decimal.
This means that the second last number would be a multiple of 8 (eg 0, 8, 16, 32).
However, you have not chosen IP addresses that start in a /21 range.
Your chosen subnets would have the following IP address ranges:
CIDR            First address   Last address
10.82.96.0/21   10.82.96.0      10.82.103.255  Good!
10.82.119.0/21  10.82.112.0     10.82.119.255  Invalid
10.82.194.0/21  10.82.192.0     10.82.199.255  Invalid
10.82.212.0/21  10.82.208.0     10.82.215.255  Invalid

Note that the first line is good because 96 is divisible by 8. Therefore, it is valid in a /21 CIDR.
However, the subsequent lines do not start on a /21 boundary. They are invalid CIDR values.
I highly recommend using a CIDR calculator when determining difficult IP ranges.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# WPF Scrollable container for usercontrols I've looked all over and have been unable to find a solution to my problem. My entire approach might be off and I could start over if I'm simply tackling this the wrong way.
I have a WPF window with a header, a listbox, an a footer. I want to programatically add n number of user controls to the listbox and have the listbox itself be scrollable (not the entire window). I also want to turn off what happens when you click an item in the listbox (the background highlights blue - I want it to change the background of the user control now treat it as a big listbox item) Really a listbox might even be the wrong thing.
I've tried stackpanels, scrollpanels, and a half dozen other approaches. Listbox just happens to be what I'm using now. I have a dozen different types of usercontrols and based on business logic some combination of them needs to be displayed, so really I need a scrollable usercontrol container where I can determine which one, if any, has been clicked.
Here is the XAML for MainWindow.xaml
<Window x:Class="LayoutTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:customUserControls="clr-namespace:LayoutTest.Properties"
        Title="Layout Sample" Height="Auto" MaxWidth="600" MinWidth="600" Width="600"  ResizeMode="CanMinimize" WindowStartupLocation="CenterScreen">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="393*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <TextBlock Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="24" TextAlignment="Center" Margin="5,5,210,5">Header</TextBlock>
        <ListBox x:Name="lstPanels" Grid.Row="1" Grid.ColumnSpan="2" HorizontalContentAlignment="Stretch" Margin="0,0,0,17"/>
        <TextBlock Grid.Column="1" Grid.Row="2" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="24" TextAlignment="Center" Margin="5,5,210,5">Footer</TextBlock>
    </Grid>
</Window>

And here is the XAML for UserControl1.xaml
<UserControl x:Class="LayoutTest.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="100" d:DesignWidth="500" Padding="0" Margin="10">
    <Border BorderThickness="2" BorderBrush="OrangeRed" CornerRadius="10">
        <StackPanel Orientation="Horizontal">
            <Image x:Name="imgLogo" MinWidth="100" MinHeight="100" MaxWidth="100" MaxHeight="100" />
            <Grid MinWidth="400">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="108*" />
                    <ColumnDefinition Width="104*" />
                    <ColumnDefinition Width="188*" />
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="25*" />
                    <RowDefinition Height="35*" />
                </Grid.RowDefinitions>
                <TextBlock Text="xxxxx:" Margin="5,2,2,2" />
                <TextBlock Grid.Column="1" Grid.ColumnSpan="2"  Text="xxxxx" Margin="2" />
                <TextBlock Text="xxxxx:" Grid.Row="1" Margin="5,2,2,2" />
                <TextBlock Grid.Column="1" Grid.Row="1" Text="xxxxxx" Grid.ColumnSpan="2" Margin="2" />
                <CheckBox Content="xxxxxx" Grid.Row="3" Name="chkSkipConfiguration" Grid.ColumnSpan="2" VerticalAlignment="Center" Margin="0,0,112,5" Width="200" HorizontalAlignment="Right" />
                <Button Content="xxxxx" Grid.Column="2" Grid.Row="3"  Padding="0" HorizontalAlignment="Right" Width="50" Margin="0,0,19,0"  />
            </Grid>
        </StackPanel>
    </Border>
</UserControl>

And lastly in the constructor for MainWindow.xaml.cs there is the following snippet to create 10 instances of the user control:
        for(int i=0; i<10; i++)
        {
            lstPanels.Items.Add(new UserControl1());
        }

A: First give your ListBox a height and width, either explicitly or by Stretching it within a container.  With your ListBox you can define a vertical scrollbar using ScrollViewer.VerticalScrollBarVisibility="Visible".  If you have a height defined then it should automatically enable scrolling as your added items extend past that height.
As far as the highlighting goes, try this setter.  Just place it in a style targeted for the ListBoxItem type:
  <Setter Property="Template">
     <Setter.Value>
        <ControlTemplate TargetType="{x:Type ListBoxItem}">
           <Border x:Name="border" Background="Transparent">
              <ContentPresenter />
           </Border>
           <ControlTemplate.Triggers>
              <Trigger Property="IsSelected" Value="true">
                 <Setter TargetName="border" Property="Background">
                    <Setter.Value>Transparent</Setter.Value>
                 </Setter>
              </Trigger>
           </ControlTemplate.Triggers>
        </ControlTemplate>
     </Setter.Value>
  </Setter>

A: Just off the cuff... Is there a reason you can't wrap things with a ScrollViewer and have the contained controls respond to the clicks by passing messages? ScrollViewer: http://msdn.microsoft.com/en-us/library/ms750665.aspx


text:
Q: How to change filter queryset depends on user I am using django-filter and I have two models CustomUser and Shop. How to change filter choices queryset so that user(request.user) can filter only his shops?
User
class CustomUser(AbstractBaseUser, PermissionsMixin):
    shop = models.ManyToManyField(Shop, blank=True, related_name='custom_user')

Shop
class Shop(models.Model):
    address = models.CharField(_('Address'), unique=True, max_length=64, blank=False, null=False, db_index=True)

filters.py
shops = Shop.objects.filter(is_active=True)
SHOP_CHOICES = [('All', 'All')]
for x in shops:
    SHOP_CHOICES.append((x.address, x))
SHOP_CHOICES = tuple(SHOP_CHOICES)

class ShopFilter(django_filters.FilterSet):
    address = django_filters.MultipleChoiceFilter(choices=SHOP_CHOICES)

    class Meta:
        model = Shop
        fields = ['address']

views.py
f = ShopFilter(request.GET)

A: You can filter the queryset before it's returned using the qs method.
See Filtering the primary `qs.
So in your case, you should be able to say:
@property
def qs(self):
    parent = super().qs
    owner = getattr(self.request, 'user', None)

    return parent.filter(custom_user=owner)

Haven't tested this, but this is definitely the method if you want to make any modifications to the query.


text:
Q: Since when are URLs parsed inside an inline code block? I just ran across this post which had been flagged for a broken link to example.com...
I'd like to see the `[Foobar](http://www.example.com)` URL markdown in comments.

That's all it is. For some reason, the URL in that inline code block is being parsed into an actual URL. The extra closing parentheses on the end is causing it to get flagged as an invalid link. Why on Earth is it getting parsed at all?

I'd like to see the [Foobar](http://www.example.com) URL markdown in comments.

It doesn't get parsed in the post preview as you're typing... and it's not getting parsed in this question's body either...

A: The actual question is until when were URLs parsed inside an inline code block. This looks like a typical case of "Markdown bug fixed once upon a time without baked content being regenerated", which I've now resolved with a dummy edit.


text:
Q: Javascript code for serial img loading I am new to javascript. I want a javascript code with which i can load an image which is named for every day/month/year. in a serial
i have the following code :
var year = new Array();
year = ["08", "09", "10", "11"];

var month = new Array();
month = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JULY", "AUG", "SEP", "OCT", "NOV", "DEC"];

var date = new Array();
date = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"];

var ims = "";
for (var x in year) {
 for (var y in month) {
  for (var z in date) {
   ims += "<im src=screencover/img/" + date[z] + "" + month[y] + "20" + year[0] + ".png>";
  }
 }
}
document.write(ims);

A: edit: now i get it :)
Try something this:
function nrpad(number, length) {
  var str = '' + number;
  while (str.length < length) {
      str = '0' + str;
  }
  return str;
}
var end_date = new Date(2011, 12, 1).getTime();
var start_date = new Date(2008, 1, 1).getTime();

var step = 86400000; // 1 day in msec
for(var ts = start_date; ts <= end_date; ts += step){
  var d = new Date(ts);
  var img = new Image();
  img.src = 'screencover/img/' + nrpad(d.getDay(),2) + nrpad(d.getMonth(),2) + nrpad(d.getFullYear(),2) + '.png';
  //console.log(img.src);
}

but you will have to rename your files like 'DDMMYYYY.png' (use a numeric month) if you use that example.

A: Use the built-in Date object:
function getFullYearArray(year) {
    var dates = [new Date(year, 0, 1, 0, 0, 0)],
        oneday = 1000 * 60 * 60 * 24;
    for (var i = 0; i < 364; i++) {
        dates.push( new Date(dates[i].getTime() + oneday) );
    }
    // leap years, if last day is december 30, add one
    if ( dates[i].getDate() == 30 ) {
        dates.push( new Date(dates[i].getTime() + oneday) );
    }
    return dates;
}

// usage
y08 = getFullYearArray(2008);
for (var i = 0, l = y08.length, date; i < l; i++) {
    date = y08[i];
    console.log( date.toDateString() );
}

You will have to parse the date string for the values to build your image src string, but this should get you started.
Edit
I went ahead and built out the string:
function getFullYearArray(year) {
    var dates = [new Date(year, 0, 1, 0, 0, 0)],
        oneday = 1000 * 60 * 60 * 24;
    for (var i = 0; i < 364; i++) {
        dates.push( new Date(dates[i].getTime() + oneday) );
    }
    // leap years, if last day is december 30, add one
    if ( dates[i].getDate() == 30 ) {
        dates.push( new Date(dates[i].getTime() + oneday) );
    }
    return dates;
}

// usage
var ims = "",
    y08 = getFullYearArray(2008);
for (var i = 0, l = y08.length, date, m, d, y; i < l; i++) {
    date = y08[i].toDateString();
    d = date.substring(8, 10);
    m = date.substring(4, 7).toUpperCase();
    y = date.substring(11, 15);

    ims += "<img src=\"screencover/img/" + d + m + y + ".png\">\n";
}

console.log(ims);


text:
Q: Streaming I/O in c++ I am trying to get this file stream program to work but when I run it all that happens is it outputs "Writing" instead of outputting the file. What am i doing wrong?
#include "stdafx.h"
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
  char str[10];
  ifstream b_file ( "ioTest.txt" );
  b_file>> str;
  cout<< str <<"\n";
  cin.get();

}

A: The standard input streams use whitespace as a delimiter for input. If you try extracting to a string, it will extract every character until a whitespace character is found. If you need the entire content of the file, here are a few options:
while (in >> word)
while (b_file >> word)
{
    std::cout << word;
}

This method will iterate over each whitespace-separated tokens in the input stream.
std::getline()
while (std::getline(b_file, line))
{
    std::cout << line;
}

std::getline() retrieves line-wise input, meaning it will extract every character until it reaches a delimiter. The delimiter by default is the newline but it can be specified as a third argument.

std::istream_iterator<T>
std::copy(std::istream_iterator<std::string>(b_file),
          std::istream_iterator<std::string>(),
          std::ostream_iterator<std::string>(std::cout, "\n"));

std::istream_iterator is a special-purpose stream iterator class designed to "iterate" over tokens of type T from an input stream.
rdbuf()
std::cout << b_file.rdbuf();

This is more low-level. An overload of std::ostream::operator<<() takes a stream buffer pointer as an argument, and it will extract characters directly from the buffer.


text:
Q: Where to store huge constants that my OOP class needs I'm new to OOP and wondering what's the right OOP way to do this. My class has a method getValue which is passed input (a key) that it uses to search an array and return a value.
The thing is the array is HUGE close to 200 entries and really disrupts the readability of the method, so I'm inclined to remove it from this class, but not sure where to put it. Should I create a separate class for it, or put it in a constants class Constants::getValue() or any other suggestions? Would it be wrong to remove it from this class since it should be contained within the object that needs it?
public function getValue($input) {
    switch ($input) {
        case 'in1' : { $value = array('wsj', 'kwo'); break; }
        case 'in2' : { $value = array('wpo', 'ki2'); break; }
        .....
        default:      { $value = array('wap', 'k90'); break; }
    }
    return $value;
}

A: You could create a key=>value array in another php file and include it in your class
content_array.php:
$ARRAY = array(
               'in1' => array('wsj','kwo'),
               'in2' => array('wpo','ki2'),
                ...
               'default' => array('wap','k90')
              );

then your function could look up these values like this:
public function getValue($input){
    include_once('content_array.php');
    if(array_key_exists($input, $ARRAY)){
        $value = $ARRAY[$input];
    } else {
        $value = $ARRAY['default'];
    }
    return $value;
}

If you don't like this method, you could put all your information in a JSON file, and then read that file into an array using json_decode()

A: If there are two hundred cases, and each one consists of constructing a small array from a few constants, then I'd strongly consider moving all the data into a file, and replacing it with a small amount of code that reads the file and stores everything in a map/lookup table, and then a bit of code that retrieves the correct response from the map. It would certainly be easier to maintain that way, and the code would be easier to understand.


text:
Q: How to adjust a plot box from edges without using set_position? I am making a plot for which I intend to make the plot have a certain amount of distance from the edges of the final saved file.
I have a figure in which I have two subplots which I want to have the distance from the edges. I am currently using NameOfSubplot.set_position in order to manually give distances from each edge but since I have to duplicate this for different plots and numbers, it takes a long time to find perfect numbers.
What can I use instead of set_position to give my subplots a specified edge boundary?
(Since I'm new to all this, I would appreciate it if you could type me the exact code for one subplot)
python
import matplotlib.pyplot as plt

fig1 = plt.figure(figsize=(16, 7))

a = [1990, 1995, 2000, 2005, 2010]
b = [2.5, 2.7, 2.8 , 3, 3.1]

ax1 = fig1.add_subplot(121)
box = ax1.get_position()
ax1.set_position([box.x0, box.y0 +.05, box.width * 0.9, box.height * 0.9])
l1 = ax1.plot(a, b, color='red')

ax3 = fig1.add_subplot(122)
box = ax1.get_position()
ax3.set_position([box.x0 +.4, box.y0 +.05, box.width*0.85, box.height*0.85])
l2 = ax3.plot(a, b, color='cyan')

A: Solution by ImportanceOfBeingErnest

For example, if the figure is 16 inches wide and you want one inch padding on both sides, you would set:
fig1.subplots_adjust(left=1/16, right=15/16)

Addition by user12321257:

If we want spacing from top and bottom too, it will be something like this (assuming figure is 16 inches wide and 7 inches high):
fig1.subplots_adjust(left= 1/16, right= 15/16, bottom = 1/7, top = 6/7)


text:
Q: Git push/pull fails on GitLab in Google Compute Engine I've installed GitLab on Google Compute Engine using "Click to Deploy" from the project interface. The deployment is successful after a few minutes. I can SSH into the instance, and muck around with it as expected.
I can also log in to GitLab using the web interface, and add SSH keys to my profile. So far, so good. However, when I attempt to push or pull to a new example repository, I receive this message:
Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I've removed my local SSH config so it doesn't interfere. Do I need to setup an SSH tunnel of some sort? What am I missing?
UPDATE: Wiping out my local ~/.ssh folder, and regenerating an SSH key (which I've added to my profile in GitLab) produces the following error:
Received disconnect from {GITLAB_IP_ADDRESS}: 2: Too many authentication failures for git
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

UPDATE 2: It seems GitLab may already have a solution: run sudo gitlab-ctl reconfigure. See here: https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/README.md#git-ssh-access-stops-working-on-selinux-enabled-systems

A: You need to create an SSH tunnel to communicate with GitLab.
1. Log into your development server as your user, and create a key.
ssh-keygen -t rsa

Follow the steps, and create a passcode (that you can remember) as you'd need this to pull and push code from/to GitLab.
2. Now that you've created your key, we can copy it;
cat id_rsa.pub

Copy the output of that command (including ssh-rsa), and add it to your GitLab profile. (http://my-gitlab-server.com/profile/keys/new).
3. Ensure you have the correct privilege to the project(s)
Ensure you are at role developer at the very least. (Screengrab of roles: http://i.stack.imgur.com/DSSvl.jpg)
4. Now, copy the project link
Go into your project, and find the SSH link in the top right;

5. Now back to your development server
Navigate to your directory where you'd like to work, and run the following;
$ git init
$ git remote add origin <<project_url>>
$ git fetch

Where <<project_url>> is the link we copied in step 4.
You will be prompted your password (this is your ssh key password, not your server password) and to add the host to your known_hosts file. After that, the project will start to download and you can enjoy development.
I did these steps on a CentOS 6.4 machine with Digital Ocean. But they shouldn't differ from using Google CE.
Edit
Quote from Marty Penner answer as per this comment
Solved it! Thanks to @sxleixer and @Alexander Wenzowski for figuring this out.
Apparently, SELinux was interfering with a non-standard location for the .ssh directory. I needed to run the following commands on the Compute Engine instance:
sudo yum -y install policycoreutils-python # Install the `semanage` tool
sudo semanage fcontext -a -t ssh_home_t "/var/opt/gitlab/.ssh/authorized_keys" # Allow the nonstandard ssh_home_t

See the full thread here:
Google Cloud Engine. Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

A: Solved it! Thanks to @sxleixer and @Alexander Wenzowski for figuring this out.
Apparently, SELinux was interfering with a non-standard location for the .ssh directory. I needed to run the following commands on the Compute Engine instance:
sudo yum -y install policycoreutils-python # Install the `semanage` tool
sudo semanage fcontext -a -t ssh_home_t "/var/opt/gitlab/.ssh/authorized_keys" # Allow the nonstandard ssh_home_t

See the full thread here:
Google Cloud Engine. Permission denied (publickey,gssapi-keyex,gssapi-with-mic)
UPDATE: It seems GitLab may already have a solution: run sudo gitlab-ctl reconfigure. See here: https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/README.md#git-ssh-access-stops-working-on-selinux-enabled-systems

A: In my situation the git user wasn´t set up completely. If you get in your log files messages like "User git not allowed because account is locked" (Under Centos or Redhat it´s /var/log/secure) than you simply need to activate the user via "passwd -d git"


text: Q: Cannot log in to ubuntu after modifying .profile file I modified .profile file, by adding some PATH to a program to it. I now cannot login to my ubuntu os. I tried to access via ctrl + alt+ fn but the console does not recognize any command I type. It just says "-bash : no such file or directory". I need to access my OS. How can I do that?


text:
Q: Why is $e^x$ having a different series expansion in terms of the Hermite polynomials? I had asked a question yesterday relating to "Evaluation of the first three terms of $e^x$ in terms of the Hermite polynomials".
Yes, my problem for that question was solved and I was successfully able to evaluate the integrals.
But what struck me was that the final expression was:
$$f(x)=e^{\frac{1}{4}}\left[\frac{1}{8}H_2(x)+\frac{1}{2}H_1(x)+H_0(x)\right]+\frac{1}{2\sqrt{\pi}}H_1(x)$$
which is not the same as the Taylor expansion of $e^x$ if we replace $H_n(x)$ by the tabulated values. But the working out and the formulae are correct as evident in the the hyperlinked question.
Is what I have done correct. But then why do we have that $e^{\frac{1}{4}}$ in wfront?
Someone please help.

A: I will use the statistician's Hermite polynomials, the answer is still the same.
The coefficients in both a Taylor expansion
$$
f(x) = \sum_{n=0}^\infty a_n x^n
$$
and the Hermite expansion
$$
f(x) = \sum_{n=0}^\infty d_n H_n(x)
$$
are both related to the $n^\textrm{th}$ derivative of the function.  It is well
known that for the Taylor expansion, the coefficients are proportional to the $n^\textrm{th}$ derivative evaluated at the expansion point (let's take zero)
$$
a_n = \frac{1}{n!} \frac{\partial^nf(0)}{\partial x^n}
$$
whereas the coefficient in the Hermite expansion is the weighted integral of the
$n^\textrm{th}$ derivative over the entire real line
$$
d_n = \frac{1}{n!} \int_{-\infty}^\infty \frac{\partial^nf(x)}{\partial x^n}\exp\left(-\frac{x^2}{2}\right)\frac{dx}{\sqrt{2\pi}}
$$
For $e^x$ all the derivatives are $e^x$ and the integral over the real line is $e^{\frac{1}{2}}$.  Therefore the Hermite expansion is
$$
e^x = e^{\frac{1}{2}}\sum_{n=0}^\infty \frac{H_n(x)}{n!}
$$
To see how this can be related back to the Taylor expansion, we instead calculate the Hermite expansion of $e^{x\sqrt{t}}$ and find
$$
e^{x\sqrt{t}} = e^{\frac{1}{2}t}\sum_{n=0}^\infty \frac{\sqrt{t}^nH_n(x)}{n!}
$$
Making the substitution $y=x\sqrt{t}$ leads to
$$
e^{y} = e^{\frac{1}{2}t}\sum_{n=0}^\infty \frac{\sqrt{t}^nH_n\left(\frac{y}{\sqrt{t}}\right)}{n!}
$$
The quantity $\sqrt{t}^nH_n\left(\frac{y}{\sqrt{t}}\right)$ is known as the Hermite martingale, but note it is still monic, ie the coefficient of the highest order power ($n$) is $1$, all other powers are multiplied by a power of $t$.
Taking the $t\rightarrow 0$ limit of the RHS leads to the Taylor series, since
$$
\lim_{t\rightarrow 0} \sqrt{t}^nH_n\left(\frac{y}{\sqrt{t}}\right) = y^n.
$$

A: The two expansions need not to be the same. You can imagine that the function $f(x)$ is a vector, if $u_n(x)$ is a basis then
$$
f(x) = \sum_n \langle u | f\rangle u_n(x) = \sum_n a_n u_n(x)
$$
where $\langle \cdot | \cdot\rangle$ denotes the inner product. Depending on the selection of the basis $u_n(x)$, the coefficients of the expansion $a_n$ are going to be different, and so is going to be the value of the RHS sum, should it be truncated at a given number $n$


text:
Q: Read multiple line from txt | JAVA How to read multiple line in a .txt file ?
    //WRITE A ELEMENT OF ARRAY TO TXT
public static void write_array_element(Persona value,String path) throws IOException{
    BufferedWriter out = new BufferedWriter(new FileWriter(new File(path),true));
    out.write(value.name);
    out.newLine();
    out.write(value.surname);
    out.newLine();
    out.write(value.d);
    out.newLine();
    out.write(value.m);
    out.newLine();
    out.write(value.y);
    out.newLine();
    out.newLine();
    out.flush();
    out.close();

}

This function write five line in a .txt at Append Write Mode, in other function I read the five line for set up element, but not read all lines but only first five line and leave out other lines.
//READ ELEMENT OF ARRAY FROM TXT
public static Persona read_from_txt(String path) throws IOException, ClassNotFoundException{
    BufferedReader in = new BufferedReader(new FileReader(new File(path)));
    String name = in.readLine();
    String surname = in.readLine();
    String d = in.readLine();
    String m = in.readLine();
    String y = in.readLine();
    Persona tmp = new Persona(name,surname,d,m,y);
    return tmp;
}

With in.readLine(); I can read the five's element line , but when I try to set up all elements from txt to array, I get only first element of txt.
Help me ?

A:
I need a set cycle to EOF, but how ?

while((line = in.readLine()) != null){
        //...
}

Also, make a method in your Persona class which will return personas values ready for your txt. So you can write persona info at once.
example:
String printPersona(){ return name + "\n" + surname + "\n" + ... }

(or you can name it toString())


text:
Q: C++1y/C++14: Variable Template Specialization? According to C++1y/C++14 N3690, does the type of a variable template specialization have to be the same as the type of the primary template?
template<int x>
char y = f(x);

template<>
double y<42> = g();

And if so, is it possible to leave the primary undefined somehow?
template<int x>
???? y = ???; // undefined

template<>
double y<42> = g();

Where is this covered in the draft?
The equivalent functionality for a class template would be:
template<int x>
struct S
{
    static char y;
};

template<>
struct S<42>
{
    static double y;
};

and
template<int x>
struct S; // undefined

template<>
struct S<42>
{
    static double y;
};

A: Does the type of a variable template specialization have to be the same as the type of the primary template?
No, an explicit (or partial) specialization of a variable template can specify a type different from the type that would be implied by an implicit instantiation. When implementing the feature for Clang, we discovered that the specification had no rule requiring the type to match in this case, and we brought the issue to the C++ core working group, where it was confirmed that this omission was intentional.
Is it possible to leave the primary undefined somehow?
It is not possible to declare the primary variable template without specifying a type -- there is no syntax that would allow such a thing.
Where is this covered in the draft?
Both of these are covered by omission -- there is no rule requiring the types to match, and there is no syntax for declaring a variable template without a type. So I can't point you at any particular part of the standard and say "here's where the rule isn't".
If you have access to the C++ standard committee's reflectors, see the thread starting with core-23901 for the discussion of this.

A: The following compiles with clang trunk -std=c++1y:
#include <iostream>

template<int x>
char y = 3;

template<>
double y<42> = 2.5;

char c {y<17>};

double d {y<42>};

So either a specialization of a variable template doesn't need to have the same type as its primary, or clang has a buggy implementation of N3690

A: I would fully expect that the declaration of a specialization needs to match the primary template exactly, including its type. This isn't anything new for variable templates. I haven't chased down the details in the standard, yet, to see where it specifies this detail.
The code below seems to do something akin to what you want, i.e., leave the variable type sort of open:
#include <iostream>

template <int X> struct var_type { typedef int type; };
template <> struct var_type<42> { typedef double type; };

int    f(int x) { return x; }
double g()    { return 3.14; }

template <int X>
typename var_type<X>::type var = f(X);
template <>
typename var_type<42>::type var<42> = g();

int main()
{
    std::cout << "var<17>=" << var<17> << '\n';
    std::cout << "var<42>=" << var<42> << '\n';
}

A:
And if so, is it possible to leave the primary undefined somehow?

I think this effectively does it:
template<class T> std::enable_if_t<sizeof(T*)==0> var;
template<> auto var<float >  = 1;
template<> auto var<double>  = 2;

var<char>, for example, seems to be an invalid variable.
For non-type template argument (NTTA) case, it is more tricky I guess, because you need to contemplate all non instantiable cases
template<int x> std::enable_if_t<x!=42 and x!=43> var;
template<> auto var<42>  = 1;
template<> auto var<43>  = 2;

In this case, var<41> is unintanstiable.
I am not sure how robust this is.
It works with clang and gcc: https://godbolt.org/z/hxcnjMrce
Finally, may be more readable:
template<class T> auto var  = std::enable_if_t<sizeof(T*)==0>{};
template<int x>   auto var2 = std::enable_if_t<x!=42 and x!=43>{};

EDIT: Actually the NTTA is easier, the only challenge is to make the boolean expression depend on the parameter x.
template<int x> auto var2 = std::enable_if_t<x!=x>{};
template<> auto var2<42>  = 1;
template<> auto var2<43>  = 2;

This is inspired by this other trick: https://devblogs.microsoft.com/oldnewthing/20200311-00/?p=103553

A: It's a bit risky to extrapolate that Clang is expressing the feature intended for standardization. (NB: I didn't refer to anything for this answer.)
Of course the fallout from allowing a change of type is that you can't specialize the template after it's been referenced in any way, whereas for all other kinds of templates the cutoff time is at ODR-use. Unless they're planning something wacky, this looks like a Clang bug.
You can always use a type template to declare the type of the variable template.
template< typename t >
struct x_type { typedef … type; };

template< typename t >
typename x_type< t >::type x = …;

Now x_type may be specialized. This just guards against the possibility that Clang is currently buggy. It doesn't allow you to refer to an object of indeterminate type. C++ just doesn't support that. Referring to the object ODR-uses the class template specialization.


text:
Q: MongoDB Query to match both single entry and array elements I have a problem with MongoDB QueryBuilder.
Assume I have a number of documents, that can contain one or more users:
{
  "_id": "document1",
  "data": {
    "user": {
      "credentials": {
        "name": "John",
        "lastname": "Watson",
        "middle": "Hemish"
      }
    }
  }
}

{
  "_id": "document2",
  "data": {
    "user": [
      {
        "credentials": {
          "name": "John",
          "lastname": "Nicholson",
          "middle": "Joseph"
        }
      },
      {
        "credentials": {
          "name": "Mary",
          "lastname": "Watson",
          "middle": ""
        }
      }
    ]
  }
}

{
  "_id": "document3",
  "data": {
    "user": [
      {
        "credentials": {
          "name": "John",
          "lastname": "Watson",
          "middle": "Hemish"
        }
      },
      {
        "credentials": {
          "name": "John",
          "lastname": "Nicholson",
          "middle": "Joseph"
        }
      },
      {
        "credentials": {
          "name": "Mary",
          "lastname": "Watson",
          "middle": ""
        }
      }
    ]
  }
}

What I am trying to do is the query, that will return only those documents containing  John Watson as a user.
Here what I got so far:
1.
QueryBuilder qb = QueryBuilder.start("credentials.lastname").is("Watson").and("credentials.name").is("John");
DBObject query = QueryBuilder.start("data.user").elemMatch(qb.get()).get();

this query will return only document3: there is no array in document1 and no match in document2 (but I would like it to return document1 and document3)
2.
DBObject query = QueryBuilder.start("data.user.credentials.lastname").is("Watson").and("data.user.credentials.name").is("John").get();

this one will return all three documents: document1 and document3 are desired match, but the query will match as well document2, for it has Watson and John in query fields in the array, no matter that they are separate entries.
Is there any way to make a right query that will return document1 and document3 for John Watson?
I am trying to do it in Java, but any other example would be fine.
Right now I use a workaround combining results from both queries: first I get limit(100) results from the query with elementMatch(), then, if there are less than 100 results, I do the second query and filter all wrong matches. But I hope there is a better and more effective way to get those results.

A: I could give you at best like the following where user would be in an array as unwind value of the key data. I think a little bit more effort would lead you to the exact format as you want.
I am sharing it as I think it should serve the purpose or anyhow it should help you.
The aggregation query:
db.tuttut.aggregate([
    {$unwind:"$data.user"},
    { $project: {
        _id:1,
        data:1,
        temp: {name:"$data.user.credentials.name",
               lastname:"$data.user.credentials.lastname"}
        } }  ,
    { $group:{
        _id:"$_id" ,
        data: {$addToSet: "$data"} ,
        temp:{ $addToSet: "$temp"  } }  },
    { $match:{ temp:{name:"John",lastname:"Watson"}  }  }  ,
    {$project:{_id:1, data:1}}
]).pretty()

Returned Result:
{
        "_id" : "document1",
        "data" : [
                {
                        "user" : {
                                "credentials" : {
                                        "name" : "John",
                                        "lastname" : "Watson",
                                        "middle" : "Hemish"
                                }
                        }
                }
        ]
}
{
        "_id" : "document3",
        "data" : [
                {
                        "user" : {
                                "credentials" : {
                                        "name" : "John",
                                        "lastname" : "Watson",
                                        "middle" : "Hemish"
                                }
                        }
                },
                {
                        "user" : {
                                "credentials" : {
                                        "name" : "Mary",
                                        "lastname" : "Watson",
                                        "middle" : ""
                                }
                        }
                },
                {
                        "user" : {
                                "credentials" : {
                                        "name" : "John",
                                        "lastname" : "Nicholson",
                                        "middle" : "Joseph"
                                }
                        }
                }
        ]
}


text:
Q: How to extract certain db fields from a parent model using STI in Rails Suppose I have a Mechanism model, and its schema is something like this:
t.string   "image"
t.string   "type"
t.string   "speed"
t.string   "name"

Now suppose I would like to create a child model called Car, which fully inherits the Mechanism model fields using STI (Car < Mechanism), but also applies its own:
t.string   "wheels"
t.string   "metal_type"
t.string   "fuel_consumption"
...

In the end I would basically like to have many models, that share certain db field with Mechanism model, and behave like a Mechanism.
Now I know that STI does not work like this, but I would like to know what other options do I have?

A: One non-STI solution would be to have a 1-M relationship between Car and Mechanism
class Car < AtiveRecord::Base
  belongs_to :mechanism
end

class Mechanism < ActiveRecord::Base
  has_many :cars
end

This would let you do something like
car = Car.first

car.mechanism.speed

Understanding that is not what you're looking for, check out the delegate method.
class Car < AtiveRecord::Base
  belongs_to :mechanism

  delegate :image, :type, :speed, :name, to: :mechanism
end

class Mechanism < ActiveRecord::Base
  has_many :cars
end

Now you can do the following
car = Car.first

car.speed

A: You can use one of the inheritance gems.
acts_as_relation & multiple_table_inheritance will help you with your work


text:
Q: Jquery Datepicker remove days of previous or next month from the current month I'd like to remove days of previous or next month from current viewing month to let you understand exactly what I mean I'll attache the screen shot where I highlighted exactly what I need to remove

I've tried this code
$('.ui-state-disabled').html('').closest('td').removeClass('highlight-date');
$(document).on('click', '.ui-datepicker-next', function(event) {
    $('.ui-state-disabled').html('').closest('td').removeClass('highlight-date');
});
$(document).on('click', '.ui-datepicker-prev', function(event) {
    $('.ui-state-disabled').html('').closest('td').removeClass('highlight-date');
}); //removes all days of previos month from the current month

it removes the days however when I click on a day it reapears
this code
$('.ui-state-disabled').html('').closest('td').removeClass('highlight-date');

does not work in the datepicker settings like onSelect or beforeShowDay:
what is the solution, I really need to remove the days

A: They are off by default.
You add these properties to your datepicker to show them:
showOtherMonths: true,
selectOtherMonths: true

https://jqueryui.com/datepicker/#other-months


text:
Q: Hide error text until box / button clicked on I'm wanting the errName errEmail errMessage text to not be displayed until the user clicks on the Name, Email, or Message box. Also I'm wanting to not show $result until the submit button is pressed. As of right now it just displays the errName, errEmail, errMessage, and the alert even if the user is not interacting with the submit form.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
global $result;
if (isset($_POST["submit"])) {
    $errName ="";
    $errEmail ="";
    $errMessage ="";
    $result="";
    $name = $_POST['name'];
    $business = $_POST['business'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = '------';
    $to = '-----';
    $subject = 'Message from user on website';
    $body ="-------";
}
// Check if name has been entered
if (!isset($_POST) || !key_exists('name', $_POST) || !filter_var($_POST['name'])) {
    $errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!isset($_POST) || !key_exists('email', $_POST) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!isset($_POST) || !key_exists('message', $_POST) || !filter_var($_POST['message'])) {
    $errMessage = 'Please enter your message';
}
// If there are no errors, send the email
if (!isset($errName) && !isset($errEmail) && !isset($errMessage)) {
    $result .= '

Thank You! We will be in touch
';
} else {
    $result .= '

Sorry there was an error sending your message. Please try again later.
';
}

Email Form

                <form class="form-horizontal" role="form" method="post" action="index.php#contact">

                        Name

                            <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php showPost('name'); ?>">
                            <?php if (isset($errName)) {
                  echo "
$errName
";
                }?>

                        Business

                            <input type="text" class="form-control" id="business" name="business" placeholder="Business name" value="<?php showPost('business'); ?>">

                        Email

                            <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com" value="<?php showPost('email'); ?>">
                            <?php if (isset($errEmail)) {
                  echo "
$errEmail
";
                }?>

                        Message

                            <textarea class="form-control" rows="4" name="message"><?php showPost('message');?></textarea>
                            <?php if (isset($errMessage)) {
                  echo "
$errMessage
";
                }?>

                            <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">

                </form>

```

A: You need to put all your php code inside if (isset($_POST["submit"])) ,because the condition !isset will always be true when you load your php page . Do below change in your code :
if (isset($_POST["submit"])) {
    $errName ="";
    $errEmail ="";
    $errMessage ="";
    $result="";
    $name = $_POST['name'];
    $business = $_POST['business'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = '------';
    $to = '-----';
    $subject = 'Message from user on website';
    $body ="-------";

// Check if name has been entered
if (!isset($_POST) || !key_exists('name', $_POST) || !filter_var($_POST['name'])) {
    $errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!isset($_POST) || !key_exists('email', $_POST) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!isset($_POST) || !key_exists('message', $_POST) || !filter_var($_POST['message'])) {
    $errMessage = 'Please enter your message';
}
// If there are no errors, send the email
if (!isset($errName) && !isset($errEmail) && !isset($errMessage)) {
    $result .= '

Thank You! We will be in touch
';
} else {
    $result .= '

Sorry there was an error sending your message. Please try again later.
';
}
} // end of isset


text:
Q: Null total spin and maximal entanglement Is it true that if the total spin of two entangled particles is 0 on all axes, then they must be maximally entangled?

A: No, this isn't true. Probably the simplest example is two spin-1 particles, with both of them in the $L_z=0$ state,
$$
|\psi⟩=\left|1,0\right>\otimes\left|1,0\right>.
$$
This is completely separable, and it has zero expectation value for the total angular momentum along any axis, since
$$
 \left<\psi\middle|L_x\middle|\psi\right>
=\left<\psi\middle|L_y\middle|\psi\right>
=\left<\psi\middle|L_z\middle|\psi\right>
=0.
$$
If this is not what you mean then you need to ask a more precise question.


text:
Q: nginx/php7-fpm on docker gives 504 error when I change the simplest html I've tried about everything but I do not expect the regular 504 solutions will solve this.
I have a dev environment on my M1 Macbook where I have 2 docker containers running. One is nginx/php7-fpm and the other a mongodb instance. My webapp ran without problems for years and since yesterday suddenly times out. I update my font-awesome lib and thought that was the problem but going back to the previous version doesn't make a difference.
What now happens is I restart the docker instances and everything works fine and fast (avg response is sub second, no large or long requests). As soon as I change the simples of code, for instance I change a random label 'menu' to 'menu2' and refresh the page it drops a 504 gateway timeout on me. When I restart the docker instance again, it works again with the change made.
It also sometimes gives me not a 504 but a ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK) error...refresh again then results in a 504.
Any idea on where to fix this?
Thx


text:
Q: update file on ssh and link to local computer I may be being ignorant here, but I have been researching for the past 30 minutes and have not found how to do this. I was uploading a bunch of files to my server, and then, prior to them all finishing, I edited one of those files. How can I update the file on the server to the file on my local computer?
Bonus points if you tell me how I can link the file on my local computer to auto update on the server when I connect (if possible of course)

A: Just use scp and copy the file back.
scp [user]@[address]:/[remotepath]/[remotefile] [localfolder] if you want to copy the file on the server back to your local machine or
scp [localfolder]/[filename] [user]@[address]:/[remotepath] in case you want to copy the file again to the server. The elements in [] have to be exchanged with actual paths and or file names. On the remote it has to be the absolute path and on the local machine it can be absolute or relative.More information on scp
This of course means that the destination file will be overwritten.
Maybe rsync would be an option. It is capable to synchronize different folders.
rsync can be used to sync folders over the network and is capable to be combined with ssh.

A: Have you considered Dropbox or SVN ?

A: I don't know your local computer OS, but if it is Linux or OSX, you can consider LFTP. This is an FTP client which supports SFTP://. This client has the "mirror" functionality. With a single command you can mirror your local files against a server.
Note: what you need is a reverse mirror. in LFTP this is mirror -r


text:
Q: Jenkins Powershell write to console I have a jenkins job that calls a powershell file.  When I use it from a freestyle project it shows the powershell execution in the console output.  Having switched it to a pipeline job I no longer see the output.
Currently my pipeline looks like this:
 pipeline
 {
    stages
    {
        stage ('Deploy To Dev')
         {
            steps
             {
                powershell '"%WORKSPACE%\\SpearsLoad\\Scripts\\CIDeployToDev.Ps1"'
             }
        }
    }
}

but I get no logging of the powershell steps.
Following the documentation I tried changing the stage to:
pipeline
{
    stages
    {
        stage ('Deploy To Dev')
            {
            steps
            {
                node('Deploy the SSIS load')
                {
                    //Deploy the SSIS load
                    def msg = powershell(returnStdout: true, script: '"%WORKSPACE%\\SpearsLoad\\Scripts\\CIDeployToDev.Ps1"')
                    println msg
                }
            }
        }
    }
}

but that gives:

Expected a step @ line 123, column 6. def msg =
  powershell(returnStdout: true, script:
  '"%WORKSPACE%\SpearsLoad\Scripts\CIDeployToDev.Ps1"')

I feel like I am missing something quite fundamental. What am I doing wrong ?

A: You need to wrap your pipeline execution into script section, because you're trying to use scripted syntax in declarative pipeline:
script {
    //Deploy the SSIS load
    def msg = powershell(returnStdout: true, script: '"%WORKSPACE%\\SpearsLoad\\Scripts\\CIDeployToDev.Ps1"')
    println msg
}

A: For anyone who comes here looking for answers, I need to point out that there were actually 3 separate problems with the code:

*

*The lack of a script section as per the accepted answer.

*The powershell was not actually running due to not calling it correctly

*The powershell was not running due to spaces in the %WORKSPACE% variable

in the end, I went with:
script {
    def msg = powershell(returnStdout: true, script: " & './SpearsLoad\\Scripts\\CIDeployToDev.Ps1'")
    println msg
}

which actually works!

A: I use
Write-Host "My message"

in powershell. This will show up in the log.


text:
Q: Why does my Task Manager window outline keep disappearing?
Possible Duplicate:
Task manager menu, titlebar and tabs have disappeared

I'm not sure what the proper term for the window outline is (chrome, I think?), but it keeps disappearing.

As you can see, theres no File->Exit or buttons that allow me to minimize or close this dialog. So instead it stays on top of everything else (unless I 'Switch To' another window). There is also no Processes tab or anything.
Since you cant right click the toolbar or bring up another instance of Task Manager, the only way to actually kill this dialog seems to be restarting. However the next time I bring up Task Manager, it will still refuse to go away.
Anyone know whats going on? I'm running 32-bit Vista SP1.

A: It's a feature in Task Manager. Double click anywhere in the window and they will come back. It's sort of a mini mode that's been available for many years.

A: It's called tiny footprint mode. Double click an area of the window to go back to normal.


text:
Q: Restrict write access in Firebase Rules to Cloud Functions Can I get an ID for a Firebase function (a database trigger) to use with Firebase Rules? I need to allow only a Firebase function to write to the database.
Update:
To clarify, I am using a Trigger Database Firebase function, and I want to allow only that function to write to the database, but allow users to read. I tried this approach Allowing write access only to Cloud Functions for Firebase but get an error The default Firebase app already exists.. However this link is for Cloud Functions and not Firebase functions, and I couldn't find any other related questions.

A: Seems that there is a misunderstood about Cloud Functions for Firebase and Google Cloud Functions (the error message is because is used code for a Google Cloud Functions within a Cloud Function for Firebase), but anyway the answer of this question is that you can use adminRef instead ref in the code of the function that will write the data on Firebase database:
event.data.adminRef instead event.data.ref
this will give you full read and write access instead of end-user access (please note that also you must take care to indicate within the rules deny to everybody).
Update: Seems that adminFef was replaced by ref due changes on Firebase, so follow the example to the respective replacement.


text:
Q: Boolean guard in PROLOG I have this prolog code that generates a txt file with latex code
worlds(_,_,_,_,[]) :- !.

worlds(Stream,Count,Right,Number,[Head|Tail]) :-
C is Count+1,
Number2 is Number+1,
single_world(Stream,Right,Number2,C,Head),
Right2 is Right+15,
worlds(Stream,C,Right2,Number2,Tail).

single_world(_,_,_,_,[]) :- !.

single_world(Stream,Right,Number,C,[Head|Tail]) :-
Right2 is Right+15,
atomic_list_concat(Head,',',Label),
world_sphere(Stream,5,Right2,Label,Number,C,Head),
write(Stream,"\\draw [->] ("),
write(Stream, C),
write(Stream, ") to ("),
write(Stream, Number),
writeln(Stream, ");"),
single_world(Stream,Right2,Number,C,Tail).

world_sphere(_,_,_,_,_,_,[]) :- !.

world_sphere(Stream,Width,Right,Label,Number,C,[_|[]]):-
write(Stream, "\\node[circle, minimum size="),
write(Stream, Width),
write(Stream,"mm, draw, label = {[label distance=0cm]:$"),
write(Stream, Label),
write(Stream, "$}]"),
write(Stream, "[below of = "),
Below is C-1,
write(Stream, Below),
write(Stream,"][right = "),
write(Stream,Right),
write(Stream,"mm] ("),
write(Stream, Number),
writeln(Stream,"){};").

world_sphere(Stream,Width,Right,Label,Number,C,[_|Tail]) :-
write(Stream, "\\node[circle, minimum size="),
write(Stream, Width),
write(Stream,"mm, draw]"),

write(Stream,"[below of = "),
Below is C-1,

write(Stream, Below),
write(Stream,"]"),
write(Stream,"[right = "),
write(Stream,Right),
write(Stream,"mm] ("),
write(Stream, Number),
writeln(Stream,"){};"),
Width2 is Width+5,
world_sphere(Stream,Width2,Right,Label,Number,C,Tail).

list_length(Xs,L) :- list_length(Xs,0,L) .

list_length( []     , L , L ) .
list_length( [_|Xs] , T , L ) :-
T1 is T+1 ,
list_length(Xs,T1,L).

draw_spheres(FileName):-
open(FileName, write, Stream),
list_length([1,2], Worlds),
worlds(Stream,0,4,Worlds,[[[1,2,3,4]],[[1],[1,3],[1,2,3,4]],[[1,2,3,4]],    [[1,2,3,4]]]),!,
close(Stream).

The code generates the following txt file that needs to be compiled with latex tools:
\node[circle, minimum size=5mm, draw][below of = 0][right = 19mm] (3){};
\node[circle, minimum size=10mm, draw][below of = 0][right = 19mm] (3){};
\node[circle, minimum size=15mm, draw][below of = 0][right = 19mm] (3){};
\node[circle, minimum size=20mm, draw, label = {[label distance=0cm]:$1,2,3,4$}]    [below of = 0][right = 19mm] (3){};
\draw [->] (1) to (3);
node[circle, minimum size=5mm, draw, label = {[label distance=0cm]:$1$}][below of = 1][right = 34mm] (4){};
\draw [->] (2) to (4);
\node[circle, minimum size=5mm, draw][below of = 1][right = 49mm] (4){};
\node[circle, minimum size=10mm, draw, label = {[label distance=0cm]:$1,3$}][below of = 1][right = 49mm] (4){};
\draw [->] (2) to (4);
\node[circle, minimum size=5mm, draw][below of = 1][right = 64mm] (4){};
\node[circle, minimum size=10mm, draw][below of = 1][right = 64mm] (4){};
\node[circle, minimum size=15mm, draw][below of = 1][right = 64mm] (4){};
\node[circle, minimum size=20mm, draw, label = {[label distance=0cm]:$1,2,3,4$}][below of = 1][right = 64mm] (4){};
\draw [->] (2) to (4);
\node[circle, minimum size=5mm, draw][below of = 2][right = 49mm] (5){};
\node[circle, minimum size=10mm, draw][below of = 2][right = 49mm] (5){};
\node[circle, minimum size=15mm, draw][below of = 2][right = 49mm] (5){};
\node[circle, minimum size=20mm, draw, label = {[label distance=0cm]:$1,2,3,4$}][below of = 2][right = 49mm] (5){};
\draw [->] (3) to (5);
\node[circle, minimum size=5mm, draw][below of = 3][right = 64mm] (6){};
\node[circle, minimum size=10mm, draw][below of = 3][right = 64mm] (6){};
\node[circle, minimum size=15mm, draw][below of = 3][right = 64mm] (6){};
\node[circle, minimum size=20mm, draw, label = {[label distance=0cm]:$1,2,3,4$}][below of = 3][right = 64mm] (6){};
\draw [->] (4) to (6);

And what i want is something like this eliminating "below of 0" for the nodes of the first world:
\node[circle, minimum size=5mm, draw][right = 19mm] (3){};
\node[circle, minimum size=10mm, draw][right = 19mm] (3){};
\node[circle, minimum size=15mm, draw][right = 19mm] (3){};
\node[circle, minimum size=20mm, draw, label = {[label distance=0cm]:$1,2,3,4$}][right = 19mm] (3){};
\draw [->] (1) to (3);
\node[circle, minimum size=5mm, draw, label = {[label distance=0cm]:$1$}][below of = 1][right = 34mm] (4){};
\draw [->] (2) to (4);
\node[circle, minimum size=5mm, draw][below of = 1][right = 49mm] (4){};
\node[circle, minimum size=10mm, draw, label = {[label distance=0cm]:$1,3$}][below of = 1][right = 49mm] (4){};
\draw [->] (2) to (4);
\node[circle, minimum size=5mm, draw][below of = 1][right = 64mm] (4){};
\node[circle, minimum size=10mm, draw][below of = 1][right = 64mm] (4){};
\node[circle, minimum size=15mm, draw][below of = 1][right = 64mm] (4){};
\node[circle, minimum size=20mm, draw, label = {[label distance=0cm]:$1,2,3,4$}]    [below of = 1][right = 64mm] (4){};
\draw [->] (2) to (4);
\node[circle, minimum size=5mm, draw][below of = 2][right = 49mm] (5){};
\node[circle, minimum size=10mm, draw][below of = 2][right = 49mm] (5){};
\node[circle, minimum size=15mm, draw][below of = 2][right = 49mm] (5){};
\node[circle, minimum size=20mm, draw, label = {[label distance=0cm]:$1,2,3,4$}][below of = 2][right = 49mm] (5){};
\draw [->] (3) to (5);
\node[circle, minimum size=5mm, draw][below of = 3][right = 64mm] (6){};
\node[circle, minimum size=10mm, draw][below of = 3][right = 64mm] (6){};
\node[circle, minimum size=15mm, draw][below of = 3][right = 64mm] (6){};
\node[circle, minimum size=20mm, draw, label = {[label distance=0cm]:$1,2,3,4$}][below of = 3][right = 64mm] (6){};
\draw [->] (4) to (6);

I'm new to prolog,
I try to add some guards but it doesn't work.
Can anyone help me?

A: Full working example with fix to your question and cut to remove choice points.
File: spheres.pl
:- module(spheres,
    [
        draw_spheres/1
    ]).

% -----------------------------------------------------------------------------

worlds(_,_,_,_,[]) :- !.
worlds(Stream,Count,Right,Number,[Head|Tail]) :-
    C is Count+1,
    Number2 is Number+1,
    single_world(Stream,Right,Number2,C,Head),
    Right2 is Right+15,
    worlds(Stream,C,Right2,Number2,Tail).

single_world(_,_,_,_,[]) :- !.
single_world(Stream,Right,Number,C,[Head|Tail]) :-
    Right2 is Right+15,
    atomic_list_concat(Head,',',Label),
    world_sphere(Stream,5,Right2,Label,Number,C,Head),
    write(Stream,"\\draw [->] ("),
    write(Stream, C),
    write(Stream, ") to ("),
    write(Stream, Number),
    writeln(Stream, ");"),
    single_world(Stream,Right2,Number,C,Tail).

world_sphere(_,_,_,_,_,_,[]) :- !.
world_sphere(Stream,Width,Right,Label,Number,C,[_|[]]) :-
    write(Stream, "\\node[circle, minimum size="),
    write(Stream, Width),
    write(Stream,"mm, draw, label = {[label distance=0cm]:$"),
    write(Stream, Label),
    write(Stream, "$}]"),
    Below is C-1,
    (
        Below == 0
    ->
        true
    ;
        write(Stream, "[below of = "),
        write(Stream, Below),
        write(Stream,"]")
    ),
    write(Stream,"[right = "),
    write(Stream,Right),
    write(Stream,"mm] ("),
    write(Stream, Number),
    writeln(Stream,"){};"), !.
world_sphere(Stream,Width,Right,Label,Number,C,[_|Tail]) :-
    write(Stream, "\\node[circle, minimum size="),
    write(Stream, Width),
    write(Stream,"mm, draw]"),
    Below is C-1,
    (
        Below == 0
    ->
        true
    ;
        write(Stream,"[below of = "),
        write(Stream, Below),
        write(Stream,"]")
    ),
    write(Stream,"[right = "),
    write(Stream,Right),
    write(Stream,"mm] ("),
    write(Stream, Number),
    writeln(Stream,"){};"),
    Width2 is Width+5,
    world_sphere(Stream,Width2,Right,Label,Number,C,Tail).

list_length(Xs,L) :-
     list_length(Xs,0,L) .

list_length( []     , L , L ) .
list_length( [_|Xs] , T , L ) :-
    T1 is T+1 ,
    list_length(Xs,T1,L).

draw_spheres(FileName):-
    open(FileName, write, Stream),
    list_length([1,2], Worlds),
    worlds(Stream,0,4,Worlds,[[[1,2,3,4]],[[1],[1,3],[1,2,3,4]],[[1,2,3,4]],    [[1,2,3,4]]]),
    close(Stream).

Example run
Welcome to SWI-Prolog (threaded, 64 bits, version 8.3.28-20-g6f8a68f2b)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
Please run ?- license. for legal details.

For online help and background, visit https://www.swi-prolog.org
For built-in help, use ?- help(Topic). or ?- apropos(Word).

?- working_directory(_,'C:/Users/groot').
true.

?- [spheres].
true.

?- draw_spheres('a.txt').
true.

File: a.txt
\node[circle, minimum size=5mm, draw][right = 19mm] (3){};
\node[circle, minimum size=10mm, draw][right = 19mm] (3){};
\node[circle, minimum size=15mm, draw][right = 19mm] (3){};
\node[circle, minimum size=20mm, draw, label = {[label distance=0cm]:$1,2,3,4$}][right = 19mm] (3){};
\draw [->] (1) to (3);
\node[circle, minimum size=5mm, draw, label = {[label distance=0cm]:$1$}][below of = 1][right = 34mm] (4){};
\draw [->] (2) to (4);
\node[circle, minimum size=5mm, draw][below of = 1][right = 49mm] (4){};
\node[circle, minimum size=10mm, draw, label = {[label distance=0cm]:$1,3$}][below of = 1][right = 49mm] (4){};
\draw [->] (2) to (4);
\node[circle, minimum size=5mm, draw][below of = 1][right = 64mm] (4){};
\node[circle, minimum size=10mm, draw][below of = 1][right = 64mm] (4){};
\node[circle, minimum size=15mm, draw][below of = 1][right = 64mm] (4){};
\node[circle, minimum size=20mm, draw, label = {[label distance=0cm]:$1,2,3,4$}][below of = 1][right = 64mm] (4){};
\draw [->] (2) to (4);
\node[circle, minimum size=5mm, draw][below of = 2][right = 49mm] (5){};
\node[circle, minimum size=10mm, draw][below of = 2][right = 49mm] (5){};
\node[circle, minimum size=15mm, draw][below of = 2][right = 49mm] (5){};
\node[circle, minimum size=20mm, draw, label = {[label distance=0cm]:$1,2,3,4$}][below of = 2][right = 49mm] (5){};
\draw [->] (3) to (5);
\node[circle, minimum size=5mm, draw][below of = 3][right = 64mm] (6){};
\node[circle, minimum size=10mm, draw][below of = 3][right = 64mm] (6){};
\node[circle, minimum size=15mm, draw][below of = 3][right = 64mm] (6){};
\node[circle, minimum size=20mm, draw, label = {[label distance=0cm]:$1,2,3,4$}][below of = 3][right = 64mm] (6){};
\draw [->] (4) to (6);


text:
Q: Why doesn't this assembly program work correct? I'm trying to make a simple x86 assembly code, which gets an input from the user, and then matches that against a hardcoded password in the memory, and prints a message to the user accordingly (correct/incorrect).
Here is my code:
%macro write_string 2
    mov   eax, 4
    mov   ebx, 1
    mov   ecx, %1
    mov   edx, %2
    int   80h
%endmacro

%macro read_string 2
    mov eax, 3
    mov ebx, 0
    mov ecx, %1
    mov edx, %2
    int 80h
%endmacro

section .text
    global _start

_start:
    write_string msg, lenMsg

    read_string string, 32

    mov [readBytes], eax

    mov ecx, 0
    l1:
        mov eax, string
        add eax, ecx

        mov byte al, [eax]

        mov eax, pwd
        add eax, ecx

        mov byte bl, [eax]

        cmp bl, al
        jne incorrect
        inc ecx
        cmp ecx, [readBytes]
        jne l1

    correct:
        write_string txt1, txt1Len
        jmp exit

    incorrect:
        write_string txt2, txt2Len

    exit:
        write_string lineBreak, 1
        mov eax,1
        int 0x80

section .bss
    readBytes: resb   1

section .data

msg db 'Password: '
lenMsg equ $ - msg

string times 100 db 0

pwd  db 'secretPass1'

txt1 db 'Correct', 0xa
txt1Len equ $ - txt1
txt2 db 'Incorrect', 0xa
txt2Len equ $ - txt2

lineBreak db 0xa

The program compiles, but when I run it and type an input, it always prints the "incorrect" message, even though I used the right password.
Can you tell me what I did wrong?
And I have another question, what's the difference between:
section .bss
    string: resb   100

and:
section .data
    string times 100 db 0

For allocating uninitialized data?
Thanks

A:
mov byte al, [eax]
mov eax, pwd

As ecm told you, loading the address to pwd overwrites the character already loaded in the AL register.
You could solve this by using a different register for traversing pwd OR you could correct it and simplify the code by using a different addressing mode:
  mov [readBytes], eax
  xor ecx, ecx
Verify:
  mov dl, [string + ecx]
  mov bl, [pwd + ecx]
  cmp dl, bl
  jne incorrect
  inc ecx
  cmp ecx, eax            ; No need to compare with a memory based variable
  jb  Verify

There are additional problems:

*

*In the .bss you reserved 1 byte for the readBytes variable that is in fact a dword and so requires 4 bytes of storage. Because you're only using that one variable in the .bss, you won't notice the error now, but wait until you (have to) write a program with more variables!

*Your password verification loop runs over all of the inputted characters disregarding the fact that if the input was longer or shorter (including empty) than the stored password, it becomes futile to compare the characters.
    mov [readBytes], eax
    cmp eax, 11          ; Length of the hardcode password 'secretPass1'
    jne incorrect
    xor ecx, ecx
  Verify:

The difference between resb 100 (.bss) and times 100 db 0 (.data).
times 100 db 0 is performed by the assembler. It physically puts this many zero bytes in your executable. You're guaranteed that the memory will contain 100 zero bytes.
resb 100 is 'performed' by the OS when the program starts. Many times this memory will also contain zero bytes but the idea is that you should not count on this to be true.


text:
Q: Hierarchical tree navigation in Django I am looking for the best way to implement a tree navigation system in my Django app. I have a hierarchy of pages, and I need a way to set links as active on the various levels of the hierarchy. The only solutions that I have come across use the database in a CMS-like fashion, but that is not what I'm looking for. Any suggestions?

A: django-mptt is a pretty decent implementation of the parent/child relationships with very good speed.
https://github.com/django-mptt/django-mptt


text:
Q: Vaadin and Tomcat7 Problems log in I am having a problem with logging in in my application using Vaadin and Tomcat 7.
The problem is like this:
If it is the first time I run the application on my server, I log in, I do what I have to do and close the browser.
Now if a friend logs in on the application from his computer, he is automatically logged in with my account.
How can I resolve this issue, is it a tomcat issue where it keeps the session open or something, or I have to make some configurations in vaadin?
EDIT:
Let me explain it a bit better.
In my main clas where vaadin is initiatied with first window (extends Application) i have a static final USER.
If i make the user=null in init(). Every time a person acceses the application, it will ask him for his username and password, so it works.
But even if he refreshes the website it will ask him to put the password and username again.
How can I make it to remember that specific person using cookies and http responses?
I am very new to this so any help is apreciated

A: I think you need to remove the static final from your USER object. Anything static final can only be created once ever for the entire application. You need it to be an instance variable.
e.g.
private User USER = null;

and not
private static final User USER = null;

A: Vaadin tracks user sessions with cookies and I have hard time believing that it could confuse sessions.
I'm a bit worried that you mention "in my main class I have a static final". Static members should not be used carelessly, as they will be shared between all users (and there will be thread safety problems). If you're using a static variable to store who's logged in, it's possible that then all users are logged in as one...
As you mentioned the Application class, you are apparently using Vaadin 6. See https://vaadin.com/book/vaadin6/-/page/advanced.httpservletrequestlistener.html for info about using cookies to automatically log in a user. That's probably not your problem in this case though.

A: Look at this:
https://vaadin.com/de/book/vaadin7/-/page/application.lifecycle.html
Basically you must distinguish these two things:

*

*User hits F5/Refresh
The default is, that it is presented with a new application session
You can disable this behaviour as described in "Preserving UI on Refresh"
You just annotate your main UI class with @PreserveOnRefresh
The "sideeffect" of this is the following:

*

*You are in your application

*Now you just close the browser (or tab)

*You open again the browser/tab

*Unless your http session has expired in meantime, Vaadin shows you the last screen, just is if you have not been away at all.

*You http session expired or you had destroyed the http and/or vaadin session
Vaadin then shows you just the start screen of your application.
If you wish to have the login form prefilled with some values, you have to store them in a http cookie and fill in the values from there
André


text:
Q: Is it possible in Firebird to create a single index with ascending and descending columns? For instance, something equivalent to
CREATE INDEX Listing_Date_Idx ON ACTIVITY(Listing,Date_ DESC,Time_ DESC);

A: The syntax for index creation does not allow for this:
CREATE [UNIQUE] [ASC[ENDING] | [DESC[ENDING]] INDEX indexname
   ON tablename
   { (<col> [, <col> ...]) | COMPUTED BY (expression) }

<col>  ::=  a column not of type ARRAY, BLOB or COMPUTED BY

As you must set a single order for the entire index, not for each individual column.
However,

It is quite valid to define both an ascending and a descending index
  on the same column or key set.


text:
Q: Why doesn't the bit-shift of a variable and a number have the same result? I'm shifting some bits and just realized that doing the operation using a variable doesn't have the same result as using a number. See the example below.
int a = 97;
int b = 0;

b = 1 << a;
printf("%d\n", b);
// 2

b = 1 << 97;
printf("%d\n", b);
// 0 - warning: shift count >= width of type [-Wshift-count-overflow]

A: The warning you are seeing is a compile time warning. Now, you can clearly see that your int b is a 32-bit variable which will be overflown if left-shifted 97 times. So, it's a valid concern. But the compiler can only detect this overflow for the constant number of shifts as it is evaluated during compilation and the compiler immediately knows that it'll overflow.
In case of variable number of shifts, the compiler isn't smart enough to know what value int a will posses when it'll come down to shifting. So, the compiler leaves it upto you.

A: Since the result of a left shift with a right operand larger than the length in bits of the left operand is undefined, any result is possible from the expression.
In the variable case (1 << a), since a is 97 (larger than the number of bits in an int), the most likely results are 1 << (97 % 32) == 1 << 1 == 2 or 0, typically depending on how the hardware (CPU) handles these shifts.
With a constant (1 << 97), the compiler knows you're shifting too far, issues the warning (which is not required), and defines the result as 0 (also not required).

A: The undefined behavior is outlined in the C++ standard here.
http://eel.is/c++draft/expr.shift

The behavior is undefined if the right operand is negative, or greater
  than or equal to the width of the promoted left operand.

You'll get different results depending on compiler and optimization level. If you turn on optimization, the compiler will easily optimize out the first shifting operation and then make it 0 as well.
Why exactly does it act like that though? The x86 instruction for shifting by a variable is SAL (shift-arithmetic-left). You can see the instruction list for bit shifting operations here:
https://c9x.me/x86/html/file_module_x86_id_285.html
The one that would be used in an unoptimized build would be SAL r/m32, CL. The CL register is 8 bits, but the processor masks it to 5 bits internally:

The destination operand can be a register or a memory location. The count operand can be an immediate value or register CL. The count is masked to 5 bits, which limits the count range to 0 to 31. A special opcode encoding is provided for a count of 1.


text:
Q: Make Moq output invocation of all methods to console How can I configure Moq in a way to output every method invocation (invoked method name and parameters) to console without writing this yourself for each method? I am trying to have these method invocations in order of execution output to a log file without doing this manually for every method. Alternatively, it would be fine to have this behavior for all methods centralized in the test setup method in such a way that a subsequent call to "Setup" (from a test method) of a mocked class would not overwrite the already set up logging logic.
Checking the Invocations property at the end of the test is not an option, since there might be several other mocked classes and I would not know the exact order of execution.
How can I achieve this behavior in Moq?
Here is an example:
[SetUp]
public void SetupTest()
{
    _encryptionServiceMock = new Mock<IEncryptionService>();
    _secretRepositoryMock = new Mock<ISecretRepository>();

    // arrange mocks to output all method invocations to console
}

[Test]
public void SomeTestCase()
{
    // arrange
    _secretRepositoryMock.Setup(sr => sr.GetById(1)).Returns("abcdefg");
    _secretRepositoryMock.Setup(sr => sr.GetById(2)).Returns("hijklmn");
    _encryptionServiceMock.Setup(sr => sr.Decrypt("abcdefg", "encryption key")).Returns("first decrypted secret");
    _encryptionServiceMock.Setup(sr => sr.Decrypt("hijklmn", "encryption key")).Returns("second decrypted secret");

    // arrange (this gets called at some point in the test)
    var encryptedSecretOne = _secretRepositoryMock.Object.GetById(1);
    var decryptedSecretOne = _encryptionServiceMock.Object.Decrypt(encryptedSecretOne, "encryption key");

    var encryptedSecretTwo = _secretRepositoryMock.Object.GetById(2);
    var decryptedSecretTwo = _encryptionServiceMock.Object.Decrypt(encryptedSecretTwo, "encryption key");

    // act

    // assert

    // Expected output:
    //
    // secretRepositoryMock     GetById(1) returned "abcdefg"
    // encryptionServiceMock    Decrypt("abcdefg", "encryption key") returned "first decrypted secret"
    // secretRepositoryMock     GetById(2) returned "hijklmn"
    // encryptionServiceMock    Decrypt("hijklmn", "encryption key") returned "second decrypted secret"
}

A: I ended up writing my own extensions of Moq (extension method "SetupWithLogging").
Usage:
[Test]
public void Test1()
{
    var mock = new Mock<ISomeService>();
    mock.SetupWithLogging(x => x.DoSomething(It.IsAny<string>()))
        .Returns<string>(false);
    mock.Object.DoSomething("ha");
}

public interface ISomeService
{
    bool DoSomething(string a);
}

Custom extensions:
public static class MockExtensions
{
    public static ICustomSetup<TResult> SetupWithLogging<T, TResult>(this Mock<T> mock, Expression<Func<T, TResult>> expression) where T : class
    {
        string methodName = ((MethodCallExpression)expression.Body).Method.Name;

        return new CustomSetupParameters<T, TResult>(methodName, mock.Setup(expression));
    }
}

public interface ICustomSetup<in TResult>
{
    void Returns<TInput>(TResult result);
}

internal class CustomSetupParameters<T, TResult> : ICustomSetup<TResult> where T : class
{
    private readonly string _methodName;
    private readonly ISetup<T, TResult> _mock;

    internal CustomSetupParameters(string methodName, ISetup<T, TResult> mock)
    {
        _methodName = methodName;
        _mock = mock;
    }

    public void Returns<TInput1>(TResult result)
    {
        _mock.Returns<TInput1>((a) =>
        {
            Console.WriteLine($"{_methodName}({a}): {result}");

            return result;
        });
    }
}


text:
Q: Findpeaks function misses peaks for an unknown reason I've got some data that I'm trying to locate the peaks in. It's got 23 peaks, which are visible in the data. However, the findpeaks function only seems to be able to identify 21 of them, but I can't work out why.
I'd be very grateful for some help debugging and picking up the last two peaks.
data <- data.frame(time = c(1669, 1670, 1671, 1672, 1673, 1674, 1675, 1676, 1677, 1923,
                            1924, 1925, 1926, 1927, 1928, 1929, 2176, 2177, 2178, 2179, 2180,
                            2181, 2182, 2428, 2429, 2430, 2431, 2432, 2433, 2434, 2435, 2687,
                            2688, 2689, 2690, 2691, 2692, 2693, 2694, 3202, 3203, 3204, 3205,
                            3206, 3207, 3208, 3209, 3730, 3731, 3732, 3733, 3734, 3735, 3736,
                            3737, 3738, 4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, 4266,
                            4267, 4268, 4269, 4789, 4790, 4791, 4792, 4793, 4794, 4795, 4796,
                            4797, 4798, 4799, 4800, 5325, 5326, 5327, 5328, 5329, 5330, 5331,
                            5332, 5333, 5334, 5335, 5336, 5337, 5849, 5850, 5851, 5852, 5853,
                            5854, 5855, 5856, 5857, 5858, 5859, 5860, 5861, 6096, 6097, 6098,
                            6099, 6100, 6101, 6102, 6103, 6104, 6105, 6106, 6107, 6108, 6109,
                            6110, 6354, 6355, 6356, 6357, 6358, 6359, 6360, 6361, 6362, 6363,
                            6364, 6365, 6366, 6367, 6857, 6858, 6859, 6860, 6861, 6862, 6863,
                            6864, 6865, 6866, 6867, 6868, 6869, 6870, 6871, 6872, 7346, 7347,
                            7348, 7349, 7350, 7351, 7352, 7353, 7354, 7355, 7356, 7357, 7358,
                            7359, 7360, 7361, 7362, 7816, 7817, 7818, 7819, 7820, 7821, 7822,
                            7823, 7824, 7825, 7826, 7827, 7828, 7829, 7830, 7831, 7832, 7833,
                            7834, 7835, 7836, 8264, 8265, 8266, 8267, 8268, 8269, 8270, 8271,
                            8272, 8273, 8274, 8275, 8276, 8277, 8278, 8279, 8280, 8281, 8282,
                            8283, 8284, 8695, 8696, 8697, 8698, 8699, 8700, 8701, 8702, 8703,
                            8704, 8705, 8706, 8707, 8708, 8709, 8710, 8711, 8712, 8713, 8714,
                            8715, 8716, 9091, 9092, 9093, 9094, 9095, 9096, 9097, 9098, 9099,
                            9100, 9101, 9102, 9103, 9104, 9105, 9106, 9107, 9108, 9109, 9110,
                            9111, 9460, 9461, 9462, 9463, 9464, 9465, 9466, 9467, 9468, 9469,
                            9470, 9471, 9472, 9473, 9474, 9475, 9476, 9477, 9478, 9479, 9799,
                            9800, 9801, 9802, 9803, 9804, 9805, 9806, 9807, 9808, 9809, 9810,
                            9811, 9812, 9813, 9814, 9815, 9816, 9817, 9818, 9819, 10102,
                            10103, 10104, 10105, 10106, 10107, 10108, 10109, 10110, 10111,
                            10112, 10113, 10114, 10115, 10116, 10117, 10118, 10119, 10120,
                            10121, 10122, 10123, 10124, 10377, 10378, 10379, 10380, 10381,
                            10382, 10383, 10384, 10385, 10386, 10387, 10388, 10389, 10390,
                            10391, 10392, 10393, 10394, 10395, 10396, 10397, 10398, 10399,
                            10400),
                   peak=c(698, 1022, 1369, 1514, 1510, 1298, 993, 726, 526, 820, 1177,
                          1418, 1495, 1327, 1000, 705, 860, 1222, 1499, 1531, 1349, 1031,
                          707, 538, 874, 1176, 1379, 1380, 1204, 893, 621, 550, 841, 1172,
                          1402, 1472, 1324, 1025, 732, 750, 1043, 1277, 1380, 1313, 1117,
                          859, 624, 707, 966, 1192, 1325, 1314, 1201, 1002, 756, 542, 500,
                          626, 734, 875, 982, 1058, 1045, 981, 860, 739, 621, 500, 500,
                          622, 767, 908, 1011, 1082, 1110, 1061, 975, 836, 701, 564, 538,
                          677, 823, 969, 1061, 1117, 1129, 1091, 1038, 902, 779, 645, 525,
                          583, 699, 837, 929, 1020, 1050, 1062, 1059, 996, 904, 802, 681,
                          576, 530, 636, 749, 864, 954, 1032, 1084, 1108, 1080, 1018, 944,
                          850, 747, 637, 526, 566, 665, 755, 852, 908, 983, 1009, 1006,
                          976, 918, 848, 757, 669, 577, 532, 618, 709, 787, 873, 934, 992,
                          1004, 996, 972, 919, 848, 753, 679, 592, 514, 566, 636, 722,
                          786, 860, 905, 935, 962, 949, 943, 906, 859, 795, 729, 650, 563,
                          501, 502, 552, 640, 702, 763, 841, 895, 945, 992, 1022, 1043,
                          1050, 1045, 1024, 961, 902, 838, 775, 706, 622, 555, 502, 582,
                          652, 724, 798, 871, 938, 974, 1035, 1053, 1066, 1079, 1055, 1015,
                          985, 927, 863, 764, 718, 637, 545, 542, 618, 689, 761, 818, 892,
                          934, 988, 1005, 1037, 1030, 1022, 1001, 969, 930, 875, 813, 752,
                          680, 628, 557, 501, 511, 578, 625, 688, 743, 786, 825, 854, 887,
                          903, 916, 894, 884, 871, 825, 791, 747, 696, 632, 582, 525, 525,
                          576, 637, 672, 718, 746, 789, 830, 822, 828, 835, 831, 802, 781,
                          743, 697, 661, 625, 551, 515, 548, 597, 643, 694, 754, 792, 830,
                          866, 874, 889, 890, 896, 862, 849, 818, 771, 739, 684, 625, 570,
                          517, 524, 573, 632, 698, 736, 797, 848, 877, 898, 941, 948, 943,
                          944, 916, 893, 881, 823, 792, 749, 696, 648, 588, 541, 504, 559,
                          626, 671, 712, 764, 818, 844, 864, 906, 915, 920, 929, 912, 889,
                          857, 838, 796, 767, 712, 656, 627, 569, 534),
                   colour="red")

library(pracma)
peaks <- data.frame(findpeaks(data$peak, npeaks=23, threshold=100, peakpat = "[+]{1,}[0]*[-]{1,}", sortstr=TRUE))
data$n <- seq(1,length(data$peak))
data <- merge(x=data, y=peaks, by.x="n", by.y="X2", all.x=TRUE, all.y=TRUE)

ggplot(data, aes(x=time, y=peak, fill=colour, colour=colour)) +
  geom_col(orientation="x") +
  geom_point(aes(x=time, y=X1))

A: The function findpeaks  , as you notice, accepts a threshold value which will affect the number of locations deemed to be peaks, and a peakpat pattern overriding nups and ndowns .
The criteria for visually finding a peak may well differ from whichever algorithm you choose to run -- there are others besides findpeaks -- to extract local maxima.
new update
I contacted the maintainer (Hans Borcher) ; here's his response and explanation.

In the given example, the use of threshold=100 causes this
phenomenon of "lost peaks". The 'threshold' is the difference between
the peak and both valleys surrounding it. In the case of the two peaks
very near to each other the valley between them is too high up and the
peaks will not get counted. I see the problem for the user. The
documentation shall make it clearer what 'threshold' really means and
what the implications are when used.

Alternatively, consider: your data are noisy.  It's often helpful to first run a smoothing algorithm such as loess or lowess (there are hundreds of smoothers and spline-fitters out there) to get rid of spikiness before trying to find local maxima.

A: There is a bug in findpeaks with the threshold parameter. If you set this to 0 you will find all 25 peaks.
findpeaks(data$peak, peakpat = "[+]{1,}[0]*[-]{1,}",
          threshold = 0, npeaks = 0)

And setting minpeakdistance = 5 will return the 23 peaks you were looking for (at least I hope so).
I assume a corrected findpeaks function will be provided with the next version of the package.
PS:
I don't think this is a Q&D tool. I know it has served well for a lot of users. Of course, there may be better and more reliable peak finding functions in other packages.


text:
Q: Noise with heavy tails The main type of noise I know other than white noise is a colored noise (Ornstein-Uhlenbeck) of the form:
$$d\eta = \lambda \eta dt + \alpha dW_t$$
with exponential correlation. I'm interested in noise in which the distribution is heavy tailed so that events far from the mean are more common, and have much longer tails in the correlation function so that correlations last much longer than the Ornstein-Uhlenbeck process (I'm unsure if this correlation and heavy tailed noise coincide or not). I believe this is also called "pink noise". Is there a known stochastic differential equation of the form:
$$dP(t) = f(P(t))dt + g(P(t))dW_t$$
describing such a process? (I'm using $P$ for pink noise).


text:
Q: Choose service type based on Enum value I would like to create kind of Factory Pattern, but am struggling.
//OperationType is an Enum
public interface SettlementService<OperationType>{
    void settleOperation(Order order);
}

then I have 2 services that handle different operation types in different ways.
public class ClientSettlementService implements SettlementService<OperationType.CLIENT> {
    @Override
    public void settleOperation(Order order) {

    }
}

public class CustomerSettlementService implements SettlementService<OperationType.CUSTOMER> {
    @Override
    public void settleOperation(Order order) {

    }
}

Then in my settlement method I have:

switch (order.getOperationType()) {
case OperationType.CLIENT:
    //here ClientSettlementService is called
    settlementService.settleOperation(order);
    break;
case OperationType.CUSTOMER:
    //here CustomerSettlementService is called
    settlementService.settleOperation(order);
    break;
default:
    LOG.error("Unsupported operation type.");
}

The code obviously doesn't work, but hope you get the idea. How do I do that?

A: To implement the SettlementService using the factory pattern you don't need a generic type awareness in the interface.
public interface SettlementService {
    void settleOperation(Order order);
}

Further, it's implementing classes would look like following -
public class ClientSettlementService implements SettlementService {
    @Override
    public void settleOperation(Order order) {
        System.out.println("clients!!");
    }
}

public class CustomerSettlementService implements SettlementService {
    @Override
    public void settleOperation(Order order) {
        System.out.println("customers!!");
    }
}

The factory that you want to build would then look like the following based on the OperationType enum.
public class SettlementFactory {
    private SettlementService provideService(OperationType operationType) {
        switch (operationType) {
            case CLIENT:
                return new ClientSettlementService();
            case CUSTOMER:
                return new CustomerSettlementService();
            default:
                throw new UnsupportedOperationException("Unsupported operation type!");
        }
    }
}

You can then make use of this factory to settle a given Order as:
private void settleOrder(Order order) {
    SettlementFactory settlementFactory = new SettlementFactory();
    SettlementService settlementService = settlementFactory.provideService(order.getOperationType());
    settlementService.settleOperation(order);
}

If you find the Factory class as overhead by any chance and want to cut the service providing capability short to the same method where you make use of it, you can use a Map and handle the service provided such as:
private void settleOrder(Order order) {
    Map<OperationType, SettlementService> typeSettlementServiceMap =
            Map.of(OperationType.CLIENT, new ClientSettlementService(),
                    OperationType.CUSTOMER, new CustomerSettlementService());
    SettlementService settlementService = typeSettlementServiceMap.get(order.getOperationType());
    if (settlementService == null) throw new UnsupportedOperationException("..message..");
    settlementService.settleOperation(order);
}


text:
Q: How to vertically align undersets? How to vertically align the numbers beneath (with \underset or otherwise)?

\documentclass{beamer}
\usepackage{amsmath}
\begin{document}

\begin{equation}
\underset{1}{x}=\underset{1}{p_{A|B}}
\end{equation}

\end{document}

Update: This should go into a tabular, which stackunder doesn't seem to be doing well:

A: This is an opportune time to use \vphantom:

\documentclass{beamer}
\usepackage{amsmath}
\begin{document}

\begin{equation}
  \underset{1}{x} = \underset{1}{p_{A|B}}
\end{equation}

\begin{equation}
  \underset{1}{\vphantom{p_{A|B}}x} = \underset{1}{p_{A|B}}
\end{equation}

\end{document}

A: Use a longstack (stacktype L).  EDITED to use \normalbaselineskip instead of \baselineskip, so that it can appear in tabular, if needed.
\documentclass{beamer}
\usepackage{stackengine}
\def\stacktype{L}
\setstackgap{L}{.7\normalbaselineskip}
\stackMath
\begin{document}
\begin{equation}
\stackunder{x}{\scriptstyle1}=\stackunder{p_{A|B}}{\scriptstyle1}
\end{equation}
\begin{tabular}{cc}
\stackunder{x}{\scriptstyle1}=\stackunder{p_{A|B}}{\scriptstyle1}
&
\stackunder{x}{\scriptstyle1}=\stackunder{p_{A|B}}{\scriptstyle1}
\end{tabular}
\end{document}


text:
Q: Is there any way to pro-grammatically create product categories and assign thumbnails in PHP and WooCommerce? I want to create categories and assign a thumbnail to them.
wp_insert_term can't be used for what I am asking, and I wonder if there is any other way known to man.
I have seen the other question on the community but it doesn't seem to work when you actually use it. I don't know why it is marked as correct.

A: wp_insert_term() works fine for this sort of thing.
You haven't given any context, but here's a quick example I made that, on every page load, adds a random WooCommerce product category(not duplicates though), and an associated random image, from a list of image id's in MY media library(change $existing_image_ids to your own ids for this to work).
// page load creates a random product category, and an associated image
add_action( 'init', 'rand_product_cat_w_rand_image' );
function rand_product_cat_w_rand_image() {

    $test_product_cats = [
        'Test Category 1',
        'Test Category 2',
        'Test Category 3',
        'Test Category 4',
        'Test Category 5'
    ];

    $existing_image_ids = [
        '144',
        '143',
        '142',
        '141',
        '140'
    ];

    $rand_cat = rand( 0, 4 );
    $rand_img = rand( 0, 4 );

    $new_cat_title = $test_product_cats[$rand_cat]; // title of product category
    $new_img_id = $existing_image_ids[$rand_img]; // id of image you want to use from your media library

    $new_cat_added = wp_insert_term( $new_cat_title, 'product_cat' ); // 'product_cat' is woocommerce product category taxonomy, and were adding a new category with title

    if(is_wp_error( $new_cat_added )) {
        return; // there was an error adding new product category, usually because it already exists with only 5 available test categories
    }
    else {
        add_term_meta( $new_cat_added['term_id'], 'thumbnail_id', $new_img_id, true ); // add image to new product category, etc.
    }
}

// This bit is just copied from WooCommerce docs for showing product category image:
// REF: https://docs.woocommerce.com/document/woocommerce-display-category-image-on-category-archive/
add_action( 'woocommerce_archive_description', 'woocommerce_category_image', 2 );
function woocommerce_category_image() {
    if ( is_product_category() ){
        global $wp_query;
        $cat = $wp_query->get_queried_object();
        $thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
        $image = wp_get_attachment_url( $thumbnail_id );
        if ( $image ) {
            echo '<img src="' . $image . '" alt="' . $cat->name . '" />';
        }
    }
}

Tested and works.


text:
Q: GNOME Panel seen in Unity 2D? Why does GNOME panel open up when I launch UNITY 2D instead of Unity panel?
This I am starting to see from last 2 days, any idea how to fix this?

A: Well finally solved, I needed to do the following

*

*gnome-panel --replace

*unity-2d-launcher &

*Save the session and logout

A: What's likely happening is that gnome-panel is set to run on login, and as such it'll automatically start every time you log into GNOME. So, what you can do is to open up Startup Application Preferences (AKA gnome-session-properties), and check for something that has a you don't know what it is, then you want "Edit" that item, and see what comes up.

Keep going through the list until you find the gnome-panel command tucked away somewhere.


text:
Q: Sorting out an array List using Collections I want to use the Comparator object of the Collections framework to sort out an ArrayList by an specific attribute.
I have an ArrayList called measureEviArray this array contains objects type MeasureEvi.
The class MeasureEvi has an attribute called mCoordenate which corresponds to a PointF data type.
public class MeasureEvi {

private int mIndex;                             //
private int mOrderIndex;
private int eIndex;                             //
private TextView mTag;                          //
private PointF mCoordenate;
}

What I want is to sort out that array depending on the coordenates given to each object in X (mCoordenate.x)
Is it possible to use Collections for this and get an Array Ordenate from the minor to the greatest in X axis?
I was trying to implement this way:
 Collections.sort(measureEviArray, new Comparator<MeasureEvi>() {
        @Override
        public int compare(MeasureEvi measureEvi, MeasureEvi t1) {
            return measureEvi.getmCoordenate().x.compareTo(t1.getmCoordenate().x);
        }
    });

but compareTo is not an Option, cannot resolve method.

A: Since x from PointF is a float, use Float.compare(float f1, float f2):
return Float.compare(measureEvi.getmCoordenate().x, t1.getmCoordenate().x);


text:
Q: AngularJS ng-if I'm currently working on a notifications page where the user can recieve a notification out from 4 actions done to his posts:
follow, like, ect.
Each object has a 'concirning' variable which gives the action of what happened.
Though for every action I would like another sentence (obviously)
Currently I have the following but it is a bit messy in my eyes:

                    {{notification.user.name}} has commented on one of your captures.
                    {{notification.user.name}} has given a birdname for your capture! Go check it out!
                    {{notification.user.name}} has just liked your capture!
                    {{notification.user.name}} has started following you.

The notification consists of 2 objects:
notification.user that preformed the action to trigger the notification
and the notification itself as notification.notification
Is there a way for me to clean this out? Thanks

A: Try the following :
In your JS :
$scope.message="";
$scope.$watch('notification.notification.concirning', function (value) {
    if (value== "comment") {
        $scope.message="whatever message you want";
    }
    //Put conditions for each type of concirning
});

In you html :

     {{message}}

If your message has html elements/tage read more about ng-bind-html

A: You can make it cleaner with ngSwitch:

      {{notification.user.name}} has commented on one of your captures.
      {{notification.user.name}} has given a birdname for your capture! Go check it out!
      {{notification.user.name}} has just liked your capture!
      {{notification.user.name}} has started following you.

A: The really best and generic way for this is a directive.
Here is a little directive which take 3 params :

*

*object : value to be used if you use angular templating in the value of the map

*map : a simple key/value object, object can be HTML, if so you can use angular templating in to display data of the object {{object.[...]}}

*key : they key that determine which message display

It's possible there is some cleaner way of doing this like :

*

*Instead of assing raw map, pass a function so you can handle more complex case if needed

*use attr instead of isolated scope and set the scope to true to inherits from other scope, so you can use everything stored upside. Otherwise you'll need a wrapper object that you will need to refresh if the value within change.

*Use something less generic, define the mapping key/template in the directive, this follow better the angularJS's guidelines. So you would have to define one directive per mapping.

angular.module("app", []).controller("ctrl", ['$scope', '$sce', function($scope, $sce){
    $scope.map = {
        'comment':$sce.trustAsHtml('{{object.user.name}} has commented on one of your captures.'),
         'birdsuggestion':$sce.trustAsHtml('{{object.user.name}} has given a birdname for your capture! Go check it out!'),
          'like':$sce.trustAsHtml('{{object.user.name}} has just liked your capture!'),
          'follow':$sce.trustAsHtml('{{object.user.name}} has started following you.')
    };
    $scope.notifications = [{
        user:{name:'foo'},
        notification:{concirning:'comment'}
    }, {
      user:{name:'bar'},
      notification:{concirning:'like'}
    }]
}]).directive('mapMessageToView', function($compile){
   return{
     restrict:'A',
     scope:{
         map:"=",
         key:"=",
        object:"="
     },
     replace:false,
     link:function(scope, element, attr){
         element.html(scope.map[scope.key]);
         $compile(element.contents())(scope);
         scope.$watch('key', function(newValue){
             element.html(scope.map[scope.key]);
             $compile(element.contents())(scope);
         });
     }
   };
});