text:
Q: How to move a object(GdImage) to a specific folder? I'm working on a image converter that convert jpg and png to webp and webp to jpg and png and i've been trying to make that the converted files go to a specific folder instead of my working folder but it doesn't go on my convert forlder
here's my code
<?php
require "db.php";
$pdo = new \PDO(DSN, USER, PASS);

if (!empty($_FILES['files']['name'][0])) {

    $files = $_FILES['files'];
    $fileName = $_POST['name'];
    $fileTag = $_POST['tag'];
    $fileDescription = $_POST['description'];
    $convert = $_POST['convert'];

    $uploaded = array();
    $failed = array();

    $allowed = array('jpg', 'jpeg', 'png', 'webp');

    foreach ($files['name'] as $position => $file_name) {

        $file_tmp = $files['tmp_name'][$position];
        $file_size = $files['size'][$position];
        $file_error = $files['error'][$position];

        $file_ext = explode('.', $file_name);
        $file_ext = strtolower(end($file_ext));

        if (in_array($file_ext, $allowed)) {

            if ($file_error === 0) {

                if ($file_size <= 2097152) /* 2mb */ {

                    $file_name_new = uniqid('IMG-', true) . '.' . $file_ext;
                    $file_destination = 'uploads/' . $file_name_new;

                    if (move_uploaded_file($file_tmp, $file_destination)) {

                        $uploaded[$position] = $file_destination;

                        $query = "INSERT INTO images(name, tag, description, images) VALUES (:name, :tag, :description,:images)";
                        $statement = $pdo->prepare($query);

                        $statement->bindValue(':name', $fileName, \PDO::PARAM_STR);
                        $statement->bindValue(':tag', $fileTag, \PDO::PARAM_STR);
                        $statement->bindValue(':description', $fileDescription, \PDO::PARAM_STR);
                        $statement->bindValue(':images', $file_name_new, \PDO::PARAM_STR);
                        $statement->execute();

                        $upload = $statement->fetchAll();
                    } else {
                        $failed[$position] = "[{$file_name}] failed to upload.";
                    }
                } else {
                    $failed[$position] = "[{$file_name}] is too large.";
                }
            } else {
                $failed[$position] = "[{$file_name}] failed to upload {$file_error}.";
            }
        } else {
            $failed[$position] = "[{$file_name}] file extension '{$file_ext}' is not allowed.";
        }
    }

    if (!empty($uploaded)) {
        print_r($uploaded);
    }

    if (!empty($failed)) {
        print_r($failed);
    }
} else {
    echo 'no files';
}

if (exif_imagetype($file_destination) == IMAGETYPE_PNG && $convert ==='webp') {

    $image = imagecreatefrompng($file_destination);
    imagewebp($image, str_replace('png', 'webp', $file_name_new));
    move_uploaded_file($file_destination, 'convert/');

} elseif (exif_imagetype($file_destination) == IMAGETYPE_JPEG && $convert ==='webp') {

    $image = imagecreatefromjpeg($file_destination);
    imagewebp($image, str_replace('jpg', 'webp', $file_name_new));
    move_uploaded_file($file_tmp, 'convert/');

} elseif (exif_imagetype($file_destination) == IMAGETYPE_WEBP && $convert ==='png') {

    $image = imagecreatefromwebp($file_destination);
    imagepng($image, str_replace('webp', 'png', $file_name_new));
    move_uploaded_file($file_tmp, 'convert/');

}elseif (exif_imagetype($file_destination) == IMAGETYPE_WEBP && $convert ==='jpg') {

    $image = imagecreatefromwebp($file_destination);
    imagepng($image, str_replace('webp', 'jpg', $file_name_new));
    move_uploaded_file($file_tmp, 'convert/');

}else {
    echo "can't convert it";
}var_dump($image);

I tried changing the variable in the move_uploaded_file but still won't let me


text:
Q: Matplotlib histogram is adding a small bar at the second histogram bin I think may hist function have some problems, at certain cases when I plot an histogram with matplotlib:
pylab.figure()
H, bins, _  = pylab.hist([2,2])
print H
print bins

The result is:

[ 0.  0.  0.  0.  0.  2.  0.  0.  0.  0.]
[ 1.5  1.6  1.7  1.8  1.9  2.   2.1  2.2  2.3  2.4  2.5]

Do you see at the plot that "bump" at between 1.5 and 1.6, where it is coming from? How can I avoid it?

A: This is interesting.
You can look at the rectangles generated:
ax = plt.subplot(111)
h, bins, rects = ax.hist([2, 2])

for r in rects:
    print(r.get_bbox())

# Bbox(x0=1.5, y0=0.0, x1=1.6, y1=0.0)
# Bbox(x0=1.6, y0=0.0, x1=1.7, y1=0.0)
# Bbox(x0=1.7, y0=0.0, x1=1.8, y1=0.0)
# Bbox(x0=1.8000000000000003, y0=0.0, x1=1.9000000000000001, y1=0.0)
# Bbox(x0=1.9, y0=0.0, x1=2.0, y1=0.0)
# Bbox(x0=1.9999999999999998, y0=0.0, x1=2.0999999999999996, y1=2.0)
# Bbox(x0=2.1000000000000005, y0=0.0, x1=2.2000000000000006, y1=0.0)
# Bbox(x0=2.2, y0=0.0, x1=2.3, y1=0.0)
# Bbox(x0=2.3, y0=0.0, x1=2.4, y1=0.0)
# Bbox(x0=2.4000000000000004, y0=0.0, x1=2.5000000000000004, y1=0.0)

Obviously, the histogram function generates a rectangle for each bin, even the empty ones. Although they have a height of 0, they are passed to the renderer and in some cases a spurious something is drawn.
I don't know how to prevent this. However, there is a solution, but it is rather hackish. The hist function puts a rectangular patch into the axis for each bin. It is possible to manually iterate over these patches and remove those with zero height:
ax = plt.subplot(111)
h, bins, rects = ax.hist([2, 2])

ax.patches = [p for p in ax.patches if p.get_height() > 0]

A: This seems to be a rendering issue. Saving the figure to pdf does not show the glimpse. So, depending on your final use of the figure this might turn out to not be a problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to create and save windows form from another form at runtime in .net I want to create and save a windows form with some controls from another windows form.
I tried below code but it's only create a new form with a textbox at runtime but i am not able to save this form in same solution path.
using (Form form = new Form())
            {
                form.Text = "About Us";
                TextBox tb = new TextBox();
                form.Controls.Add(tb);
                form.ShowDialog();
            }


text:
Q: Matrix production in cpp I wanted to read and use(product) 'dat' files in cpp
There is matrix in each files. I already did reading files.
but, I couldn't product them. what should I do?, profs

A: I would recommand to use a 3rd party library to calculate the linear algebra related topics, like http://arma.sourceforge.net/. You basically load your data to an armadillo matrix and you can do a lot with it ;)


text:
Q: Is frequency a scalar quantity? Well, our professor in class posed a question to all of us:
Is frequency a scalar quantity?
The obvious answer, of course, is yes, it is, because it does not have a direction associated with it. But then, a scalar is defined as a coordinate invariant quantity. In the case of frequency this obviously fails (the Doppler shift).
So how do we classify it?

A: The frequency of a traveling wave is a scalar with respect to Euclidean transformations of space; it is preserved by rotations, translations, and even reflections. It is not a scalar with respect to Galilean, Lorentz or Poincaré transformations of spacetime; boosts of the coordinate system cause a Doppler shift.


text:
Q: Chart data displays on the console.log but not on the page (Using Axios/Vue) I'm trying to use axios to get data for my Chart but I couldn't know how to make it appear on the canvas, i can see the values on the console.log as below
Console.log,
I'm not too sure what is happening, here's my code :
   mounted(){
  const ctx = document.getElementById('myChart');
  let myData = [];
 const myChart = new Chart(ctx,
   {
   type: 'line',
   data: {
   labels: [....],
    datasets: [{
        data: this.myData,
        backgroundColor: [  ['blue']],
                 }] },
      options: {.....}
           });
           myChart;

here's the methode:
created: function(){
 this.getData();} ,
methods: {
getData : function(){
axios.get('http://localhost:3000/Chart/chartjs')
  .then(resp => {this.myData = resp.data
  console.log(resp.data); }) }

A: your problem is related to the reactivity fundamentals of VueJS. As you are declaring a local variable in the mounted method and trying to access the property myData on this without declaring it in the component, VueJS will not update the UI.
The way you presented your code, I'll assume that you are using VueJS3 with the Options API.
To have a reactive component, you need to declare a reactive state.  This is usually done before the mounted() method.
export default {
    data() {
        return {
            myData: []
        }
    },
    mounted() {
    ...

Afterward, in your mounted and getData methods, instead of declaring myData, you need to use this.myData.  VueJS will take care of the reactivity.
Also, I noticed that you are trying to access the DOM directly. This is not a usual or recommended in VueJS.  You should use a bind to make sure your properties are updated correctly.


text:
Q: JavaFX-8 Make text caret visible in readonly textarea JavaFX textfields do not show a text caret if you set them to readonly mode. Here is an example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;

public class TextAreaReadOnly extends Application {

    public TextAreaReadOnly() {
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        TextArea textarea = new TextArea();
        textarea.setText("This is all\nreadonly text\nin here.");
        textarea.setEditable(false);
        Scene scene = new Scene(textarea, 600, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

While it is still possible to select text with Shift+Cursor keys, no caret is displayed. Does anyone know a workaround for this?

A: I want the same thing -- a read-only field, but caret visible for navigation.  I tried:
.text-input:readonly { -fx-display-caret: true; }

But to no avail.  Digging in to the FX source code (for 2.2), I found this:
caretVisible = new BooleanBinding() {
        { bind(textInput.focusedProperty(), textInput.anchorProperty(), textInput.caretPositionProperty(),
                textInput.disabledProperty(), textInput.editableProperty(), displayCaret, blink);}
        @Override protected boolean computeValue() {
            // RT-10682: On Windows, we show the caret during selection, but on others we hide it
            return !blink.get() && displayCaret.get() && textInput.isFocused() &&
                    (isWindows() || (textInput.getCaretPosition() == textInput.getAnchor())) &&
                    !textInput.isDisabled() &&
                    textInput.isEditable();
        }
    };

It looks like there is no way to override the requirement isEditable() at the end of that conditional.  I may paint on a dummy caret as a work-around, which is ugly but I'm not sure there is another way -- looks like you can either fake the caret or fake the read-only aspect (rejecting all edits to the control).

A: Triggered by Neil's answer, I tried a quick test of my suggestion to extend TextAreaSkin and replace the caretVisible property by one that doesn't check for editability. Seems to work (not thoroughly tested, though) - but requires reflective access of super's private blink property. Obviously dirty and not possible in security restricted contexts ...
public static class MyTextAreaSkin extends TextAreaSkin {

    public MyTextAreaSkin(TextArea textInput) {
        super(textInput);
        caretVisible = new BooleanBinding() {
            { bind(textInput.focusedProperty(), textInput.anchorProperty(),
                    textInput.caretPositionProperty(),
                    textInput.disabledProperty(), displayCaret , blinkProperty() );}
            @Override protected boolean computeValue() {
                return !blinkProperty().get() &&  displayCaret.get() && textInput.isFocused() &&
                        (isWindows() || (textInput.getCaretPosition() == textInput.getAnchor()))
                        && !textInput.isDisabled();
            }
        };
        // rebind opacity to replaced caretVisible property
        caretPath.opacityProperty().bind(new DoubleBinding() {
            { bind(caretVisible); }
            @Override protected double computeValue() {
                return caretVisible.get() ? 1.0 : 0.0;
            }
        });

    }

    BooleanProperty blinkAlias;

    BooleanProperty blinkProperty() {
        if (blinkAlias == null) {
            Class<?> clazz = TextInputControlSkin.class;
            try {
                Field field = clazz.getDeclaredField("blink");
                field.setAccessible(true);
                blinkAlias = (BooleanProperty) field.get(this);
            } catch (NoSuchFieldException | SecurityException
                   | IllegalArgumentException | IllegalAccessException e) {
                // TBD: errorhandling
                e.printStackTrace();
            }

        }
        return blinkAlias;
    }

}

// usage in a custom TextArea
TextArea textarea = new TextArea() {

    @Override
    protected Skin<?> createDefaultSkin() {
        return new MyTextAreaSkin(this);
    }

};


text:
Q: Actionscript 3.0 addchild Here's my code, the problem is that it doesn't add the sprite when i call it from my main function in main.
package{

import flash.display.*;
import flash.events.*;

public class gfxs extends MovieClip{

    public function gfxs(){
    }
    public function placeCar(){
       var car:MoonCar = new MoonCar();
       car.x = 100;
       car.y = 372;
       addChild(car);
       trace("PLACED CAR"); //JUST TO CHEK IF IT RUNS THIS CODE(IT DOES)
    }
}

}

A: You need to add gfxs to the stage in your main class. For example in you main.as you might have something like this :
var myGfxs:gfxs = new gfxs();
myGfxs.placeCar();
addChild(myGfxs);

Hard to give a definitive answer as we canot see what you have done in your main.as file.


text:
Q: How would I make program subtract the previous temp and current temp An interactive C++ program whose input is a series of 12 temperatures from the user. It should write out on file tempdata.dat each temperature as well as the difference between the current temperature and the one preceding it. The difference is not output for the first temperature that is input. At the end of the program, the average temperature should be displayed for the user via cout.
Here is What I have so far:
#include <iostream>
#include <fstream>

using namespace std;

int main() {

    int counter = 0;
    int previousTemp;
    ofstream file; //declares a file of type ofstream
    file.open("temperaturefile.txt"); //opens the file with open method
    int temperature = 0;
    int difference = 0;
    cout << "Enter 12 temperatutes" << endl;

    file << temperature;

    while (counter < 12)
    {

        cin >> temperature;
        counter++;
//        difference = temperature-previousTemp;
//        cout << difference << endl;
//
    }

}

A: You have it commented in your code? I don't understand
difference = temperature-previousTemp;

You can keep track of previousTemp at the end of your loop.
After everything in the loop put
previousTemp=temperature;


text:
Q: Showing the convergence in probabilty of two Ito integrals
Consider a Brownian Motion, $B(t)$, which are all $\mathcal F_t$ measurable. Let $f,f_n$ be in $L_{ad}^2\{[a,b] \times \Omega\}$, which are the set of stochastic processes that are adapted to the filtration $\{\mathcal F_t\}$ and satisfy $\int_a^bE\left(f(t)^2\right)dt < \infty$. Suppose that $\int_a^b|f(t)-f_n(t)|dt\to0$ almost surely. Prove that $\int_a^bf_n(t)dB(t) \to \int_a^bf_n(t)dB(t)$ in probability.

I am trying to show this two different ways. First by using $L^2$ convergence which will then imply convergence in probability. What I have for this way is the following:
Since $f$ and $f_n$ are in $L_{ad}^2$ then the ito integral $\int_a^bf(t)-f_n(t)dB(t)$ exists and $E\left|\int_a^bf(t)-f_n(t)dB(t)\right|^2=\int_a^bE\left|f(t)-f_n(t)\right|^2dt$, so it will suffice to show that the right hand side of this equal sign converges to $0$ which i'm unsure how to do.
Second, I am try to show this directly using the definition of convergence in probability.
$P\left(\left|\int_a^bf(t)-f_n(t)dB(t)\right|>\epsilon\right)\le\frac{1}{\epsilon}E\left|\int_a^bf(t)-f_n(t)dB(t)\right|$, hence if I could show that $\int_a^bf(t)dB(t) \to \int_a^bf_n(t)dB(t)$ in $L^1$ then I would be done.
Similarly,
$ P\left(\left|\int_a^bf(t)-f_n(t)dB(t)\right|>\epsilon\right)\le\frac{1}{\epsilon^2}E\left|\int_a^bf(t)-f_n(t)dB(t)\right|^2= \frac{1}{\epsilon^2}\int_a^bE\left|f(t)-f_n(t)\right|^2dt$ so if we could show this last term converged to $0$ then we would be done.


text:
Q: Display a specific record from an xml file using ASP.NET mvc5 I'm having issues figuring out what's wrong here. It's giving me an error was node does not exist in its context:
XmlDocument doc = new XmlDocument();
doc.Load("path");

Personal persons = doc.SelectNodes("/Persons/record")
 .Cast<XmlNode>()
 .Where(ID.Equals(node["ID"].InnerText) ==> This node does not exist
 .Select(node => new Personal()
 {
     ID = node["ID"].InnerText,
     Name = node["Name"].InnerText,
     Email = node["Email"].InnerText,
     DateOfBirth = node["DateOfBirth"].InnerText,
     Gender = node["Gender"].InnerText,
     City = node["City"].InnerText
 }).FirstOrDefault());

return View(persons);

XML:
<?xml version="1.0" encoding="UTF-8"?>
<Persons>
  <record>
    <ID>1602081497499</ID>
    <Name>Graham, Echo J.</Name>
    <Email>diam@Nullaeu.net</Email>
    <DateOfBirth>11/07/93</DateOfBirth>
    <Gender> Female</Gender>
    <City>Lloydminster</City>
  </record>
  <record>
    <ID>1688110330299</ID>
    <Name>Larson, Kevin K.</Name>
    <Email>eu.augue@penatibuset.co.uk</Email>
    <DateOfBirth>03/11/94</DateOfBirth>
    <Gender>Male </Gender>
    <City>Habra</City>
  </record>
</Persons>

I've tried changing it to xmlNode, contains, and others. Please and thanks for helping.

A: Here is a solution using Xml Linq which is a new Visual Studio library than older XmlElement
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication71
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            string id = "123";

            XDocument doc = XDocument.Load(FILENAME);
            List<Personal> personals = doc.Descendants("record").Select(x => new Personal()
            {
                ID = (string)x.Element("ID"),
                Name = (string)x.Element("Name"),
                Email = (string)x.Element("Email"),
                DateOfBirth = (DateTime)x.Element("DateOfBirth"),
                Gender = (string)x.Element("Gender"),
                City = (string)x.Element("City")
            }).Where(x => x.ID == id).ToList();
        }

    }
    public class Personal
    {
        public string ID {get ; set; }
        public string Name {get ; set; }
        public string Email {get ; set; }
        public DateTime DateOfBirth {get ; set; }
        public string Gender {get ; set; }
        public string City { get; set; }
    }
}


text:
Q: Collapse duplicates in python list sorry if this is a duplicate thread but I couldn't find one.
I'm currently trying to make an inventory for a game that is in the works. The problem I run into is that, when you have a lot of a particular item, it kind of wastes a lot of space.
Here's my code: (inv is the inventory)
inv = ["item1","item2","item3","item2","item2","item1"]

print(', '.join(inventory))

Output:
item1, item2, item3, item2, item2, item1

I'd like to, instead of doing that, do this:
item1 x2, item2 x3, item3

I don't really care if you need item3 to be x1, either way would be fine, thanks.

A: There are many options actually. The main goal is to count your items, and print them out in order.
One option is to use collections.OrderedDict. Others are collections.Counter/collections.defaultdict, but I'll give you an example with the former:
from collections import OrderedDict

counter = OrderedDict()

inv = ["item1", "item2", "item3", "item2", "item2", "item1"]
for i in inv:
    if i not in counter:
        counter[i] = 0

    counter[i] += 1

for c in counter:
    if counter[c] > 1:
        print(c + ' x{}'.format(counter[c]))
    else:
        print(c)

This prints:
item1 x2
item2 x3
item3

You're free to modify this example as needed if you want to print them out in one line. This code was written in python3.x.

A: Here is an example with Counter:
from collections import Counter

inv = ["item1", "item2", "item3", "item2", "item2", "item1"]

print (', '.join('%s x%d' % (item, count)
                 for item, count in sorted(Counter(inv).items())))

A: out = ['{} x{}'.format(item, inv.count(item)) if inv.count(item) > 1 else item
   for item in set(inv)]

out:
['item1 x2', 'item2 x3', 'item3']


text:
Q: What element to use if I only need an placement target element I want to show a flyout at a specific place. I want to specify a placement target element in XAML, but I want to make sure I am using the "lightest" element possible, given that I don't want that element to ever be visible or interacted with.
Is there a "recommended" or "correct" element to use? If not, what would be the "lightest" element to use? Or am I overthinking this and should just use a button?

A:
I want to show a flyout at a specific place.

The place of FrameworkElements are based on the panel that you are using to hold them. If you want to show your flyout based on a FrameworkElement being placed in a specific place, you can use Canvas to position your FrameworkElement.

I want to specify a placement target element in XAML, but I want to make sure I am using the "lightest" element possible.

Flyout.ShowAt takes FrameworkElement as it's placement target. So I think the "lightest" element would be an empty custom FrameworkElement like below:
public class MyElement:FrameworkElement
{
}

And you can put it into XAML and use Canvas to position it:
<Page
  x:Class="PopupSample.MainPage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="using:PopupSample"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  mc:Ignorable="d">

<Canvas>
    <Button Name="btnClick" Canvas.Left="50" Canvas.Top="500" Click="btnClick_Click">Click Me</Button>
    <local:MyElement x:Name="myEle" Canvas.Left="100" Canvas.Top="100"></local:MyElement>
</Canvas>

Code-Behind:
public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    private void btnClick_Click(object sender, RoutedEventArgs e)
    {
        Flyout flyout = new Flyout();
        TextBlock tbContent = new TextBlock
        {
            Text= "this is a flyout content"
        };
        flyout.Content = tbContent;
        flyout.ShowAt(myEle);
    }
}

A: Grid is a pretty light element, it's just a simple Panel-derived class without any child elements. Button is a Control, meaning it has a template which will create many child elements that make up its visual appearance.
Are you saying you want to use a dummy element just for the purpose of specifying the position of the flyout which you will show programmatically? If you want to avoid the element altogether, then maybe a Popup would be a better choice.


text:
Q: faster mongoimport, in parallel in airflow? tl;dr: there seems to be a limit on how fast data is inserted into our mongodb atlas cluster. Inserting data in parallel does not speed this up. How can we speed this up? Is our only option to get a larger mongodb atlas cluster with more Write IOPS? What even are write IOPS?
We replace and re-insert >10GB+ of data daily into our mongodb cluster with atlas. We have the following 2 bash commands, wrapped in python functions to help parameterize the commands, that we use with BashOperator in airflow:
upload single JSON to mongo cluster
def mongoimport_file(mongo_table, file_name):
    # upload single file from /tmp directory into Mongo cluster
    # cleanup: remove .json in /tmp at the end
    uri = 'mongodb+srv://<user>:<pass>@our-cluster.dwxnd.gcp.mongodb.net/ourdb'
    return f"""
        echo INSERT \
        && mongoimport --uri "{uri}" --collection {mongo_table} --drop --file /tmp/{file_name}.json \
        && echo AND REMOVE LOCAL FILEs... \
        && rm /tmp/{file_name}.json
    """

upload directory of JSONs to mongo cluster
def mongoimport_dir(mongo_table, dir_name):
    # upload directory of JSONs into mongo cluster
    # cleanup: remove directory at the end
    uri = 'mongodb+srv://<user>:<pass>@our-cluster.dwxnd.gcp.mongodb.net/ourdb'
    return f"""
        echo INSERT \
        && cat /tmp/{dir_name}/*.json | mongoimport --uri "{uri}" --collection {mongo_table} --drop \
        && echo AND REMOVE LOCAL FILEs... \
        && rm -rf /tmp/{dir_name}
    """

There are called in airflow using the BashOperator:
import_to_mongo = BashOperator(
    task_id=f'mongo_import_v0__{this_table}',
    bash_command=mongoimport_file(mongo_table = 'tname', file_name = 'fname')
)

Both of these work, although with varying performance:

*

*mongoimport_file with 1 5GB file: takes ~30 minutes to mongoimport

*mongoimport_dir with 100 50MB files: takes ~1 hour to mongoimport

There is currently no parallelization with ** mongoimport_dir**, and in fact it is slower than importing just a single file.

*

*Within airflow, is it possible to parallelize the mongoimport of our directory of 100 JSONs, to achieve a major speedup? If there's a parallel solution using python's pymongo that cannot be done with mongoimport, we're happy to switch (although we'd strongly prefer to avoid loading these JSONs into memory).

*What is the current bottleneck with importing to mongo? Is it (a) CPUs in our server / docker container, or (b) something with our mongo cluster configuration (cluster RAM, or cluster vCPU, or cluster max connections, or cluster read / write IOPS (what are these even?)). For reference, here is our mongo config. I assume we can speed up our import by getting a much bigger cluster but mongodb atlas becomes very expensive very fast. 0.5 vCPUs doesn't sound like much, but this already runs us $150 / month...

A: First of all "What is the current bottleneck with importing to mongo?" and "Is it (a) CPUs in our server / docker container " - don't believe to anyone who will tell you the answer from the screenshot you provided.
Atlas has monitoring tools that will tell you if the bottleneck is in CPU, RAM, disk or network or any combination of those on db side:

On the client side (airflow) - please use system monitor of your host OS to answer the question. Test disk I/O inside docker. Some combinations of host OS and docker storage drivers performed quite poor in the past.
Next, "What even are write IOPS" -  random
write operations per second
https://cloud.google.com/compute/docs/disks/performance
IOPS calculation differs depending on cloud provider. Try AWS and Azure to compare cost vs speed. M10 on AWS gives you 2 vCPU, yet again I doubt you can compare them 1:1 between vendors. The good thing is it's on-demand and will cost you less than a cup of coffee to test and delete the cluster.
Finally, "If there's a parallel solution using python's pymongo" - I doubt so. mongoimport uses batches of 100,000 documents, so essentially it sends it as fast as the stream is consumed on the receiver. The limitations on the client side could be: network, disk, CPU. If it is network or disk, parallel import won't improve a thing. Multi-core systems could benefit from parallel import if mongoimport was using a single CPU and it was the limiting factor. By default mongoimport uses all CPUs available: https://github.com/mongodb/mongo-tools/blob/cac1bfbae193d6ba68abb764e613b08285c6f62d/common/options/options.go#L302. You  can hardly beat it with pymongo.


text:
Q: how to remove accents from a string in python i recently made a test in university and the question was like this-"ask a name,and remove the accents from it and print it"(there was more to the question but this was the main problem for me).
My teacher didn´t allow us to use string or list methods, just the basic things literally(if, while loop, for loop, arrays),the only methods that we where allowed to use were the find() , index() and len().
So for example the name José needed to be printed has Jose, or José Magalhães should be Jose Magalhaes
If you could say a way to to this with the basic things i would be appreciated.
thank you.

A: The translate function is usually the fastest for this given that it's a one to one character mapping:
normalMap = {'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A',
             'à': 'a', 'á': 'a', 'â': 'a', 'ã': 'a', 'ä': 'a', 'ª': 'A',
             'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E',
             'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e',
             'Í': 'I', 'Ì': 'I', 'Î': 'I', 'Ï': 'I',
             'í': 'i', 'ì': 'i', 'î': 'i', 'ï': 'i',
             'Ò': 'O', 'Ó': 'O', 'Ô': 'O', 'Õ': 'O', 'Ö': 'O',
             'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o', 'ö': 'o', 'º': 'O',
             'Ù': 'U', 'Ú': 'U', 'Û': 'U', 'Ü': 'U',
             'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u',
             'Ñ': 'N', 'ñ': 'n',
             'Ç': 'C', 'ç': 'c',
             '§': 'S',  '³': '3', '²': '2', '¹': '1'}
normalize = str.maketrans(normalMap)

output:
print("José Magalhães ".translate(normalize))
# Jose Magalhaes

If you're not allowed to use methods of str, you can still use the dictionary:
S = "José Magalhães "
print(*(normalMap.get(c,c) for c in S),sep="")
# Jose Magalhaes

If you're not allowed to use a dictionary, you can use two strings to map the characters and loop through the string:
fromChar = "ÀÁÂÃÄàáâãäªÈÉÊËèéêëÍÌÎÏíìîïÒÓÔÕÖòóôõöºÙÚÛÜùúûüÑñÇ秳²¹"
toChar   = "AAAAAaaaaaAEEEEeeeeIIIIiiiiOOOOOoooooOUUUUuuuuNnCcS321"

S = "José Magalhães "
R = ""                                 # start result with an empty string
for c in S:                            # go through characters
    p = fromChar.find(c)               # find position of accented character
    R += toChar[p] if p>=0 else c      # use replacement or original character

print(R)
# Jose Magalhaes

A: text_normalizing_map = {'À': 'A',
        'Á': 'A',
        'Â': 'A',
        'Ã': 'A',
        'Ä': 'A',
        'È': 'E',
        'É': 'E',
        'Ê': 'E',
        'Ë': 'E',
        'Í': 'I',
        'Ì': 'I',
        'Î': 'I',
        'Ï': 'I',
        'Ù': 'U',
        'Ú': 'U',
        'Û': 'U',
        'Ü': 'U',
        'Ò': 'O',
        'Ó': 'O',
        'Ô': 'O',
        'Õ': 'O',
        'Ö': 'O',
        'Ñ': 'N',
        'Ç': 'C',
        'ª': 'A',
        'º': 'O',
        '§': 'S',
        '³': '3',
        '²': '2',
        '¹': '1',
        'à': 'a',
        'á': 'a',
        'â': 'a',
        'ã': 'a',
        'ä': 'a',
        'è': 'e',
        'é': 'e',
        'ê': 'e',
        'ë': 'e',
        'í': 'i',
        'ì': 'i',
        'î': 'i',
        'ï': 'i',
        'ù': 'u',
        'ú': 'u',
        'û': 'u',
        'ü': 'u',
        'ò': 'o',
        'ó': 'o',
        'ô': 'o',
        'õ': 'o',
        'ö': 'o',
        'ñ': 'n',
        'ç': 'c'}

def normalize(text):
    list_text = list(text)
    for index, i in enumerate(list_text):
        val = text_normalizing_map.get(i)
        if(val):
            list_text[index] = val
    return "".join(list_text)

print(normalize("José Magalhães "))

output
Jose Magalhaes


text:
Q: MKMapSnapshotter satellite error image when camera zoom / altitude level is close in I am getting an error image when I use MKMapsnapshotter.
I tried manually zooming out (setting a higher camera altitude) and that seems to fix the issue, but I am not sure how to handle this programmatically. Is there a way to detect this kind of error and then reset the camera altitude? Is this a MapKit bug? This happens when I use a satellite or hybrid map type.
http://imgur.com/vWsu3Nc
MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc] initWithOptions:options];
      [snapshotter startWithCompletionHandler:^(MKMapSnapshot *snapshot, NSError *error) {

if (!snapshot.image || error) {
// Can't create snapshot. Use Placeholder
   mapImage.image = [UIImage imageNamed:@"NoPhoto.png"];
   NSLog(@"Snapshot Error: %@",[error localizedDescription]);
}

Any help would be greatly appreciated. Thanks!

EDIT:
After more research and testing, I was able to figure out a workaround.
This error image was mainly happening in satellite imagery over oceans/seas. I found that I can use reverse geocoder and check the placemark array to see if the location is in a city. If not, then it is probably over an ocean.
// Check location of satellite imagery
CLLocation *location = [[CLLocation alloc] initWithLatitude:myLatitude longitude:myLongitude];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];

[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray* placemarks, NSError* error){
    // check to see if location is in a city
    if ([placemarks[0] locality]) {
        // set up camera
        MKMapCamera  *myCamera = [MKMapCamera
             cameraLookingAtCenterCoordinate:location.coordinate
             fromEyeCoordinate:location.coordinate
             eyeAltitude:250];

        // set snapshot options
        MKMapSnapshotOptions *options = [[MKMapSnapshotOptions alloc] init];
        options.camera = myCamera;
        options.showsBuildings = YES;
        options.showsPointsOfInterest = NO;
        options.mapType = MKMapTypeSatellite;
        options.scale = [UIScreen mainScreen].scale;
        options.size = myImage.frame.size;

        MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc] initWithOptions:options];
        [snapshotter startWithCompletionHandler:^(MKMapSnapshot *snapshot, NSError *error) {
            if(!error) {
                myImage.image = snapshot.image;
            }
        }]; // end snapshotter completion handler

    } else {
        // probably in the ocean
        myImage.image = [UIImage imageNamed:@"NoPhoto.png"];
    }
}];


text:
Q: why my google cloud instance often shut down automatically by itself my google cloud instance(compute engine) was shut down automatically with unknown reason
there is the event log for the instance
{"shutdownEvent":{},"bootCounter":"6","@type":"type.googleapis.com/cloud_integrity.IntegrityEvent"}

{
 insertId:  "0"
 jsonPayload: {
  @type:  "type.googleapis.com/cloud_integrity.IntegrityEvent"
  bootCounter:  "6"
  shutdownEvent: {
  }
 }
 logName:  "projects/<xxxx>/logs/compute.googleapis.com%2Fshielded_vm_integrity"
 receiveTimestamp:  "2019-05-09T10:14:29.112673979Z"
 resource: {
  labels: {
   instance_id:  "<xxxx>"
   project_id:  "<xxxx>"
   zone:  "us-west1-b"
  }
  type:  "gce_instance"
 }
 severity:  "NOTICE"
 timestamp:  "2019-05-09T10:14:26.928978844Z"
}

A: gcloud compute instances update INSTANCE_NAME --shielded-learn-integrity-policy

Instance must be running and have Integrity Monitoring enabled.
I don't know if this is secure though. Read more:
https://cloud.google.com/compute/docs/instances/integrity-monitoring#updating-baseline

A: This seems to be a shielded VM with "integrity monitoring" enabled
... and most likely this is caused by an integrity validation failure.

A: You might use Stackdriver Advanced Logs Filters and try to get more details about the reason behind the shutdown, for example, sometimes instances are migrated (Live Migration) and cause the behavior reported.
Some filters that may help you to determine what caused the shutdown on instances are:

*

*Checking for migrations, in Stackdriver Advanced Logging filter, use following entries:

compute.instances.migrationOnHostMaintenance
OR
compute.instances.migrateOnHostMaintenance

*For hostError, you can use following filter:

"compute.instances.hostError"

*For VM Instance Stop:

resource.type="gce_instance"
protoPayload.methodName="v1.compute.instances.stop"

A: had the some problem and confirmed from gcp that my vm had moved from one physics host to another..
pls feel free to open case and google customer support will help you diagnostics


text:
Q: How to add a custom message in obiee 11g/12c? I have added a new text in l_en/messages/text.xml
<?xml version = '1.0' encoding = 'UTF-8'?>
<WebMessageTables>
  <WebMessageTable lang="en-us" system="Test" table="Tests">
  <WebMessage name="kmsgSystemTest">
  <TEXT>Test</TEXT>
</WebMessage>
</WebMessageTable>
</WebMessageTables>

But when I try to use kmsgSystemTest, console error says "kmsgSystemTest" is not defined.
Should I declare this new text somewhere else?

A: Documentation states that custom messages should go in the customMessages folder inside
ORACLE_INSTANCE\bifoundation\OracleBIPresentationServicesComponent\coreapplication_obipsn\msgdb\l_xx
(where xx is the language identifier, l_en in your case).
Also don't forget to restart the BI Presentation Services.
Hope it helps
(doc link)


text:
Q: Ubuntu 15.04 internet only works for a few minutes after boot I recently purchased a Toshiba satellite L15W-B1208D two in one laptop/tablet. The first thing I did was to wipe websites and install Ubuntu 14.04, as that was the distro I was used to. With 14.04 installed I could only use the internet for about 5-10 minutes after booting the machine. After that it would still say it was connected to Wi-Fi but I could not use the internet to do anything. Browsers would time out, curl would not work, the software center couldn't download packages, etc. I spent days reading forums and trying everything that was suggested in previous posts. Finally I found a post saying an upgrade to 15.04 could help, so I tried it. The internet seems to last a little longer but eventually it disappears and the only way to reconnect is rebooting.
Please do not mark this as off topic because it can't be reproduced; it happens every time I boot on any different Wi-Fi network.
I apologize for the long post, I'm a first time poster and wanted to be detailed. Let me know if there are any commands I could run and post the output of to help diagnose.
Additional info: the machine has no Ethernet connection and has a Realtek RTL8723BE network driver, currently running 15.04 as the only OS.
Thanks in advance!
Edit: Thanks for the quick reply Jeremy!
On 14.04 I first tried the basics like resetting the router and restarting network-manager from the command line. After that I tried live booting from a usb stick to see if the problem persisted, which it did. Then I tried changing the IPv6 settings to "link local only" as suggested here: WIreless connects but Internet stops working on Ubuntu 12.04 64 Bit and Broadcom 4313. Then I tried
sudo dhclient wlan0
as suggested here: Internet stops working after a few minutes (13.04).
Then I tried
sudo apt-get remove network-manager
and reinstalling it from a flash drive. Next I tried this block of code:
sudo modprobe ath5k nohwcrypt
sudo sh -c "echo 'options ath5k nohwcrypt' >/etc/modprobe.d/custom-wireless.conf"
sudo apt-get remove libnss-mdns
as suggested by this post: Internet stops working after some time
The last thing I tried before switching to 15.04 was to uninstall and reinstall every package I could think of. I'm not sure how to reinstall my network driver so I haven't done so yet. I haven't retried any of these methods since wiping the disk and installing 15.04.

A: Since you have the rtl8723be, the first thing I would try is
echo "options rtl8723be fwlps=N" | sudo tee /etc/modprobe.d/rtl8723be.conf
Reboot, this parameter of the kernel module disables power management which is known to cause issues with the Realtek wifi cards.


text:
Q: Is it possible to set context name in SNMPv3 using pySNMP library There is one simulator available using pySNMP called SNMP simulator.
It sets a default context name value.
Is there anyway to set custom context name value for snmpv3 ?
Here is an extract from snmpsimd.py where i tried to give context name value.
config.addContext(snmpEngine, '')

Giving value as custom parameter is not setting value there.

A: If you are building an Agent, you should register your contextName at SnmpContext class instance. See examples here and here.
If your app is a Manager based on pysnmp's high-level API, you should pass contextName to getCmd/setCmd(). See example an here (search for contextName).
Please clarify your task if my suggestions do not help.


text:
Q: ASP.NET - Master Page Disables Validator Error Message Ok Simple : TextBox, RequiredFieldValidator, Button
Without a Master Page - if the TextBox is empty - I get an Error Message when Clicking Button.
With a Master Page - if the TextBox is empty - I get NO Error Message when Clicking Button.
This happened recently without changing the code. Simply creating a DEFAULT Master Page and putting these three controls in it will result in NOT having an Error Message.
I am at a loss on how to fix this. It seems not code-related as a default Master Page stops the error message from showing up.
Should I reinstall Visual Studio 2010 Ultimate?
Browser Independent, Recent, Not Code Related AFAIK, just started happening recently.
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator
            ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
        <asp:Button ID="Button1"
            runat="server" Text="Button" onclick="Button1_Click"
            ValidationGroup="RequiredFieldValidator1" />
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {

    }
}

A: I think you're experiencing the problem because you have the validation group set for your button, however, it is not set for the TextBox and the Validator control itself.
Try to assign the same ValidationGroup for all controls that are participating in your validation scenario. It seems that you have misused the
ValidationGroup="RequiredFieldValidator1"

Property. You don't have to use the Id of the RequiredFieldValidator as your button's ValidationGroup (you can, but you don't have to). Please refer to the following article for more details:
http://msdn.microsoft.com/en-us/library/ms227424%28v=vs.100%29.aspx
Anyway, the

ValidationGroup

property has to be the same for all controls that belong to your validation scenario. In your case this is TextBox, Button and the Validator control.


text:
Q: MYSQL Connector/NET 8.0.25 Upgrading failed Can anyone please help me to resolve below error? I tried many times by uninstall and reinstall again but no luck.
The action 'Upgrade' for product 'Connector/NET 8.0.25' failed.
Thanks in advance

A: If you have problems uninstalling the old version you can try running the "Microsoft Troubleshooter to install and uninstall programs", at present you can download from here:
https://support.microsoft.com/en-us/topic/fix-problems-that-block-programs-from-being-installed-or-removed-cca7d1b6-65a9-3d98-426b-e9f927e1eb4d
Once you uninstalled the old version you can install the newest version


text:
Q: Error in infinite sum The binary weight of the non negative integer k is defined by
w[k_] := Total[IntegerDigits[k, 2]]

The first values are (cf. http://oeis.org/ A000120)
Table[w[k], {k, 0, 10}]

(*
  {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2}
*)

Now define formally the generating function
g[z_] = Sum[w[k] z^k, {k, 0, ∞}]

(*
  (2 - z)/(-1 + z)^2
*)

Most surprisingly, Mathematica returns an explicit result.
But this can't be correct, as the expansions about z = 0 differ
Sum[w[k] z^k, {k, 0, 5}]

(*
  z + z^2 + 2 z^3 + z^4 + 2 z^5
*)

Series[(2 - z)/(-1 + z)^2, {z, 0, 5}] // Normal

(*
  2 + 3 z + 4 z^2 + 5 z^3 + 6 z^4 + 7 z^5
*)

It looks as if in the infinite sum the function w[k] is replaced by (k + 2).
Any explanation? Seems to be a bug.
EDIT #1
24.02.15 19:08
To avoid the head replacement effect pointed out by belisarius we can consider the function
w1[n_] := n - Sum[IntegerExponent[k, 2], {k, 1, n}]

which is identical to w[k] for any k.
Now the infinite sum
g1[z_] = Sum[w1[n] z^n, {n, 0, \[Infinity]}]

is returned unevaluated, as it "should" (because it is too complicated)
$\sum _{n=0}^{\infty } z^n \left(n-\sum _{k=1}^n \text{IntegerExponent}[k,2]\right)$
So my discovery is not a bug, but I have learned the lesson that one should be very careful with infinite sums and their interpretation of the terms to be added.

A: The problem is that Total[] works with any head. So:
Total[Derivative[1, 2, 1]]
(* 4 *)

Total[IntegerDigits[k, 2]]
(* 2 + k *)

And so you can expect
Sum[(2 + k) z^k, {k, 0, ∞}] == Sum[Total[IntegerDigits[k, 2]] z^k, {k, 0, ∞}]


text:
Q: How to upload a "Image only from client side to SharePoint Custom List" using Rest Api ? not in Document Library and not in picture Library I'm new to SharePoint & REST API. So kindly help me with Step by Step Instructions.
I have one custom list called "Attachment" within this custom list I have one Attachment column named as "Attach" which is created with the data type "Hyperlink or Picture".
Using Rest API I want to add the Image which is selected by the end user in client side (browser) to SharePoint Custom list named as "Attachment" under the column "Attach".
Help me with the working Code Samples.
Note: I'm trying this in visual studio 2017 as a SharePoint Hosted App.
This is my Default.aspx page code.

Attachments
<input type="file" class="form-control" id="attch"/>

"I expect when the user selected any image using this control, I need to upload and store that image to custom List" not in document library , not in picture gallery. Only in Custom List.
Kindly Give me a Visual Studio Solution File (or) Give me a Clear Working code For Default.aspx and App.js with the Script.
Thanks in Advance!!!

A: The "Hyperlink or Picture" field only store the link of the image.
If you only want to store the image in custom list, we need store the images as attachments. I suggest you store the images into a document library or picture library, then use a "Hyperlink or Picture" to store the link of the images.
To upload image as attachment in list items using REST API, the following articles for your reference.
Working with files attached to list items by using REST
Uploading Attachments to SharePoint Lists Using REST

A: you need to create a document library instead and upload the image to it,
you can try this js to upload the image,

function _arrayBufferToBase64(buffer) {
var binary = ''
var bytes = new Uint8Array(buffer)
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i])
}
return binary;
}

 function uploadfile(name, content) {
  var createitem = new SP.RequestExecutor(appweburl);
createitem.executeAsync({
  url: appweburl + "/_api/web/GetFolderByServerRelativeUrl('/sites/Tile of web/app title/Lists/list name/foldername')/Files/Add(url='" + name + "',overwrite=true)",
    method: "POST",
    binaryStringRequestBody: true,
    body: content,
    success: function (e) {
        alert('done');
    },
    error: function () { alert("Error"); },
    state: "Update"
 });
}


text:
Q: EF Core DDD ValueObject property is part of a key and so cannot be modified or marked as modified Hello I sometimes have in parallel integration tests problem with saving entities. EF Core throws exception with message: The property 'Order.Price#Money.OrderId' is part of a key and so cannot be modified or marked as modified.
It is really curious that I run single test 'should_get_order' and everything is fine, but when I try to run all tests sometimes I have issue
Here is implementation
public class Order : AggregateRoot
{
    // some other props
    public Money Price { get; private set; }

    public Order()
    {
        Price = Money.Zero; // exception throws but when I change to new Money(0) everything works fine
    }

    public static Order Create()
    {
        return new Order();
    }
}

public abstract class AggregateRoot
{
    public AggregateId Id { get; protected set; }
}

public class AggregateId<T> : IEquatable<AggregateId<T>>
{
    public T Value { get; }

    public AggregateId(T value)
    {
        Value = value;
    }

    public bool Equals(AggregateId<T>? other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return EqualityComparer<T>.Default.Equals(Value, other.Value);
    }

    public override bool Equals(object? obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((AggregateId<T>)obj);
    }

    public override int GetHashCode()
    {
        return EqualityComparer<T>.Default.GetHashCode(Value);
    }
}

public class AggregateId : AggregateId<Guid>
{
    public AggregateId() : this(Guid.NewGuid())
    {
    }

    public AggregateId(Guid value) : base(value)
    {
    }

    public static implicit operator Guid(AggregateId id) => id.Value;
    public static implicit operator AggregateId(Guid id) => new(id);
}

public class Money : IEquatable<Money>
{
    public static readonly Money Zero = new Money(0);
    public decimal Value { get; }

    public Money(decimal value)
    {
        if (value < 0)
        {
            throw new InvalidOperationException($"Money '{value}' cannot be negative");
        }

        Value = value;
    }

    public Money ChangeValue(decimal value)
    {
        return new Money(value);
    }

    public bool Equals(Money? other)
    {
        if (other is null) return false;
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return Value == other.Value;
    }

    public override bool Equals(object? obj)
    {
        if (obj as Money is null) return false;
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != GetType()) return false;
        return Equals((Money)obj);
    }

    public override int GetHashCode()
    {
        return EqualityComparer<decimal>.Default.GetHashCode(Value);
    }

    public override string ToString()
    {
        return Value.ToString("0.00", CultureInfo.CreateSpecificCulture("en-US"));
    }
}

Configuration
internal class OrderConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.HasKey(o => o.Id);

        builder
            .Property(o => o.Id)
            .HasConversion(id => id.Value, id => new AggregateId(id));

        builder.OwnsOne(i => i.Price, navigation =>
        {
            navigation.Property(m => m.Value).HasColumnName("Cost").IsRequired().HasPrecision(14, 4);
        });
    }
}

Integration test
public class OrdersTests : IClassFixture<TestApplicationFactory<Program>>,
    IClassFixture<TestDbContext>
{
    [Fact]
    public async Task should_get_order()
    {
        var order = Order.Create();
        await _dbContext.AddAsync(order); // here there are some exceptions
        await _dbContext.SaveChangesAsync();

        var response = await _client.Request($"{Path}/{order.Id.Value}").GetAsync();
        var order = await response.GetJsonAsync<Order>();

        order.ShouldNotBeNull();
    }

    // some other tests
}

public class TestApplicationFactory<TProgram> : WebApplicationFactory<TProgram> where TProgram : class
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseEnvironment("test");
    }
}

public class TestDbContext : IDisposable
{
    internal OrderDbContext DbContext { get; }

    private const string AppSettings = "appsettings.test.json";

    private static readonly IConfiguration Configuration =  new ConfigurationBuilder().AddJsonFile(AppSettings)
                                                      .AddEnvironmentVariables()
                                                      .Build();

    public TestDbContext()
    {
        DbContext = new OrderDbContext(new DbContextOptionsBuilder<OrderDbContext>().UseNpgsql(Configuration["database:connectionString"])
                                    .EnableSensitiveDataLogging()
                                    .Options);
    }

    public void Dispose()
    {
        DbContext?.Database.EnsureDeleted();
        DbContext?.Dispose();
    }
}

When I change Price to new Money(0) there is no exceptions. Maybe the problem is in public static readonly field?
Message:
System.InvalidOperationException : The property 'Order.Price#Money.OrderId' is part of a key and so cannot be modified or marked as modified. To change the principal of an existing entity with an identifying foreign key, first delete the dependent and invoke 'SaveChanges', and then associate the dependent with the new principal.

Stack Trace:
    InternalEntityEntry.SetPropertyModified(IProperty property, Boolean changeState, Boolean isModified, Boolean isConceptualNull, Boolean acceptChanges)
ChangeDetector.PropertyChanged(InternalEntityEntry entry, IPropertyBase propertyBase, Boolean setModified)
InternalEntityEntryNotifier.PropertyChanged(InternalEntityEntry entry, IPropertyBase property, Boolean setModified)
InternalEntityEntry.SetProperty(IPropertyBase propertyBase, Object value, Boolean isMaterialization, Boolean setModified, Boolean isCascadeDelete, CurrentValueType valueType)
InternalEntityEntry.SetProperty(IPropertyBase propertyBase, Object value, Boolean isMaterialization, Boolean setModified, Boolean isCascadeDelete)
InternalEntityEntry.PropagateValue(InternalEntityEntry principalEntry, IProperty principalProperty, IProperty dependentProperty, Boolean isMaterialization, Boolean setModified)
NavigationFixer.SetForeignKeyProperties(InternalEntityEntry dependentEntry, InternalEntityEntry principalEntry, IForeignKey foreignKey, Boolean setModified, Boolean fromQuery)
NavigationFixer.InitialFixup(InternalEntityEntry entry, Boolean fromQuery)
NavigationFixer.StateChanged(InternalEntityEntry entry, EntityState oldState, Boolean fromQuery)
InternalEntityEntryNotifier.StateChanged(InternalEntityEntry entry, EntityState oldState, Boolean fromQuery)
InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey)
EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1 node)
EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)
DbContext.SetEntityState(InternalEntityEntry entry, EntityState entityState)
DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState)
DbContext.Add[TEntity](TEntity entity)
OrdersControllerTests.given_valid_order_item_should_add_to_order() line 24
--- End of stack trace from previous location ---


text:
Q: EBNF: one or more and zero or more, in no particular order In an EBNF grammar I have two tokens shape and attr. How would I express that shape should occur one or more times and attr zero or more times, but in no particular order, i.e.:
shape1 shape2 shape3
attr1 shape1
shape1 attr1
shape1 shape2 attr1 shape3

Would all be parsed, but
attr1 attr2 ..
would not?

A: Answering my own question:
seq = shape as_seq | attr seq
as_seq = (shape | attr)*

does the trick
(where shape and attr are defined elsewhere in the grammar.
e.g. shape = 'a' and attr = 'b'. Then 'a' 'ab' 'aaab' 'bbbab' will all match but 'b' 'bb' 'bbb..' etc will not)


text:
Q: Segmentation Error when using a shared library Im building a shared library on linux. the library ".so" was sucessfully created, but when I tried to link it to a test application (with an empty main) and run the executable I got a segmentation error : "Segmentation error (cure dumped)"
when I tried to debug it with gdb and check the backtrace I got this output:
Program received signal SIGSEGV, Segmentation fault.
0x0073d5df in std::_Rb_tree_decrement(std::_Rb_tree_node_base*) () from /usr/lib/libstdc++.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.12.1-4.i686 libgcc-4.4.5-2.fc13.i686 libstdc++-4.4.5-2.fc13.i686 zlib-1.2.3-23.fc12.i686

(gdb) backtrace

#0  0x0073d5df in std::_Rb_tree_decrement(std::_Rb_tree_node_base*) () from /usr/lib/libstdc++.so.6
#1  0x0012d70c in ?? () from /opt/cuda/lib/libcudart.so.3
#2  0x0012df0c in ?? () from /opt/cuda/lib/libcudart.so.3
#3  0x0012c88a in ?? () from /opt/cuda/lib/libcudart.so.3
#4  0x00121435 in __cudaRegisterFatBinary () from /opt/cuda/lib/libcudart.so.3
#5  0x005d7bfd in __sti____cudaRegisterAll_55_tmpxft_00000fe6_00000000_26_MonteCarloPaeo_SM10_cpp1_ii_3a8af011()
    () from libsharedCUFP.so
#6  0x005db40d in __do_global_ctors_aux () from libsharedCUFP.so
#7  0x005a8748 in _init () from libsharedCUFP.so
#8  0x008abd00 in _dl_init_internal () from /lib/ld-linux.so.2
#9  0x0089d88f in _dl_start_user () from /lib/ld-linux.so.2

Im not familiar with gdb debugging, and it's the first time Im trying to build a shared library on Linux, but it seems to me that it has something to do with the library dynamic linking.
If anyone had any idea about this error and could help me, I would be grateful.

A: It doesn't have anything to do with dynamic linking or shared libraries - one of the constructors in libsharedCUFP.so (I assume this is your shared library) is most probably passing an illegal address to a function in libcudart.so which crashes.
You simply need to debug your code.


text:
Q: Paypal integration - Relying Party Validation error: redirect_uri provided in the request does not Trying to get login with PayPal into prestashop, all seem to be done corectly accorting to installation guide but getting this error:

Relying Party Validation error: redirect_uri provided in the request
  does not match with the registered redirect_uri. Please check the
  request.

What is the problem?

A: There are two modes for any application on Paypal developers website (i.e. Live and Sandbox mode), please confirm that you are using the same API data that you have configured.

A: Yes, taking all data from live mode of the app.


text:
Q: NoClassDefFoundError on an interface, not a class I have an issue with NoClassDefFoundError. I am using interfaces, and no class definition should be available:
package code;
public interface Constants {...}

The class implementing this interface compiles without any errors, and a JAR file has been built, but at runtime it gives me an error.
import ...;
import code.*;
public class MultiDoc extends LanguageAnalyser implements Constants{}

Constants contains only a list of constants.
I read some posts pointing to CLASSPATH as a cause of this problem, but I have the code package in my CLASSPATH. If I didn't have it, it would produce a compilation error. So, the problem should be something else.
The runtime error is:
java.lang.NoClassDefFoundError: code/Constants

What's the solution?

A: Check the static initialization of this class. Look here: what is the difference between NoClassDefFoundError and ClassNotFoundException.
java.lang.NoClassDefFoundError: code/Constants  does not mean that the Constants  class is not in the CLASSPATH. In fact it is quite the opposite. It means that the class was found by the ClassLoader, however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader.

A: Note that there are two different exceptions that sound very similar:  ClassNotFoundException and NoClassDefFoundError.
The first exception occurs in the simple case that the JVM looks for "packageB.ClassA" and can't find it in the search path.  There are a few other cases, I suspect, but fairly rare.
The second exception occurs mostly when an appropriately-named class file is found, but for some reason it can't be used.  There are two primary reasons for this:

*

*The class is in, eg, "packageA/ClassA.class" but internally is named "packageB/ClassA" (or the package name was accidentally omitted in the source, or the class file is in the wrong directory, given its package name).

*While loading the class, there was some sort of error, usually an error initializing static storage.

A: From your question I see that the compiled Constants interface resides in a jar which is different from the jar/location of the implementing classes. So you should be able to execute your application like this:
java -cp /path-to-jar/JarContainingConstants.jar my.application.Main

(replace the names with your real names)
If you've added the other classes to another jar and then if you made that jar executable and then if you tried to run it with java -jar MyApplication.jar, then any the classpath defined outside the executed jar is ignored. But the above command shoud work with any jar (executable or not).

from comment
[alef@localhost ~]$ java -cp /../code-misc.jar /.../MultiDoc.jar
Exception in thread "main" java.lang.NoClassDefFoundError: /.../MultiDoc/MultiDoc/jar
Caused by: java.lang.ClassNotFoundException: .home.
  ... .MultiDocDateMathcer.jar
  at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
  ...
  at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: /.../MultiDoc/MultiDocr.jar.
Program will exit.

You call is definitely incorrect. Do it like this (UPDATE):
java -Dgate.home=/my/new/gate/home/directory -cp gate.jar;code-misc.jar;MultiDoc.jar gate.Main

A: If you have somedirectory/code in your classpath, then that's wrong. You always need the base directory in your classpath (in this case it would be somedirectory). Java itself will search those roots for a directory called code containing a file called Constants.class.

A: You might have it in your CLASSPATH when compiling but this does not guarantee that it is in the CLASSPATH when you run it. How do you run it?

A: Any Interface must declared inside class.
public class Calbacks {
    public interface IBaseFragmentInterface {
        void NotifyMainActivity();
    }
}

*I very long find resolution of this problem, but i find resolution independently by the method of scientific poking


text:
Q: Could anyone explain these two sentences to me? I don't really get what mindful and catching myself in a cycle mean I'd like to know what they mean by the sentences in bold.

How is work going on the new album, Notes on a Conditional Form?

MH: It's like half-way done. Sometimes we'll write a song and it has a really traditional form, and we'll go, "Oh, that's cool". A 'song-song' we call it. And then a lot of stuff is less linear, all over the place. But we just love the way it exists like that too. With this record at the moment, I'm constantly thinking, we're getting pretty big, can we really make a record like this? Can we really make a record that the only thing we thought about is, am I vibing on this?

GD: It's definitely just [about] getting better at our own craft. You're still just making whatever you want that makes you feel good. But there are a lot of moments where Matty just won't sit still in a chair and every morning you can hear [manager] Jamie on the other end of the phone trying to convince him that it is a good album and that it's not hopeless. It's the worst thing.

MH: What did we call it - Friday feelings? Where I sit everyone down and I go, "Right, guys. We're not going to make this record. It's not going to happen. I just can't do it. I'm off." I have a full-on nervous breakdown for about six months.

GD: To be honest, after about four or five Fridays, you're just mindful of what happened last Friday. I'm just like, "I'm not buying into this."

MH: At that point I just start going, "You know what? I think that I'm actually even catching myself in a cycle! Let's just make it!"

after about four or five Fridays, you're just mindful of what happened last Friday.
Does this sentence mean that after four or five weeks passed, they'd start thinking carefully about what they thought about the album being not good enough last Friday might be a wrong idea?
At that point I just start going, "You know what? I think that I'm actually even catching myself in a cycle!
I don't really get what catching myself in a cycle means. Does this mean that he doesn't really think it's a good album but he feels like he might be wrong about it?

A: after about four or five Fridays, you're just mindful of what happened last Friday.

*

*You are only really thinking about (or remembering, or focusing on) the events of the previous Friday.

"You know what? I think that I'm actually even catching myself in a cycle!

*

*caught in a repeating loop of events.  Might also be caught in a rut which means that you are not really progressing.


text:
Q: Excel Controls - Delete Combo Box Dynamically I've added a combo box to my worksheet dynamically, and I want to delete the combo box dynamically at the end of two events - specifically the combobox.LostFocus and combobox.KeyDown events.
It currently works for two scenarios:

*

*The use manually selects an item from the dropdown

*The user partially types in an item and auto-completes fills in the rest, then the user hits enter on the keyboard.

It does NOT work if the user types in the entire text for a select, and presses enter.  I get the message:

COMException was unhanded by user code: Unable to get the Name property of the OLEObject class

Visual Studio points to the line 'sheetVSTO.Controls.Remove(myBox);' in the myBox_LostFocus event handler as the source of the failure.
A user show be able to type the entire text into the combobox and press enter.  Any help would be appreciated.
Here is what I have (let me know if more detailed needed):
    private void AddComboBox(String[] list)
    {
        Excel.Worksheet sheet = Globals.ThisAddIn.Application.ActiveSheet;
        Microsoft.Office.Tools.Excel.Worksheet sheetVSTO = Globals.Factory.GetVstoObject(sheet);
        Excel.Range cell = Globals.ThisAddIn.Application.ActiveCell;
        Microsoft.Office.Tools.Excel.Controls.ComboBox myBox= new Microsoft.Office.Tools.Excel.Controls.ComboBox();
        myBox.Name = "button1";
        myBox.Items.AddRange(list);
        myBox.KeyDown += new KeyEventHandler(myBox_KeyDown);
        myBox.LostFocus += new EventHandler(myBox_LostFocus);
        myBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        myBox.AutoCompleteSource = AutoCompleteSource.ListItems;
        myBox.Focus();
        Microsoft.Office.Tools.Excel.ControlSite myBoxControl = sheetVSTO.Controls.AddControl(myBox, cell, boxName);
    }

    void myBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == System.Windows.Forms.Keys.Enter)
        {
            Microsoft.Office.Tools.Excel.Controls.ComboBox myBox = sender as Microsoft.Office.Tools.Excel.Controls.ComboBox;
            Excel.Worksheet sheet = Globals.ThisAddIn.Application.ActiveSheet;
            if (myBox.SelectedIndex > -1)
            {
                Microsoft.Office.Tools.Excel.Worksheet sheetVSTO = Globals.Factory.GetVstoObject(sheet);
                sheetVSTO.Controls.Remove(myBox);
            }
        }
    }
    void myBox_LostFocus(object sender, EventArgs e)
    {
        Microsoft.Office.Tools.Excel.Controls.ComboBox myBox = sender as Microsoft.Office.Tools.Excel.Controls.ComboBox;
        Excel.Worksheet sheet = Globals.ThisAddIn.Application.ActiveSheet;
        Microsoft.Office.Tools.Excel.Worksheet sheetVSTO = Globals.Factory.GetVstoObject(sheet);
        sheetVSTO.Controls.Remove(myBox);
    }

A: I found the answer!
I changed my 2 remove calls to this:
myBox.BeginInvoke(new MethodInvoker(delegate { sheetVSTO.Controls.Remove(myBox); }));


text:
Q: Make a bash script available without using ssh I have a simple bash script (myscript.sh).
mysqldump -u busql mydb mytable1 mytable2 mytable3 | mysql -u busql mydb2 && rsync --progress --stats -av --chown=mydomain.de:psacln /var/www/vhosts/mydomain.com/httpdocs/pictures/master/product/1/* /var/www/vhosts/mydomain.de/httpdocs/pictures/master/product/1/

So basically the script dumps 3 tables from db1 and insert them into db2, copy all pictures from mydomain.com to mydomain.de and change the user for all copied pictures from mydomain.com to mydomain.de.
Now I want to make this script (one-click) available for my colleagues without giving them ssh access to our server.
First thing I was thinking of, was to make this script through html/php available. But the problem here is that the script needs to be run as root in order to change the user/owner for the copied files. I would like run the script from/with mydomain.com user but open minded. And it seems like there is no safe solution to run this script from a php page as root.
Could I maybie give mydomain.com user the rights to change file-owners or what would you suggest to make this script available without ssh access?!
There are also other scripts with other file-owners coming in the future, that need to be easy available for my colleagues. So I thinking what could be here the best solution ...

A: chown is really a root only operation.  The usual way to change ownership is to allow the target user (mydomain.de) read access to the files and then copy the files as that user.  This doesn't require any root access to execute.
You can give access for one specific user to run one specific script as another named user using sudo by editing /etc/sudoers.
For example, for two users "bob" and "frank", bob can run "/home/bob/special_script.sh" as frank as long as frank has access to the script and this line is added to /etc/sudoers:
bob ALL=(frank) NOPASSWD: /home/bob/special_script.sh

bob would run:
sudo -u frank /home/bob/special_script.sh

I recommend that instead of rsync with --chown you create a script containing the rsync command and give sudo access to run it as mydomain.de, giving mydomain.de access to read  /var/www/vhosts/mydomain.com/httpdocs/pictures/master/product/1/


text:
Q: Coffeescript class extend more bloat than Backbone extend I am just beginning to learn Coffeescript and cannot find a definite answer to why I should use
class Model extends Backbone.Model
    urlRoot: '//some/url'

compiles to
Model = (function(_super) {
    __extends(Model, _super);

    function Model() {
        _ref = Model.__super__.constructor.apply(this, arguments);
        return _ref;
    }

    Model.prototype.urlRoot = '//some/url';

    return Model;

})(Backbone.Model);

as opposed to
Model = Backbone.Model.extend
    urlRoot: '//some/url'

compiles to
var Model = Backbone.Model.extend({
    urlRoot: '//some/url'
});

The main reason I am asking is because the former is used in nearly all examples I have looked at. However, it creates 'much' more bloat when compiled as opposed to the latter. I did read this question, but the answers seem to differ.

A: Since you're asking just about the bloat, let's have a look at some code.
JavaScript with Backbone.Model.extend
If you open up the Backbone source code, you'll see the extend function is the following:
var extend = function(protoProps, staticProps) {
    var parent = this;
    var child;

    if (protoProps && _.has(protoProps, 'constructor')) { // _.has comes from
      child = protoProps.constructor;                     // underscore, even
    } else {                                              // more 'bloat'
      child = function(){ return parent.apply(this, arguments); };
    }

    _.extend(child, parent, staticProps);                // more underscore

    var Surrogate = function(){ this.constructor = child; };
    Surrogate.prototype = parent.prototype;
    child.prototype = new Surrogate;

    if (protoProps) _.extend(child.prototype, protoProps);

    child.__super__ = parent.prototype;

    return child;
  };

What actually happens here:
When we call
var Model = Backbone.Model.extend({urlRoot: '//some/url' });

we get something like:
  // Create new constructor which calls the parent constructor
  var Model;
  if (({}).hasOwnProperty.call({urlRoot: '//some/url' }, 'constructor') {
      // this is false so...
  } else {
      Model = function(){ return Backbone.Model.apply(this, arguments); };
  }

  // Set up prototype chain
  var Surrogate = function(){ this.constructor = model; };
  Surrogate.prototype = Backbone.Model.prototype;
  Model.prototype = new Surrogate;

  // Add properties to the child prototype
  // Same as:
  // Model.prototype.urlRoot = '//some/url';
  _.extend(Model.prototype, { urlRoot: '//some/url' });

  // Set the magical __super__ property
  Model.__super__ = Backbone.Model.prototype;

CoffeeScript with extends
Compare that with the CoffeeScript code. You will see that when you use extends a magical function called __extends gets added to the start of your file, which (when formatted) looks like:
__extends = function(child, parent) {
    for (var key in parent) {
        if (__hasProp.call(parent, key))
            child[key] = parent[key];
    }

    function ctor() { this.constructor = child; }
    ctor.prototype = parent.prototype;
    child.prototype = new ctor();

    child.__super__ = parent.prototype;

    return child;
};

which is combined with the generated JS:
var Model = (function(_super) {
    __extends(Model, _super);

    function Model() {
        _ref = Model.__super__.constructor.apply(this, arguments);
        return _ref;
    }

    Model.prototype.urlRoot = '//some/url';

    return Model;

})(Backbone.Model);

What actually happens here:
When we call
Model extends Backbone.Model
    urlRoot: '//some/url'

we get something like:
// Create new constructor which calls the parent constructor
var Model = function () {
    return Model.__super__.constructor.apply(this, arguments);
}

// Copy static properties from Backbone.Model to Model
for (var key in Backbone.Model) {
    if (__hasProp.call(Backbone.Model, key))
        Model[key] = Backbone.Model[key];
}

// Set up prototype chain
function ctor() { this.constructor = Model; }
ctor.prototype = Backbone.Model.prototype;
Model.prototype = new ctor();

// Add properties to the child prototype
Model.prototype.urlRoot = '//some/url';

// Set the magical __super__ property
Model.__super__ = Backbone.Model.prototype;

What do we see?
They look pretty similar don't they?
CoffeeScript is just JavaScript. If you are already using Backbone and want to avoid adding in the __extends function in your generated source, then use Backbone.Model.extend. If you want to avoid adding in Backbone all together then extends does practically the same thing. The reason that so many examples don't use the latter is that Backbone is not required to use CoffeeScript - it just wouldn't make sense to have an example which relies on an external library.


text:
Q: Analyzing impact of baseline value on change score using lmm I'm using a big clinical data set with a the evolution of a continuous lab value over time being the dependent variable and I am interested in the impact of the baseline of this value on this evolution. I have come across some similar qustions in CrossValidated and have learned that baseline cannot be incorporated as a covariate (quite locgical). Instead, it is possible to analyze the correlations between random intercepts (which actually represent the baseline) and slopes to answer this question. In this case, at least as I understand it, the subjects are treated as random effetcs. However, I wonder whether it is also possible (and sensible) to incorporate the baseline value as a random effect (instead of or in addition to subject) and either change score or the measured values directy as dependent variable. Time would be one of the covariates.
Does that make any sense?

A: You seem to be on the right track and thinking of the right things. Regressing change scores on baseline is a very bad idea as you have already learned. For the same reasons and more, don't include baseline as a random effect. That doesn't make much sense at all. Also, change scores themselves are not a good way to analyse change, as the estimand in such a model is often not the estimand that you want. A much better approach is what you described in the first part of your question: the measurements are the dependent variable, along with time. Time should be centered, and you should fit random intercepts and slopes as you suggest.
For some background reading on this, see:
Senn, S., 2006. Change from baseline and analysis of covariance revisited. Statistics in medicine, 25(24), pp.4334-4344.
https://onlinelibrary.wiley.com/doi/abs/10.1002/sim.2682
Tennant, P.W., Arnold, K.F., Ellison, G.T. and Gilthorpe, M.S., 2019. Analyses of'change scores' do not estimate causal effects in observational data. arXiv preprint arXiv:1907.02764
https://arxiv.org/pdf/1907.02764.pdf
Tu, Y.K. and Gilthorpe, M.S., 2007. Revisiting the relation between change and initial value: a review and evaluation. Statistics in medicine, 26(2), pp.443-457.
https://onlinelibrary.wiley.com/doi/abs/10.1002/sim.2538

Edit to address the question of why time should be centered. This is related to the correlation $r$ between the random slopes and intercepts, and is explained in the paper by Tu & Gilthorpe above. Here is the relevant quote:

It should be noted that different parameterizations of Time will yield different results [43]. For instance, when Time is coded as 0 (initial) and 1 (post-treatment), testing the correlation between intercept and slope is equivalent to testing $r_{x−y, x}$ , because the intercept variance is the variance of x and the slope variance is the variance of x − y; when Time is centred, such as − 0:5 (initial) and 0.5 (post-treatment), testing the correlation between intercept and slope is equivalent to Oldham's method because the intercept variance is the variance of (x + y)=2 and the slope variance is the variance of x − y; when Time is coded as − 1 (initial) and 0 (post-treatment), testing the correlation between intercept and slope is equivalent to testing $r_{x−y, y}$ because the intercept variance is the variance of y and the slope variance is the variance of x − y. An advantage of multilevel modelling over other approaches is that this method can be applied to more than two measurement occasions; details can be found in our previous study [43].

Reference [43] from the paper is, if interested:
Blance A, Tu Y-K, Gilthorpe MS. A multilevel modelling solution to mathematical coupling. Statistical Methods in Medical Research 2005; 14:553–565.
Also, as mentioned in the comments, you intend to include time in an interaction with treatment. It is usually a good idea to centre time in that case because the main effect of treatment is conditional on time being zero, so if time is centred zero then become the mid point, and this usually helps with interpretation.


text:
Q: Jenkins and GitLab: How to setup SCM aware job which is not triggered by the hook? To give some context the question is about GitLab and Jenkins setup.
I know how to setup a web hook, I know how to setup a job to be triggered by the hook. The problem is that I need to have multiple jobs and only a single entry-point (parent job) trigger for them.
The downstream jobs at the same time need to be git repo aware so I have to set repo url for them. This causes them to be triggered independently by the hook and I don't want that as this means that they are triggered twice.
On the other hand if I don't configure repo url on a downstream job and the parent job triggers it, it fails as it is not able to do a checkout.
I may try to hack around with some 'execute shell' build step, I believe it's not a valid way to go. Has anybody a good tip how to solve that?
For the reference here is the GitLab Jenkins plugin documentation according to which:

Plugin will parse the GitLab payload and extract the branch for which
the commit is being pushed and changes made. It will then scan all Git
projects in Jenkins and start the build for those that:

*

*match url of the GitLab repo

*match the configured refspec pattern if any

*and match committed GitLab branch

I tried playing around with different settings, without a great result though.

A: For the project you want to get only local triggers, just enable Don't trigger a built on commit notification in the Additional behaviours of git plugin.
(https://github.com/elvanja/jenkins-gitlab-hook-plugin/issues/11#issuecomment-35385032, as you actually have discovered).
But a better solution could be to make your downstream jobs reference the repository locally cloned by main job (not sure if actually possible), so the plugin will never consider them for schedule a build, as the git url don't match.


text:
Q: What is versionCodeMajor? And what is the difference with versionCode? I just found that PackageInfo.versionCode is deprecated in Android Pie. They point you to use PackageInfo.getLongVersionCode() instead. The JavaDoc of this new method is:

Return versionCode and versionCodeMajor combined together as a single long value. The versionCodeMajor is placed in the upper 32 bits.

But what is versionCodeMajor? How must I use it? What's the difference between versionCodeMajor and the old versionCode?
The documentation of it say nearlly nothing:

Internal major version code. This is essentially additional high bits for the base version code; it has no other meaning than that higher numbers are more recent. This is not a version number generally shown to the user, that is usually supplied with R.attr.versionName.

A: Up to now, the only way I've found to set versionCodeMajor with Android Studio 3.2.1 is through AndroidManifest.xml and disabling InstantRun.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:versionCodeMajor="8" [...]

'cause setting it in build.gradle file you get
android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.xxx.myapplicationp"
        minSdkVersion 'P'
        targetSdkVersion 'P'
        versionCode 127
        //versionCodeMajor 8
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

Could not find method versionCodeMajor() for arguments

So, having set your chosen major version code number in AndroidManifest.xml and having disable InstantRun then you could get it in this way:
static long getAppVersionCode(Context context) throws PackageManager.NameNotFoundException {
        PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        long returnValue = Long.MAX_VALUE;
        //if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P
                && !"P".equals(Build.VERSION.CODENAME) /* This 'cause the dev preview */) {
            returnValue = pinfo.versionCode;
        } else {
            returnValue = pinfo.getLongVersionCode();
            Log.d("AAA", "Full long value: " + returnValue);
            Log.d("AAA", "Major Version Code (your chosen one) " + (returnValue >> 32)); // 8 in this scenario
            Log.d("AAA", "Version Code (your chosen one) " + (int)(returnValue & 0x00000000ffffffff)); // 127 in this scenario
        }
        return returnValue;
    }

or you could use PackageInfoCompat like that:
static long getAppVersionCode(Context context) throws PackageManager.NameNotFoundException {
        PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        long returnValue = Long.MAX_VALUE;
        returnValue = PackageInfoCompat.getLongVersionCode(pinfo);
        if (BuildConfig.DEBUG) {
            int majorCode = (int)(returnValue >> 32);
            int versionCode = (int)(returnValue & 0x00000000ffffffff); // or simply returnValue

            Log.d("AAA", "Full long value: " + returnValue);
            Log.d("AAA", "Major Version Code (your chosen one) " + majorCode); // 8 in this scenario
            Log.d("AAA", "Version Code (your chosen one) " + versionCode); // 127 in this scenario
        }
        return returnValue;
    }

And this should answer how to use it or a way to.
For when and why using it... I guess it's up to you... as, as you pointed out, the documentation tells you nothing on why you should use it. What doc says it's you should present to your users only the well known versionNumber.
I guess they add some more bits to versionCode 'cause they needed a greater number for their versioning ^^'
That said, if you dind't set the versionCodeMajor either in AndroidManifest.xml or in the build.gradle file (when it will handle it) or you set it to 0 then this value is identical to the old versionNumber deprecated field.

A: Another way to get version name and version code is by BuildConfig
BuildConfig.VERSION_CODE
BuildConfig.VERSION_NAME


text:
Q: Calculate integral with infinite? I have done some integration in the past, but came across the following question:

The question is simple, calculate the integral and give the final answer. I am really not sure what to do and how I fill in the infinite values. Could somebody give me some more insight in how to solve this question.

A: When integrating agains the delta function the result is evaluation at the origin. Thus $\int_{-\infty}^{\infty}\delta(t)f(t)dt = f(0)$ more generally $$\int_{-\infty}^{\infty}\delta(t-x)f(t)dt = \int_{-\infty}^{\infty} \delta(t) f(t+x) dt = f(x)$$


text:
Q: How to solve Java error "pool-1-thread-xxxx" java.lang.OutOfMemory I have searched the posts about this issue, but I did't see similar situation like mine.
My java console shows the error message "pool-1-thread-xxxx" java.lang.OutOfMemory as the picture bellow:

*

*Red Line: CPU usage

*Green line: Memory usage

I have increased the RAM from 6G to 10G, and set -Xms=8G -Xmx=8G -Xmn=3G in *.bat file before I start the program. I also keep watching performance monitor but the memory is always around 20%. I have no idea how could this happen. Any idea?
Here is my run.bat code.
@echo off
javapro @java -Xoptimize -Xms8G -Xmx8G -Xmn3G -Xss1024k -XX:+UseConcMarkSweepGC -cp javaPro.exe;
cls
run.bat

*

*OS: windows server 2012 R2

*Java version : jre1.8.0_171

*RAM: 10G

*CPU: 2.5 GHz Intel Xeon(R)(Hyper Threaded)

A: The error message java.lang.OutOfMemoryError: unable to create new native thread means that

the JVM is asking a new thread from the OS and the underlying OS
  cannot allocate a new thread anymore.

See OOM explanations and your specific case explained.
So you won't see high memory usage in the graph, because the heap size is not close to its limit.
You have to check your application code and inspect the thread pool usages there. It's hard to say anything without the source code, but there may be few suggestions:

*

*If you use CachedThreadPoolExecutor, then the submitted tasks may be not fast enough, so your app is unable to process all submitted tasks.

*You may use FixedThreadPoolExecutor with the maximum (Integer.MAX_VALUE) capacity, in such case you have to limit the pool capacity and its queue size. So the pool eats all available threads and OOM happens.

Generally, you should always control your thread pool configuration and be sure it won't hog all system resources.

A: think that I've found a possible reason / solution approach:
one can check for the soft-limit for processes with ulimit -a:
$ cat /proc/22666/limits | grep processes
Max processes             1024                 62265                processes

$ ulimit -a | grep processes
max user processes

in order to change these values:
$ ulimit -Su 2000

$ ulimit -a | grep processes
max user processes (-u) 2000

$ cat /proc/22666/limits | grep processes
Max processes 2000

one can also adjust the default configuration:

*

*modify the limits.conf file with the following:

*sudo nano /etc/security/limits.conf or look inside /etc/security/limit.d/.

*add the following for the user who runs java.
limits.conf
#<domain>        <type>  <item>    <value>

# adjust these values as needed:
someuser          soft    nofile    4096
someuser          hard    nofile    8192

then modify the common-session file with the following:
sudo nano /etc/pam.d/common-session

add the following line:
common-session
session required pam_limits.so

and restart java.

*

*also see the ThreadPoolExecutor ...

*and the ThreadPoolExecutor Configuration.

for a Windows 2012 Server, this would be about the same.

*

*see Pushing the Limits of Windows on the Tech Net Blog.


text: Q: Нужно чтобы бот вызвал функцию в определенное время каждый день, как это реализовать? Библиотека - pyTelegramBotAPI Может есть какой то декоратор или библиотека для таких целей, я пробовал реализовать через потоки но получилось плохо


text:
Q: Why do I get a blank screen with this code? I'm following Big nerd ranch's android book(Second edition). The below code is expected to show a list of model data generated from a CrimeLab class(100 crimes with title,date and solved checkbox each).A recyclerView is used within the CrimeListFragment to display the data. But on building & running the application, all I get is a blank white screen.
Here's the relevant code:
public class CrimeListActivity extends FragmentActivity {

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fragment_host);

    FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragment_container);
    if (fragment == null) {
        fragment = new CrimeListFragment();
        fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
    }
}}

CrimeListFragment.java
public class CrimeListFragment extends Fragment {

private RecyclerView mCrimeRecyclerView;

private CrimeAdapter mAdapter;

public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View view = inflater.inflate(R.layout.fragment_crime_list,container,false);
    mCrimeRecyclerView = (RecyclerView) view.findViewById(R.id.crime_recycler_view);
    mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    updateUI();
    return view;
}

private void updateUI(){
    CrimeLab crimeLab = CrimeLab.get(getActivity());
    List<Crime> crimes = crimeLab.getCrimes();
    mAdapter = new CrimeAdapter(crimes);
    mCrimeRecyclerView.setAdapter(mAdapter);

}

public class CrimeHolder extends RecyclerView.ViewHolder{

    public TextView mTitleTextView;
    private TextView mTitleTextView;
    private TextView mDateTextView;
    private CheckBox mSolvedCheckBox;
    private Crime mCrime;

    public CrimeHolder (View itemView){
        super(itemView);
      //  mTitleTextView = (TextView) itemView;
        mTitleTextView =(TextView) itemView.findViewById(R.id.list_item_crime_title_text_view);
        mDateTextView =(TextView) itemView.findViewById(R.id.list_item_crime_date_text_view);
        mSolvedCheckBox = (CheckBox) itemView.findViewById(R.id.list_item_crime_solved_check_box);
    }

    public void bindCrime(Crime crime){
        mCrime = crime ;
        mTitleTextView.setText(mCrime.getTitle());
        mDateTextView.setText(mCrime.getDate().toString());
        mSolvedCheckBox.setEnabled(mCrime.isSolved());
    }

}

public class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder>{
    private List<Crime> mCrimes;

    public CrimeAdapter(List<Crime> crimes){
        mCrimes = crimes;
    }

    @Override
    public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType){
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        View view = layoutInflater.inflate(R.layout.list_item_crime,parent,false);
        return new CrimeHolder(view) ;
    }

    @Override
    public void onBindViewHolder(CrimeHolder holder,int position){
        Crime crime = mCrimes.get(position);
        holder.bindCrime(crime);
    }

    @Override
    public int getItemCount(){
        return mCrimes.size();
    }
}

Just in case,CrimeLab.java :    (provides the model data)
public class CrimeLab {
private static CrimeLab sCrimeLab;
private List<Crime> mCrimes;

public static CrimeLab get(Context context){
    if (sCrimeLab==null){
        sCrimeLab = new CrimeLab(context); //Hence calling the private constructor that no other class can access
    }
    return  sCrimeLab;
}

private CrimeLab(Context context){
    mCrimes = new ArrayList<>();
    for (int i=0; i<100; i++){
        Crime crime = new Crime();
        crime.setTitle("Crime #"+i);
        crime.setSolved(i%2==0);
        mCrimes.add(crime);
    }
}

public List<Crime> getCrimes(){
    return mCrimes;
}

content_fragment_host.xml (this one is 'ed by activity_fragment_host.xml from which I did delete the default AppBarLayout & Toolbar code,if that helps)
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context="com.bignerdranch.android.crimeintent.CrimeListActivity"
tools:showIn="@layout/activity_fragment_host"
android:id="@+id/fragment_container">

</FrameLayout>

fragment_crime_list.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView     xmlns:android="http://schemas.android.com/apk/res/android"
                                    android:layout_width="match_parent"
                                    android:layout_height="match_parent"
                                    android:id="@+id/crime_recycler_view">

</android.support.v7.widget.RecyclerView>

list_item_crime.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            xmlns:tools="http://schemas.android.com/tools">

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/list_item_crime_solved_check_box"
    android:layout_alignParentRight="true"
    android:padding="4dp"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/list_item_crime_title_text_view"
    android:layout_toLeftOf="@+id/list_item_crime_solved_check_box"
    android:textStyle="bold"
    android:padding="4dp"
    tools:text="Title"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/list_item_crime_date_text_view"
    android:layout_toLeftOf="@+id/list_item_crime_solved_check_box"
    android:layout_below="@id/list_item_crime_title_text_view"
    android:padding="4dp"
    tools:text="Date"/>

</RelativeLayout>

A: it was just a typo. onCreateView was changed to OnCreateView in CrimeListFragment.java . But thanks, anyways, it was driving me crazy.

A: Everytime you use fragment and want to show it or replace with another, you need call commit() from FragmentManager. In your case would be fm.commit();
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
    fragment = new CrimeListFragment();
    fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
}
fm.commit();


text:
Q: Can I cap the monthly network transfer of a process? I'm looking for a way to monitor and/or cap the monthly network transfer of an Ubuntu Server 12.04 process. I'm running a Plex Media Server, and while my current ISP is very lax on my bandwidth usage, I'm afraid that may be changing soon and want to be prepared.
I've looked into both NTM (http://netramon.sourceforge.net/eng/index.html) and Trickle (http://manpages.ubuntu.com/manpages/precise/man1/trickle.1.html) but NTM appears to need a GUI to run and doesn't monitor on a per process basis and Trickle doesn't appear to allow total transfer caps, only upload/download speed limitations. All of the posts I've seen on Ask Ubuntu are related to these two applications.
Is anyone aware of an application that will let me set a total monthly transfer limit, or any other way I could work this out?

A: The 'tc' command should do what you want.
http://manpages.ubuntu.com/manpages/precise/man8/tc.8.html