text:
Q: Can't save the data in shelve module Python I want to create a python file that when user inputs a value, it will save to a dictionary and update the binary file created by shelve module.
The problem is that when I run the python file again, the dictionary is not updated.
There is no error code or anything and I don't know what to do.
import shelve
menubook = shelve.open('menu_data', writeback=True)

menubookA = {'main':'toast', 'sub':'egg', 'drink':'milk'}

print(menubookA)
print(menubookA['drink'])

key = input("Enter key: ")
value = input("Enter value: ")

menubookA[key] = value
print(menubookA) # When I check the dictionary here, it has been updated but when I run the program again, the value and key added are gone.

menubook.close()

I would appreciate if anyone could help me.

A: You obviously forgot to write the data back to the file:
import shelve

menubook = shelve.open("menu_data", writeback=True)

# Read data from the file
for key, value in menubook.items():
    print("Key: %s = %s" % (key, value))

menubookA = {"main": "toast", "sub": "egg", "drink": "milk"}

print(menubookA)
print(menubookA["drink"])

key = input("Enter key: ")
value = input("Enter value: ")

menubookA[key] = value
print(menubookA)  # When I check the dictionary here, it has been updated but when I run the program again, the value and key added are gone.

# Write data back to the file
menubook.update(menubookA)

menubook.close()


text:
Q: Let $x\in \mathbb{R}$. Suppose that for all $\varepsilon\in \mathbb{R}^{*}_{+}, x< \varepsilon$. Argue by contradiction to show that $x\leq 0$. I am new to Real Analysis.
Exercise: Let $x\in \mathbb{R}$. Suppose that for all $\varepsilon\in \mathbb{R}^{*}_{+}$, we have $x< \varepsilon$. Argue by contradiction to show that $x\leq 0$.
My attempt:
Assume that $x\geq 0$. We have that for all $\varepsilon>0$, then $x< \varepsilon$. Let $\varepsilon = {x}/{n}$, where $n\in \mathbb{N}$ and $n>1$. It is given that $x< \varepsilon$, so $x< \varepsilon$ $\Rightarrow$ $x< x/n$ $1<1/n$ which are false because we have $n>1$. Therefore, we have a contradiction so $x\leq 0$.
Do I miss something valid, or is this a sound proof.?

A: Let's say that $x=\delta>0$, so for $\epsilon = \delta / 2$, we should have $$\delta = x < \epsilon = \delta / 2$$
That was a contradiction.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Handling POST request with axios and express I can't seem to figure out why when I'm doing an axios.post method providing a body of data, it gets captured as undefined on my server.
I have the following files with snippets of code:
app.js:
auth(user, pass){
    return axios.post('http://localhost:3000/auth', {
        username: user,
        password: pass
    })
}

server.js:
app.post('/auth', (req, res) => {
    console.log(req.body) //undefined
    res.end("Success")
})

I'm how can I properly handle the POST data using axios?  Am I missing something?
The success returns fine, but the username / password cannot seem to be found anywhere in the req

A: Add following parser to handle the requested data
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())

A: Turns out I had all my middleware installed out of order; I was attempting to handle the POST in my server.js file prior to using any middleware.

A: I don't have enough reputation to comment on Jim's last post but I had the same problem and that solved it!
To clarify: In my server.js file I was requiring my routes before these:
these first:
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

then this:
app.use(routes);


text:
Q: Loading TreeView and XML control from XML in C# I've never worked with XML and TreeView or the XML control before, following some online tutorials I've cobbled together a working TreeView and XML control but I have several issues: 1) The TreeView is showing the actual name of the node in addition to the text, 2) The XML control is showing all of the pages at once when I want to show only one at a time, 3) How do I configure the TreeView to have the XML control change pages?
The XSLT stylesheet for the XML control:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" >
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

  <xsl:template match="/">
    <book>
      <xsl:for-each select="book/page">

            Previous Page
            |

              <xsl:value-of select="title" />

            |
            Next Page

            <xsl:value-of select="content"/>

            <xsl:value-of select="pgno" />

      </xsl:for-each>
    </book>
  </xsl:template>
</xsl:stylesheet>

The XSLT style sheet for the TreeView:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

  <xsl:template match="/book">
      <xsl:for-each select="book/page/title">
        <xsl:value-of select="title" />
      </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

The XML file:
<book time="" title="">
  <page time="">
    <title></title>
    <content>

    </content>
    <pgno></pgno>
  </page>
</book>

I'm loading the TreeView and XML control in the code behind like this:
Page_Load:
XmlDocument doc = new XmlDocument();
doc.Load(myXml);

tvBook.Nodes.Clear();

XmlNodeList nodelist =  doc.SelectNodes("book/page/title");
XmlDocument cDoc = new XmlDocument();
cDoc.LoadXml("<title></title>");
foreach (XmlNode node in nodelist)
{
    XmlNode newElem = cDoc.CreateNode(XmlNodeType.Element, node.Name, node.LocalName);
    newElem.InnerText = node.InnerText;
    cDoc.DocumentElement.AppendChild(newElem);
}

tvBook.Nodes.Add(new TreeNode(cDoc.DocumentElement.Name));
TreeNode tNode = new TreeNode();
tNode = tvBook.Nodes[0];

AddNode(cDoc.DocumentElement, tNode);
tvBook.ExpandAll();

xmlContent.DocumentSource = myXml;
xmlContent.TransformSource = myStyle;

Additional method:
private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
{
    XmlNode xNode;
    TreeNode tNode;
    XmlNodeList nodeList;
    int i;

    if (inXmlNode.HasChildNodes)
    {
        nodeList = inXmlNode.ChildNodes;
        for (i = 0; i < nodeList.Count; i++)
        {
            xNode = nodeList.Item(i);
            inTreeNode.ChildNodes.Add(new TreeNode(xNode.Name));
            tNode = inTreeNode.ChildNodes[i];
            AddNode(xNode, tNode);
        }
    }
    else
    {
        inTreeNode.Text = (inXmlNode.OuterXml).Trim();
    }
}

My output on the screen looks like this:
TreeView
title
    title
         First Page of My Book
    title
         Second Page of My Book

XML Control
   Previous Page             TITLE             Next Page

                            CONTENT

                                                  Page No

RESOLUTION UPDATE: Because of some additional issues that forced how I achieve my objective to change problems 2 and 3 no longer need to be solved. However, I am marking the below answer as correct because it did resolve problem 1 for me.

A: XDocument is XML Linq while XmlDocument is standard XML.
Try code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =
            "<book time=\"\" title=\"\">" +
              "<page time=\"\">" +
                "<title></title>" +
                "<content>" +

                "</content>" +
                "<pgno></pgno>" +
              "</page>" +
            "</book>";

            XDocument doc = XDocument.Parse(input);
            // or from a file
            //XDocument doc = XDocument.Load(filename);

            XElement title = doc.Descendants("title").FirstOrDefault();
        }

    }
}


text:
Q: Do We Know Which People are Moderators in Stack Exchange? I am just curious to know if there is a way for regular users to know who the moderators are in their community of interest (let's say, Stack Overflow).
Can the moderators be accessed? (maybe via chat feature of Stack Exchange?)

A: You will see a diamond(♦) after their username on their profile page and in
chatrooms showing they are moderators.
The link https://stackexchange.com/about/moderators lists all moderators across the network with additional information.


text:
Q: Rails DB Seeding For some reason, the food_id field in 'ratings' isn't populating when I run the seed.rb file below.  Can somebody help me figure out why?
Seed file contains the following lines:
Food.create(:id => 1, :description => 'Stonyfield Farm Yomommy 4oz. Strawberry')
OverallRating.create(:score => 0, :count => 1, :food_id => 1)

Code for Food and Rating are as follows:
    class OverallRating < Rating
      belongs_to :food
    end
class Food < ActiveRecord::Base
   has_one :overall_rating
end

class Rating < ActiveRecord::Base
  belongs_to :food
end

The rating migration file is as follows:
class CreateRatings < ActiveRecord::Migration
  def self.up
    create_table :ratings do |t|
      t.integer :food_id
      t.integer :count
      t.decimal :score
      t.string :type
      t.timestamps
    end
  end

  def self.down
    drop_table :ratings
  end
end

A: how are you invoking the seeds.rb file? You may have to do a rake db:seed

A: Is that really the actual code?  I would guess you've got an attr_accessible or attr_protected declaration in Rating/OverallRating that is preventing the option from being set in the instantiated object.

A: Instead of hardcoding the id, try something like this:
food = Food.create(:description => 'blah')
food.create_overall_rating(:score => 0, :count => 1)

I just tried your exact method though, and it worked for me without a problem. So perhaps you have something else awry.


text:
Q: Is there a way to enable/disable searching on a datatable by an specific event? I'm trying to disable the seaching field on a datatable when an specific radio button is selected.
I'using icheck plugin
I was thinking of using the blur even or this
My html

        <input type="radio" name="buscar_por" class="flat-red" id="rbn_buscar_codigo">
        Código

        <input type="radio" name="buscar_por" class="flat-red" id="rbn_buscar_linea">
        Línea

        <input type="radio" name="buscar_por" class="flat-red" id="rbn_buscar_seccion">
        Sección

        <input type="radio" name="buscar_por" class="flat-red" id="rbn_buscar_descripcion">
        Descripción

        <input type="radio" name="buscar_por" class="flat-red" id="rbn_buscar_todos">
        Todos

My Js
$('#rbn_buscar_codigo').on('ifChecked', function (event) {
    $('#postTable').DataTable({
        'searching': false,
        'language': {
            'url': '../plugins/dataTables.spanish.lang'
        }
    })
})

In the documentation there's a way to destroy the datatable .destroy() but i dont know how to create it again when that radiobutton is uncheck and another is selected

A: I did this, not the best solution but it's suppoused that they will get diferent data for the diferent urls
$(document).ready(function () {
  var tablaBusqueda = $('#postTable').DataTable({
    'searching': false,
    'language': {
      'url': '../plugins/dataTables.spanish.lang'
    }
  })
  $('#rbn_buscar_codigo').on('ifChecked', function (event) {

    tablaBusqueda.destroy()
    alert('tabla codigo')
    tablaBusqueda = $('#postTable').DataTable({
      'searching': false,
      'language': {
        'url': '../plugins/dataTables.spanish.lang'
      }
    })
  })
  $('#rbn_buscar_descripcion').on('ifChecked', function (event) {
    tablaBusqueda.destroy()
    alert('tabla descripcion')
    tablaBusqueda = $('#postTable').DataTable({

      'language': {
        'url': '../plugins/dataTables.spanish.lang'
      }
    })
  })
  $('#rbn_buscar_linea').on('ifChecked', function (event) {
    tablaBusqueda.destroy()
    alert('tabla linea')
    tablaBusqueda = $('#postTable').DataTable({

      'language': {
        'url': '../plugins/dataTables.spanish.lang'
      }
    })
  })
  $('#rbn_buscar_seccion').on('ifChecked', function (event) {
    tablaBusqueda.destroy()
    alert('tabla seccion')
    tablaBusqueda = $('#postTable').DataTable({

      'language': {
        'url': '../plugins/dataTables.spanish.lang'
      }
    })
  })
  $('#rbn_buscar_todos').on('ifChecked', function (event) {
    tablaBusqueda.destroy()
    alert('tabla todos')
    tablaBusqueda = $('#postTable').DataTable({

      'language': {
        'url': '../plugins/dataTables.spanish.lang'
      }
    })
  })

})

A: Searching div id is example_filter. Just simply hide the div using jquery when the radio button is checked.


text:
Q: sheaves on a scheme I work within the framework of Demazure & Gabriel`s book. (My schemes are all functors). Let $X$ be a scheme. I can define an underlying topological space $|X$| of $X$. Its points are equivalence classes of field valued generalised points $\text{Spec }K\to X$, and its topology is induced by the open subfunctors of $X$. As for any topological space I get a topos of sheaves $\text{Sh}(|X|)$. Let $\text{Aff}$ be the opposite of the category of rings equipped with the Zariski Grothendieck topology. Every scheme is a sheaf on $\text{Aff}$.
What is the relationship between the comma category $\text{Sh}(\text{Aff})/X$ and the category $\text{Sh}(|X|)$?
It seems like every object $F\to X$ of the slice category gives me an object of $\text{Sh}(|X|)$ by letting its set on the open subfunctor $U$ be the set of sections of $U\to F$. Is there a construction in the other direction? Is it an equivalence?

A: I think that there does not exist a good description of the relationship in the generality you state it. It also seems like this question is not well-posed (with regards to your actual interests) based off your comments. That said, there is one nice thing you can say in the context of torsors which, given you are interested in vector bundles/reading a book on group schemes, might be of interest to you.
In general if you have a continuous functor $\nu\colon \mathcal{D}\to\mathcal{C}$ such that $\nu^{-1}$ is exact (i.e. that $\nu$ induces a morphism of sites $\mathcal{C}\to\mathcal{D}$) then you obtain a morphism of topoi
$$\mathbf{Sh}(\mathcal{C})\substack{\xrightarrow{\nu_\ast}\\ \xleftarrow{\nu^{-1}}}\mathbf{Sh}(\mathcal{D})$$
(sorry for the bad TeX). Suppose that you start with a group sheaf $\mathcal{G}$ on $\mathcal{C}$, then one has the following:

Theorem([1, Chapitre V, Proposition 3.1.1]): There is a pair of quasi-inverse functors
$$\mathbf{Tors}_\mathcal{G}(\mathcal{C})'\substack{\xrightarrow{\nu_\ast}\\ \xleftarrow{\nu^{-1}}}\mathbf{Tors}_{\nu_\ast(\mathcal{G})}(\mathcal{D})$$
where $\mathbf{Tors}_\mathcal{G}(\mathcal{C})'$ is the full subcategory of $\mathbf{Tors}_\mathcal{G}(\mathcal{C})$ consisting of those $\mathcal{G}$-torsors $\mathcal{F}$ such that $\nu_\ast(\mathcal{F})$ is locally non-empty.

If you apply this with $\nu\colon X_{\mathrm{zar}}\to X_{\mathrm{Zar}}$ (the inclusion of the small Zariski site into the large Zariski site), then it's easy to check that $\nu_\ast(\mathcal{F})=\mathcal{F}|_{X_\mathrm{zar}}$ and so we can just write this as $\mathcal{F}$. As it's clear that in this case
$\mathbf{Tors}_\mathcal{G}(X_\mathrm{Zar})'$ is the entirety of $\mathbf{Tors}_\mathcal{G}(X_{\mathrm{Zar}})$, the above theorem says that we get equivalences of categories
$$\mathbf{Tors}_\mathcal{G}(X_\mathrm{Zar})\substack{\xrightarrow{\nu_\ast}\\ \xleftarrow{\nu^{-1}}}\mathbf{Tors}_{\nu_\ast(\mathcal{G})}(X_\mathrm{zar})$$
for any group sheaf $\mathcal{G}$ on $X_\mathrm{Zar}$.
Of course, here this is not that surprising/interesting, but it becomes much more so when you apply it to other less trivial cases (e.g. the inclusion of the small Zariski site into the big fpqc site).
References:
[1] Giraud, J., 2020. Cohomologie non abélienne (Vol. 179). Springer Nature.


text:
Q: calling vb dll in python So I have a function in vb that is converted to a dll that I want to use in python. However trying to use it, I get an error message
 this is the VB function
Function DISPLAYNAME(Name)
MsgBox ("Hello " & Name & "!")
End Function

and this is how I call it in python
from ctypes import *
test = windll.TestDLL
print test
print test.DISPLAYNAME("one")

But I get errors so what is the right way of calling the dll
Traceback (most recent call last):
  File "C:\Test\testdll.py", line 4, in <module>
    print test.DISPLAYNAME("one")
  File "C:\Python26\lib\ctypes\__init__.py", line 366, in __getattr__
    func = self.__getitem__(name)
  File "C:\Python26\lib\ctypes\__init__.py", line 371, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'DISPLAYNAME' not found

I have been looking around online but no solution so far. Can't use cdll since this is for c progs.
I have looked at some of the python and dll related questions but no solution so far works for my issue.

A: I dunno the answer to your specific question, but if it's VB.NET, you can natively call it in IronPython.

A: It might be a scoping issue, with out the Public access modifier, the function may not be visible to external callers. Try
Public Function DISPLAYNAME(Name)
MsgBox ("Hello " & Name & "!")
End Function

in your dll


text:
Q: Basic I/O text replacing I'm using the following program to read in a huge search engine database dump on search queries (>100 MB) and delete unneeded table data so that I'm left with just the keyword, so that I can mine the data for trends for one of my classes.
Here's what I have so far:
import java.io.*;
public class FileUtil {

    public static void main(String args[]) {

        try {

            FileInputStream fStream = new FileInputStream("\\searches.txt");
            BufferedReader in = new BufferedReader(new InputStreamReader(fStream));
            //PrintStream out = new PrintStream(new FileOutputStream("searchesEdited.txt"));

            while (in.ready()) {
                System.out.println(in.readLine());
                String keyword = "foo"; // selected keyword to delete in txt file
                //search for string
                //delete the string
                //write newly edited file to searchesEdited.txt

            }
            in.close();

        } catch (IOException e) {
            System.out.println("File input error");
        }

    }
}

This works as expected and outputs all the data to the console, so I'm in the right direction. Now I just need to replace/delete the passed keyword. I have looked into the replaceAll() method but can't seem to get it implemented correctly. Any help would be greatly appreciated.

A: Try,
String line=in.readLine();
 String keyword = "foo";
 String newLine=line.replaceAll(keyword,"");

Or
 String keyword ="\\bfoo\\b"; //word boundary match
 String newLine=line.replaceAll(keyword,"");

A: You could just use String.replace() with an empty String for the replacement, e.g.
 "search for a keyword and delete this keyword".replace("keyword", "")

returns
 "search for a  and delete this"

See also here for a simple tutorial on how to read and write text files.


text:
Q: php how to get __DIR__ of child class I have two classes in separate folders
class Parent
{
    public $path = null;

    function  __construct()
    {
        $this->path = __DIR__;
    }
}

and
class Child extends Parent
{

}

So when I create an instance of Child:
$child = new Child();
echo $child->path

I get a path to Parent. What I actually want is to get path to Child. I cannot modify Child class.
Is it possible?

A: You can get use reflection to get what you're looking for:
$child = new Child();
$class_info = new ReflectionClass($child);
echo dirname($class_info->getFileName());


text:
Q: Columna desconocida al tratar de insertar con EF Actualmente tengo dos funciones  una de tipo GET que es donde hago la siguiente consulta:
[HttpGet]
[Route("GetProd")]
public IEnumerable<Producto> GetProd()
{

    List<Producto> productos = myDbContext.producto.FromSqlRaw("select tbl_producto.*, GROUP_CONCAT(tbl_archivo.url SEPARATOR ',') as urls,tbl_archivo.url from tbl_producto inner join tbl_archivo on tbl_producto.idProducto=tbl_archivo.idProducto group by tbl_producto.idProducto;").ToList();

    return productos;

}

Esa consulta me obtiene los registros agrupados y en especifico 2 columnas con url y urls, estas columnas no estan en mi tabla de base de datos pero si en mi clase de Producto.
public class Producto
{
    public int idProducto { get; set; }

    public string nombre { get; set; }

    public string descripcion { get; set; }

    public string codigo { get; set; }
    public float? inventario { get; set; }

    public float precioProv { get; set; }

    public float precioPublico { get; set; }
    public float? precioPiso { get; set; }

    public DateTime fecha { get; set; }

    public bool Estatus { get; set; }

    public int idTipo { get; set; }
    [NotMapped]
    public string? tipo { get; set; }
    public int idMarca { get; set; }
    [NotMapped]
    public string? marca { get; set; }
    public int idSubMarca { get; set; }
    [NotMapped]
    public string? subMarca { get; set; }
    public int idTipoVolumen { get; set; }
    [NotMapped]
    public string? tipoVolumen { get; set; }
    public int idCaracteristica { get; set; }
    [NotMapped]
    public string? caracteristica { get; set; }
    public int idPropiedad { get; set; }
    [NotMapped]
    public string? propiedad { get; set; }
    public int idPresentacion { get; set; }
    [NotMapped]
    public string? presentacion { get; set; }

    public string? url { get; set; }

    public string? urls { get; set; }

}

El problema que tengo es en esta siguiente linea.
                await myDbContext.producto.AddAsync(
                    new Producto
                    {
                        fecha=DateTime.Now,
                        codigo=producto.codigo,
                        nombre=producto.nombre,
                        descripcion=producto.descripcion,
                        inventario=producto.inventario,
                        precioProv=producto.precioProv,
                        precioPublico=producto.precioPublico,
                        precioPiso=producto.precioPiso,
                        idTipo=producto.idTipo,
                        idSubMarca=producto.idSubMarca,
                        idMarca=producto.idMarca,
                        idTipoVolumen=producto.idTipoVolumen,
                        idCaracteristica=producto.idCaracteristica,
                        idPropiedad=producto.idPropiedad,
                        idPresentacion=producto.idPresentacion,
                        Estatus=producto.Estatus
                    }
                    );
                int cve = myDbContext.SaveChanges(); - aqui marca el error

Yo intente poner el atributo [NotMapped] en las dos columnas de las url pero si hago eso cuando hago la consulta en el get no me obtiene esas dos columnas y quiero saber como puedo combinar la posibilidad de insertar mas la posibilidad de obtener.


text:
Q: What is the "energy associated with torque?" I'm told that when a magnetic dipole is placed in a magnetic field $\vec{B}$, it experiences a torque $\vec{\tau} = \vec\mu \times \vec{B}$ and  an associated energy $ H = -\vec{\mu} \cdot \vec{B} $, where $\vec{\mu}$ is the magnetic dipole moment, pointing in the same direction as how the dipole is oriented in space.
I thought at first the associated energy might be the total amount of work you'd have to do to spin the dipole from equilibrium to whatever orientation you care about, but this doesn't agree with the math. If $\vec{\mu}$ points in the same direction as $\vec{B}$, you get a non zero value. What on earth does this associated energy actually mean?

A: You're mostly correct, except for the expectation that the minimum energy orientation is used for zero potential energy.  Instead, the zero point is when the spin and field are perpendicular.
This suggests (correctly) that it will take energy to remove a dipole from a magnetic field after they have become parallel, as the potential energy in a zero-strength magnetic field is greater than the potential energy when it is aligned in a magnetic field.
This should be no odder than using the general gravitational potential energy equation, where the potential energy of a system of masses is negative.


text:
Q: Bootstrapper design pattern using Caliburn.Micro MVVM framework with IoC-container The WPF application uses Caliburn.Micro as MVVM framework. CM has it's built in IoC-Container named SimpleContainer, I replaced it with Castle.Windsor container. (But container type does not matter here I guess.) CM uses a Bootstrapper.Configure() method where container can be configured. After that Bootstrapper.OnStartup() method starts application displaying a View for root ViewModel. So container configures before first View appears. In my case container configuration a pretty complex and may cause errors. For example I want to deserialize some XML files from app directory to objects and register them as components in container. So I want to get a SplashScreen to see container configuring progress, and then if all OK, splash disappears, container resolves root item and application starts as expected. If not - problem shown on splashscreen. I can't get in mind how to get a SplashScreenView (binded to SplashScreenViewModel) before I get a configured container. So application divides on "before" and "after" container. How can that issue can be solved? Is there any patterns? Is it OK to partly configure container in Configure and partly somewhere else, after it Resolved some components? Or maybe there is a practic to use container instance "inside" components  resolved by another container instance? Thanks.
public class CastleModernUIBootstrapper : BootstrapperBase
    {
        private WindsorContainer _container;
        public CastleModernUIBootstrapper()
        {
            Initialize();
        }
        protected override void Configure()
        {
            _container = new WindsorContainer();
            // here components are registered.
            // I want perform complex container configuration here,
            // but I can't vizualize what happens here.
            _container.Register(Component.For<LoadingSplashScreenViewModel>());
            // ...
        }
        // ...
        protected override void OnStartup(object sender, StartupEventArgs e)
        {
            // after we resolving first element from container
            DisplayRootViewFor<LoadingSplashScreenViewModel>();
        }
    }

A: WPF has a built-in (as in I don't know how it works) Splash Screen. Just use "Add new item" on your project. It does work with Caliburn.
It's only a simple bitmap, but it takes care of the appearance. You can handle your errors as normal data.
You don't want your Splash window to be the Root View anyway.


text:
Q: What are the similarities and differences between Java Annotations and C# Attributes? I have a Java library I'm considering porting to C#.  The Java library makes extensive use of annotations (at both build time and run time.)
I've never used C# attributes, but understand that they are the rough equivalent of Java annotations.
If I proceed with the port using attributes to replace annotations, what do I need to know?  What's going to be the same?  Different?  What's going to bite me?

A: Control over when your metadata is made accessible is different between the two languages.
Java provides the java.lang.annotation.Retention annotation and java.lang.annotation.RetentionPolicy enum to control when annotation metadata is accessible.  The choices vary from Runtime (most common - annotation metadata retained in class files), to Source (metadata discarded by compiler).  You tag your custom annotation interface with this - for example:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.CLASS)
public @interface TraceLogging {
  // etc
}

would allow you to reflect on your custom TraceLogging annotation at runtime.
C# uses the ConditionalAttribute attribute that is driven from compile time symbols.  So the analogous example in C# is:
[Conditional("TRACE")]
public class TraceLoggingAttribute : Attribute
{
  // etc
}

which would cause the compiler to spit out the metadata for your custom TraceLogging attribute only if the TRACE symbol was defined.
NB. attribute metadata is available at runtime by default in C# - this is only needed if you want to change that.

A: Following up to what Jon said...
Both Java 5 and Java 6 allow metaprogramming. Java 5 uses a separate apt tool; Java 6 integrates it into the compiler. (Though the Java 5 apt is still available in Java 6)
Unfortunately each uses a different API.
I'm currently using the Java 5 API for my Bean annotations
See http://code.google.com/p/javadude/wiki/Annotations for an example
(NOTE: I'm currently making some major updates, some of which change the API.)
Very cool stuff...
-- Scott

A: One important aspect of Java annotations which I haven't looked at in detail yet: you can write code which uses annotations within javac (as of Java 6, I believe) as a form of metaprogramming.
PostSharp allows something similar, admittedly.
(That's far from the only difference, but it's all I have time for right now.)

A: One interesting difference is that C# allows module and assembly level attributes.  These are applied to your module or assembly and are available via reflection in the normal way.  Java does not provide reflection on a jar file, so jar level annotations are not possible.
In fact this is quite common as Visual Studio a file called AssemblyInfo.cs at the root project level which contains, for example:
[assembly: AssemblyVersionAttribute("1.2.3.4")]
[assembly: AssemblyTitleAttribute("My project name blah blah")]
...

There is no equivalent jar level annotation in Java (although since jdk5, there is a little used package level annotation mechanism - thanks to mmeyers for pointing that one out)


text:
Q: A limit of indeterminate $$\lim _{x\to \infty }\frac{\left(e^x+x\right)^{n+1}-e^{\left(n+1\right)x}}{xe^{nx}}\:= \:\:?$$
I tried to get it to a simpler form like this:
$$\lim _{x\to \infty }\frac{\left(e^x+x\right)^{n+1}-e^{\left(n+1\right)x}}{xe^{nx}}\:=\:\lim _{x\to \infty }\frac{e^{\left(n+1\right)x}\left(1+\frac{x}{e^x}\right)^{n+1}-e^{\left(n+1\right)x}}{xe^{nx}}=\lim _{x\to \infty }\frac{e^x}{x}\left(\left(1+\frac{x}{e^x}\right)^{n+1}-1\right)$$
Then i noted $\frac{e^x}{x}$ with t which tends to infinity also. Then i applyed the formula for $a^n-b^n$ (I've considered $1$ as $1^\left(n+1\right)$) and i got 1, but the answer is $n+1$. What have i missed ?

A:
$$\begin{align}\lim_{x\to \infty}\frac{e^x}{x}((1+\frac{x}{e^x})^{n+1} - 1) &= \lim_{t\to \infty}t((1+\frac{1}{t})^{n+1}-1) \\&= \lim_{t\to \infty}t(1+\frac{n+1}{t}-1 + o(\frac{1}{t}))\\&=n+1\end{align}$$

A: Use binomial expansion on the numerator :
$$\left(e^x+x\right)^{n+1}-e^{(n+1)x} = \sum_{k=0}^n \binom{k}{n+1} e^{kx}x^{n+1-k}$$
Now the dominant term here is the term of number $k=n$, so
$$\frac{\left(e^x+x\right)^{n+1}-e^{(n+1)x}}{xe^{nx}} \sim \frac{(n+1)xe^{nx}}{xe^{nx}}=n+1$$
An alternative method, starting with your factorization, is to use $(1+u)^\alpha-1\sim \alpha u$, so :
$$\frac{e^x}{x}\left(\left(1+\frac{x}{e^x}\right)^{n+1}-1\right) \sim \frac{e^x}{x}.(n+1)\frac{x}{e^x}$$
which gives the same result.

A: First multiply numerator and denominator by e,
We get $\dfrac{e(1+\frac{x}{e^x})^{n+1}-1}{x}. $
=  $$\dfrac{e*\left(e^{\frac{x}{e^x}(n+1)}-1\right)}{x}. $$ ( as $1^\infty$ form)
Applying L' hopital's rule and simplifying,we get
= $$ \dfrac{e(e^{\frac{x}{e^x}(n+1)})*(n+1)*(1-x)}{e^x}
= $$e(e^{\frac{x}{e^x}(n+1)-1})(n+1)$$
$$~e * e^{-1} * (n+1) = n+1$$


text:
Q: How can I get an OID for a certificate template? I'm using C# (or VBScript) to issue a certificate from an Enterprise CA.
According to this answer, I need to specify the OID instead of the certificate name, and place it in an unexpected portion of code.  (IMHO I should place it where the null string is)
I'm looking at certificate manager, templates, et.al, and can't locate the OID I should be using.  Have any suggestions?

A: Certificate Templates are stored in the Configuration partition of Active Directory.
For instance, if your Certificate Template is named "Smartcard," then its DN would be:
CN=Smartcard,CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=Contoso,DC=Com

The msPKI-Cert-Template-OID attribute of that object contains the OID  you seek.
Edit: Here's some Powershell:
PS C:\Users\Ryan> Get-ADObject 'CN=Smartcard,CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=Contoso,DC=Com' -Properties msPKI-Cert-Template-OID

DistinguishedName       : CN=Smartcard,CN=Certificate Templates,CN=Public Key
                          Services,CN=Services,CN=Configuration,DC=Contoso,DC=Com
msPKI-Cert-Template-OID : 1.3.6.1.4.1.311.21.8.13882702.11110958.1330334.1890290.2281445.541.2.14
Name                    : Smartcard
ObjectClass             : pKICertificateTemplate
ObjectGUID              : 1cd4698d-56fe-4d4b-8005-f89a76d24ae1

A: I had trouble with finding the distinguished name for a certificate template, so I found a different way than the other answers by following these steps:

*

*Open MMC and add the Certificate Templates snap-in (File > Add/Remove Snap-ins > Certificate Templates - you may need to run as administrator to have this snap-in available)

*Right Click the certificate template you want the OID of

*Open Properties

*Open Extensions tab

*Select Certificate Template Information

*The OID will be visible in the description below after "Object identifier"

A: I think you may need this entire string for your domain OID.
    Get-ADObject ('CN=OID,CN=Public Key Services,CN=Services,'+(Get-ADRootDSE).configurationNamingContext) -Properties msPKI-Cert-Template-OID | Select-Object -ExpandProperty msPKI-Cert-Template-OID


text:
Q: METADATA parameters disappear after AJAX action in template i'm defining a parameter
<f:metadata >
    <f:viewParam name="pageKey" value="#{parameterProvider.pageKey}" />
</f:metadata>

All works fine except AJAX requests with makes this param disappear?
example ajax button in xhtml page:
Message value from server= [#{lockerBean.msg}]

<h:form>
       <h:commandButton value="Ajax Action" styleClass="systemButton" >
           <f:ajax  execute="@all" render="@all" listener="#{lockerBean.ajaxButton(event)}"/>
       </h:commandButton>

</h:form>

ajax action is simply
public void ajaxButton(ActionEvent event){
        msg="Ajax reload";
    }

After ajax request pageKey is gone. If i set required="true" i get valudation error
j_idt3: Validation Error: Value is required. with clearly indicates, that parameter has been deleted. how can i preserve it?
I know about includeViewParams, but i don't understand this mechanism very well and it is not easy to add to all kinds of buttons and links... can i somehow force it to be passed or can i inject them somewhere in context?
EDIT:
this log might help to understand what is happening:
ParameterProvider, is sessionscoped CGI that holds pageKey. I modified getter & setter, so they log info about being called. In whole aplication getters and setters to this value is used only when applying request value in jsf lifecycle (my own code uses different methods)
14:04:06,400 OFF   [ParameterProvider] (default task-12) Getting pageKey[-1] into viewParams.
14:04:06,401 OFF   [ParameterProvider] (default task-12) Setting pageKey[2] from viewParams.
14:04:06,401 OFF   [MultiActionLockListener] (default task-12) AJAX ACTION
14:04:06,414 OFF   [ParameterProvider] (default task-12) Getting pageKey[3] into viewParams.

as you can see, before anything we have calling getter and setter for key (2 has been send from client 3 suppose to be sent to client in response)
calling another action will cause to log:
14:08:54,281 OFF   [MultiActionLockListener] (default task-14) AJAX ACTION
14:08:54,294 OFF   [ParameterProvider] (default task-14) Getting pageKey[7] into viewParams.

as you see, there is no getter and setter, which means pageKey is gone?


text:
Q: Bit.dev - components - How do you compile scss files on bit build, so bit exports with compiled css Bit dev - components - How do you compile scss files on bit build, so we bit export with compiled css.
Currently we are building and exporting our bit components. On the npm install of a component, the dist output is still in scss rather than css. Meaning when we bit build the scss is not being complied into css. Any ideas on how to implement the compilation of scss step into workspace.json? (webpack is not setup, using pnpm and bit commands only)


text:
Q: Пропал счётчик FB говорят в FB что-то поменялось
с недавних пор, даже в базовом конструкторе (share-кнопок Yandex) не отображается счётчик FB, и не резервируется место под его отображение
и на сайте, куда встроен код счётчика, тоже пропал счётчик
https://iocs.hse.ru/announcements/236638175.html
Yandex-поддержка игнорирует сообщения об этом, как будто это само собой разумеющееся поведение и счётчика нет и не было…
вот на сайте самой платформы:
https://tech.yandex.ru/share/
раздел счётчики

в чём может быть проблема?

A: В доках есть упоминание проблем с FB

Вы используете устаревший блок «Поделиться». Обновите его до актуальной версии.

Но, задавшись вопросом, почему же тогда в демке на сайте яндекса не отображается счетчик, я нажал на него, и заветная единичка появилась:

Статьей из вашего примера я тоже поделился:


text:
Q: How to access Google Play Games Gamer ID Recently google added the concept of a Gamer ID to Google Play Games services which allows a player to setup a gaming identity distinct from their google+ identity. http://officialandroid.blogspot.co.uk/2016/02/embrace-your-inner-gaming-hero-with.html
My use case is that I have an online multiplayer game which uses my own matchmaking server. I don't use Google Play Game's matchmaking because I require skill-based matchmaking capabilities that are not currently available using GPGS.
I'd like to be able to display the player's Google Play Games identity (just the name) if they happen to have signed in. However, I had previously elected not to for privacy reasons as I know that in Quick Matches with GPGS, google elects to conceal your opponent's identities, and I felt I should follow their lead.
Now, I think that part of the reason that gamer IDs have been added is to avoid the need for such caution over privacy. So I have the following questions:

*

*Is there any way to programmatically get the Google Play Game Gamer ID of the local player?

*Is there a way to be sure that what I have got is a Gamer ID, and not the old-style google+ identity which carries extra privacy issues?

*Am I right in assuming that privacy over the new Gamer IDs is more relaxed and that google and my users will not be concerned about having gamer IDs shared when playing against random opponents on the internet?

A: You can get some more information from http://android-developers.blogspot.com/2016/01/play-games-permissions-are-changing-in.html
Quick answers to your questions:

*

*You can programmatically get the local player's ID, name and avatar
as usual using  Games.getCurrentPlayerId() or
Games.getCurrentPlayer() then using Player.getDisplayName().

*You can verify the player's identity on the server side using www.googleapis.com/games/v1/applications/<app_id>/verify/ with a
token obtained as described in the blog post.  The updated
permissions are rolling out now, so I'd expect it to be everywhere
very soon.

*Yes, the new gamer identity is independent of Google+ for exactly this reason.  So you can safely use the gamer identity without risking the privacy of the player.


text:
Q: Flask app working on dev server but facing issues when deployed on httpd with mod_wsgi I got an assignment on one of the Python training that I attended. I built a simple app for one of my projects using flask 1.0/python3.6. My application need to achieve the following:

*

*Call an API from an internal application at college.

*Run a database query on Oracle db and display data on the webpage.

I wrote a bunch of functions in the backend (python) to achieve this and am using ajax to call these functions. Everything is running good in flask dev server. Now i need to move this to production server and I am using mod_wsgi along with httpd to achieve this. After some struggle I am get my application running on the production server, however my python code is failing with 500 error while running both functions.
jquery.min.js:4 POST http://server.com/flaskprod/requestbots 500 (INTERNAL SERVER ERROR)

POST http://server.com/flaskprod/home 500 (INTERNAL SERVER ERROR)

I checked the apache httpd error_log and I see the following errors.
Errors when calling API:
  [Mon Jul 02 13:48:41.302510 2018] [wsgi:error] [pid 18202] [remote 1.1.1.1:1212]   File "/var/www/flask-prod/flaskprod.py", line 230, in createCM
[Mon Jul 02 13:48:41.302513 2018] [wsgi:error] [pid 18202] [remote 1.1.1.1:1212]     r = requests.post(URL, auth=creds, data=json.dumps(DATAS), proxies=proxies, headers=headers)
[Mon Jul 02 13:48:41.302515 2018] [wsgi:error] [pid 18202] [remote 1.1.1.1:1212]   File "/usr/local/lib/python3.6/site-packages/requests/api.py", line 112, in post
[Mon Jul 02 13:48:41.302517 2018] [wsgi:error] [pid 18202] [remote 1.1.1.1:1212]     return request('post', url, data=data, json=json, **kwargs)
[Mon Jul 02 13:48:41.302519 2018] [wsgi:error] [pid 18202] [remote 1.1.1.1:1212]   File "/usr/local/lib/python3.6/site-packages/requests/api.py", line 58, in request
[Mon Jul 02 13:48:41.302522 2018] [wsgi:error] [pid 18202] [remote 1.1.1.1:1212]     return session.request(method=method, url=url, **kwargs)
[Mon Jul 02 13:48:41.302524 2018] [wsgi:error] [pid 18202] [remote 1.1.1.1:1212]   File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 508, in request
[Mon Jul 02 13:48:41.302526 2018] [wsgi:error] [pid 18202] [remote 1.1.1.1:1212]     resp = self.send(prep, **send_kwargs)
[Mon Jul 02 13:48:41.302528 2018] [wsgi:error] [pid 18202] [remote 1.1.1.1:1212]   File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 618, in send
[Mon Jul 02 13:48:41.302530 2018] [wsgi:error] [pid 18202] [remote 1.1.1.1:1212]     r = adapter.send(request, **kwargs)
[Mon Jul 02 13:48:41.302532 2018] [wsgi:error] [pid 18202] [remote 1.1.1.1:1212]   File "/usr/local/lib/python3.6/site-packages/requests/adapters.py", line 502, in send
[Mon Jul 02 13:48:41.302539 2018] [wsgi:error] [pid 18202] [remote 1.1.1.1:1212]     raise ProxyError(e, request=request)
[Mon Jul 02 13:48:41.302546 2018] [wsgi:error] [pid 18202] [remote 1.1.1.1:1212] requests.exceptions.ProxyError: HTTPSConnectionPool(host='exampleee.com', port=443): Max retries exceeded with url: /api/now/change/change_req (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fac76d37eb8>: Failed to establish a new connection: [Errno 13] Permission denied',)))

Errors when querying database:
    [Mon Jul 02 13:51:23.148685 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]   File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
[Mon Jul 02 13:51:23.148687 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]     response = self.full_dispatch_request()
[Mon Jul 02 13:51:23.148690 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]   File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
[Mon Jul 02 13:51:23.148693 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]     rv = self.handle_user_exception(e)
[Mon Jul 02 13:51:23.148695 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]   File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
[Mon Jul 02 13:51:23.148698 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]     reraise(exc_type, exc_value, tb)
[Mon Jul 02 13:51:23.148700 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]   File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
[Mon Jul 02 13:51:23.148702 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]     raise value
[Mon Jul 02 13:51:23.148705 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]   File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
[Mon Jul 02 13:51:23.148707 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]     rv = self.dispatch_request()
[Mon Jul 02 13:51:23.148709 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]   File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
[Mon Jul 02 13:51:23.148711 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]     return self.view_functions[rule.endpoint](**req.view_args)
[Mon Jul 02 13:51:23.148714 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]   File "/var/www/flask-prod/flaskprod.py", line 97, in get_cms_requested_for_approval
[Mon Jul 02 13:51:23.148716 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]     CMREQ = connect_bcc(queryCMREQ)
[Mon Jul 02 13:51:23.148718 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]   File "/var/www/flask-prod/flaskprod.py", line 86, in connect_bcc
[Mon Jul 02 13:51:23.148721 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]     connection = cx_Oracle.connect(bccConnectionString)
[Mon Jul 02 13:51:23.148725 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212] cx_Oracle.DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory". See https://oracle.github.io/odpi/doc/installation.html#linux for help
[Mon Jul 02 13:51:23.148750 2018] [wsgi:error] [pid 18200] [remote 1.1.1.1: 1212]

P.S Everything is running good in the flask dev server. No issues there. I am adding some more information below.
This is my config file:
WSGIPassAuthorization On

WSGIScriptAlias /flaskprod /var/www/flask-prod/flaskprod.wsgi

WSGIDaemonProcess flaskprod user=cld group=users processes=5 threads=5 maximum-requests=1000 umask=0007
WSGIProcessGroup flaskprod
WSGISocketPrefix /var/run/wsgi

<Directory /var/www/flask-prod/>
Order allow,deny
Allow from all
</Directory>

Snippet of my python code:
def connect_bcc(query):
    connectionString = 'bla bla'
    connection = cx_Oracle.connect(connectionString)
    cursor = connection.cursor()
    cursor.execute(query)
    return cursor.fetchall()
    cursor.close()
    connection.close()

 @app.route('/requestbots', methods=['GET','POST'])
 def get_cms_requested_for_approval():
    if request.method == "POST":
        queryCMREQFORAPPRVL = "SELECT * FROM....."
        CMREQ = connect_bcc(queryCMREQ)

        print (CM)
        return json.dumps({'CM': CM})

Snippet of js code:
function getResult() {
        $.ajax({
                type: "POST",
                url: $SCRIPT_ROOT + "/requestbots".....bla bla
         })
}

A: So, i figured it out. Yay for internet! I spent a while looking for answer to this question, so mentioning all details below.
Both issues were related to SELinux. If you're wondering what that is - Security-Enhanced Linux is a Linux kernel security module that provides a mechanism for supporting access control security policies.
In case, you run into a similar issue, check the SELinux boolean value for various booleans related to your web server:
getsebool -a | grep httpd

For me, below two parameters were off.
httpd_can_network_connect --> off
httpd_can_network_connect_db --> off

I turned them on using below command.
setsebool httpd_can_network_connect on -P

setsebool httpd_can_network_connect_db on -P

 (-P is used to make the change persisting)

That's it. Everything works like a charm now.


text:
Q: How to trigger hyperlink click even - react component In my react component I am trying to trigger a click on the hyperlink created in the below function:
  getUsers(e){
    e.preventDefault();
    const { userIds } = this.props;
    BatchRoleActions.getAllRoleUsers(userIds)
    .then((users) => {
      const link = document.createElement('a');
      link.setAttribute('id', 'csvLink');
      link.setAttribute('download', 'roles.csv');
      link.setAttribute('href', users);
      document.getElementById('csvLink').onClick();
    });

  }

When the function is run I get the below error :
Uncaught (in promise) TypeError: Cannot read property 'onClick' of null
How can I trigger click to start my download?
BatchRoleActions.getAllRoleUsers(userIds) returns an an array with data for export to a csv file.  encodeURI(data:text/csv;charset=utf-8,\uFEFF${data});
I am trying to find a solution for: ReactJs - How to complete onClick before download - href

A: Edit1: I misunderstood what the OP asked for, edited my answer now!
Edit2: More edits after reading OP's link
I've set up a sandbox to mock what you're trying to do; take a look at it here - https://codesandbox.io/s/18k6oppy2l
Pay attention to the Users.js file

*

*We'll put a visible button and an invisible <a> tag in the DOM

*When the user clicks on the Download User data button, the request to retrieve the users is made

*Once the request resolves to string representation of the users data, we call setState to set the user in the state

*In the setState callback, we then programatically "click" the invisible <a> tag to download the users.csv; this will trigger the download of the file


text:
Q: Find underlaying normal distribution of random vectors I am trying to solve a statistics-related real world problem with Python and am looking for inputs on my ideas: I have N random vectors from a m-dimensional normal distribution. I have no information about the means and the covariance matrix of the underlying distribution, in fact also that it is a normal distribution is only an assumption, a very plausible one though. I want to compute an approximation of the mean vector and covariance matrix of the distribution. The number of random vectors is in the order of magnitude of 100 to 300, the dimensionality of the normal distribution is somewhere between 2 and 5. The time for the calculation should ideally not exceed 1 minute on a standard home computer.
I am currently thinking about three approaches and am happy about all suggestions for other approaches or preferences between those three:

*

*Fitting: Make a multi dimensional histogram of all random vectors and fit a multi dimensional normal distribution to the histogram. Problem about that approach: The covariance matrix has many entries, this could possibly be a problem for the fitting process?

*Invert cumulative distribution function: Make a multi dimensional histogram as approximation of the density function of the random vectors. Then integrate this to get a multi dimensional cumulative distribution function. For one dimension, this is invertible and one could use the cum-dist function to distribute random numbers like in the original distribution. Problem: For the multi-dimensional case the cum-dist function is not invertible(?) and I don't know if this approach still works then?

*Bayesian: Use Bayesian Statistics with some normal distribution as prior and update for every observation. The result should always be again a normal distribution. Problem: I think this is computationally expensive? Also, I don't want the later updates have more impact on the resulting distribution than the earlier ones.
Also, maybe there is some library which has this task already implemented? I did not find exactly this in Numpy or Scipy, maybe someone has an idea where else to look?

A: If the simple estimates described in the section Parameter estimation of the wikipedia article on the multivariate normal distribution are sufficient for your needs, you can use numpy.mean to compute the mean and numpy.cov to compute the sample covariance matrix.


text:
Q: IE8 expected ']' in regular expression I'm getting error in regexp in IE8. Other browsers work ok, but on IE8 I'm getting error:
IE8 expected ']' in regular expression

in line:
src.replace(/\/([^]+)\//g, '/big/$1');

Any ideas how to solve it?
Thanks in advance
Here you can se the result:
http://regexr.com?38bil

A: It looks like you are using [^] to match every possible character. You can use [\s\S] instead. See What is meaning of [^] in Javascript regexps?.

A: You should use this regex:
\/([^\/]+)\/

You're using [^]+ which may not work with all regex engines as there should by a character following ^ (for negation) in character class.


text:
Q: WCF Direct Authentication using BasicHttpBinding I am trying to  test a simple scenario in my development machine wherein I have a service which is configured on basicHttpbinding. I am trying to use CustomUserNamePasswordValidator and have configured Security level as "TransportWithMessageCredential"
Now, when I test the service with a web client (both service and client on Asp.net development server), service completely ignores the validator and simply returns the data, although I am passing wrong credentials from my client.
Is it because I am using VS Development Server ?
Is use of SSL over HTTP manadatory when we use TransportWithMessageCredentials. Is there an alternative wherein I need not use Https ?

A: WCF does not support any configurations out of the box which would permit transmission of unsecured credentials.


text:
Q: Rotating verticies created by a geometry shader I am trying to generate a cube from 6 points (each point representing a side, then 2 extra values to say if its rotated to face on the x, or y axis, z axis doesn't need one because its like that by default). Problem comes in when I try to multiply the gl_Position value by a mat4 rotation matrix to make the sides of the cube rotated properly. It doesn't even glitch out, it just doesn't display the faces at all (it does when I dont have the matrices multiplying the values).
Heres my geometry shader:
layout(points) in;
layout(triangle_strip, max_vertices = 4) out;

in vec3 gFacePos[];

out vec2 texCoord;

mat4 xtrans = mat4( //rotate on the x axis
1.0, 0.0, 0.0, 0.0,
0.0, 0.0, -1.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0
);

mat4 ytrans = mat4( //rotate on y
0.0, 0.0, 1.0, 0.0,
0.0, 1.0, 0.0, 0.0,
-1.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0
);

mat4 rtrans = (gFacePos[0].x * xtrans) + (gFacePos[0].y * ytrans); //figure out what the current point wants to rotate on

void main() { //this whole thing makes a square at the requested point
    gl_Position = gl_in[0].gl_Position + vec4(-0.5, 0.5, 0.0, 0.0);
    gl_Position *= rtrans; //these break it
    texCoord = vec2(0.0, 0.0);
    EmitVertex();
    gl_Position = gl_in[0].gl_Position + vec4(0.5, 0.5, 0.0, 0.0);
    gl_Position *= rtrans;
    texCoord = vec2(1.0, 0.0);
    EmitVertex();
    gl_Position = gl_in[0].gl_Position + vec4(-0.5, -0.5, 0.0, 0.0);
    gl_Position *= rtrans;
    texCoord = vec2(0.0, 1.0);
    EmitVertex();
    gl_Position = gl_in[0].gl_Position + vec4(0.5, -0.5, 0.0, 0.0);
    gl_Position *= rtrans;
    texCoord = vec2(1.0, 1.0);
    EmitVertex();
    EndPrimitive();
}

Fragment and vertex are pretty standard (vertex has some basic camera stuff on it).


text:
Q: Update Interface dynamically I am working on an android application which can be controlled by other mobile via SMS. I am using PreferenceScreen as layout(settings part of the app). The layout is updated when onResume()is called.
When the command(SMS) is sent via other mobile, service running in the background snoops the incoming sms and change the settings saved in SharedPreferences. In order to see these changes, my Activity need to execute the code in onResume. If I go back to previous activity and come back I can see the changes.
I want to the changes to be displayed as soon the SharedPreferences is changed by running service. What should I do to make it happen?

A: Something like this:
public class MyActivity extends Activity implements OnSharedPreferenceChangeListener
{
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle state)
    {
      /* get shared preferences */
      SharedPreferences mySharedPreferences = getSharedPreferences(PREFS_NAME, 0);

      /* register listener for changes to the values within the shared preferences */
      mySharedPreferences.registerOnSharedPreferenceChangeListener(this);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
    {
      /* perform application processing */
      ...

      /* update layout */
      View myView = findViewById(id.my_view);

      /* invalidate the view causing it to be redrawn */
      myView.invalidate();
    }
}


text:
Q: Is something like "typedef int arrChoice[5];" a global variable? #include <stdio.h>
#include <conio.h>
typedef arrChoice[10] /*is this a global variable?*/
int main() {};

  getch();
  return 0;
}

its not done yet, but this is what i meant.

A: typedef is not a global variable, it's simply an alias for another type. I usually use them for function pointers when I'm passing those around because writing them out every time is annoying.
typedef int (*function)(int, int);
I also use them to define a structure, union, or enumeration as a type
typedef struct {
    int x;
    int y;
    int z;
} Point;

A: typedef declares the new type not variable.

A: This might help you. In the code you posted here, there is a error. There are no statements in side main function. getch and return statements should be inside main function. I feel your code should be like this.
#include <stdio.h>
typedef int  arrChoice; /* arrChoice is alias to int */
arrChoice a[10] ;/* array a is a global variable of integers*/
int main()
{
 getch();
 return 0;
}

please note that the purpose of typedef is to assign alternative names to existing types(int,float,double,etc.).  The following statements are similar.
typedef arrChoice[10]  is similar to typedef int[10];

When you try to refer arrChoice, then you get an error message
expected expression before 'arrChoice'.


text:
Q: What does this notation mean for a squared matrix? A is a square matrix
$A^n = A \cdot A\cdot$...$n$ times
What's $A^{2n}$?
$2A^n$ or $A \cdot A\cdot$...$2n$ times?

A: It means $A\cdot A\cdot \dotsb$ $2n$ times, it's just a convenient way of making it clear that the power is even.


text:
Q: Proving that conservation of momentum doesn't apply to electron in H-atom To prove that the conservation of linear momentum doesn't apply to electron in H-atom, is it sufficient to show that angular momentum operator ($\hat L$) and momentum operator ($\hat p$) do not commute?

A: That would only show that you cannot find simultaneous eigenstates of Linear and angular momentum. You could use Ehrenfest's theorem and show that the time derivative of the average of momentum is not zero.

A: The ground state of the Hydrogen atom, $n=1, \ \ell = 0$, is an eigenstate of the angular momentum $\hat {\vec L}$ with eigenvalue zero. In this state we have
(1) $<n=1, \ \ell = 0| \hat {\vec L} \hat {\vec P} - \hat {\vec P} \hat {\vec L}|n=1, \ \ell = 0>$
$ \ \ \ \ = <n=1, \ \ell = 0|0 \dot \ \hat {\vec P} - \hat {\vec P} \dot \ 0| n=1, \ \ell = 0> = 0$.
These equalities show that in this state commutativity or non-commutativity of $\hat {\vec P}$ with the angular momentum operator has no meaning because of the eigenvalue zero of $\hat {\vec L}$.
So, I calculated the mean value of the linear momentum operator $\hat P = i \hbar \nabla$ for the ground state of the Hydrogen atom, and I obtained
(2) $< \hat P > \ = \ 0$.
However,
(3) $< \hat {P^2} > \ = \ \frac {\hbar ^2}{a_0^2}$,
where $a_0$ is the Bohr radius, (see the question How did we come to know that electrons actually move in an atom?).
Thus, by eq. (3) a linear movement exists in this state, but it is not a constant of motion, eq. (2).


text:
Q: jQuery: Swapping divs containing embedded video I have a page with a grid of thumbnails. Some thumbs open an image, some open an embedded video, all open into a Bootstrap3 modal. To try and "kill" a video that is still playing after a modal is dismissed / hidden I have been trying a few jquery functions (empty, remove) which work just fine, until I have to re-open or open another modal, so now I'm doing a little bit of swapping divs around with replaceWith which also works exactly as intended with photos and with youtube embeds, but not with Instagram video embeds. I can only get 1 successful IG video load per page refresh. Any subsequent calls to an IG embed doesn't seem to make a connection to IG. Here is a sample of where I am currently at:
CLICK ME (0)
CLICK ME (1)

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Here it was it looks like as it happens:
1) You can see the empty div #inner before any modals are activated:

2) #inner is replaced by #newDiv0 which now has the embed code in it (this displays properly):

3) Once modal is dismissed, #inner is recreated and replaces #newDiv0 as the modal is hidden:

4) Just like in step2, #inner is again replaced but now with #newDiv1 (which is also an IG video embed), however this time the iframe is missing and the network tab shows no connection to Instagram:

Can anyone explain why this doesn't work and maybe suggest a workaround? Thank you for reading, I know this is a lengthy post.

A: I was able to get that plnkr to work. A few things.

*

*Include the embed script only once in the body.

< script src="https://platform.instagram.com/en_US/embeds.js">

*Add the window.instgrm call below as the last line in your switch function.
 $('#myModal').modal('show');  // show the modal
 window.instgrm.Embeds.process();

*Remove the embed.js script from all of your embed items.

*Optionally add OMITSCRIPT=true to your embed links (so the embed.js does not load for each item).


text:
Q: How to use set methods with Input vatiables having defaults value as well? In a component I have two input variables
@Input() public data: User[] = []
@Input() public type: UserType = 'A1';

If the value of above variables change I need to call a function for this I have used below method
ngOnChanges(changes: SimpleChanges) {
     if (changes.type && changes.data) {
      this.userList = this.userService.getAllUsersList(changes.type.currentValue, changes.data.currentValue);
     }
  }

But I need to change this I need to use Setters function instead of ngOnChanges. Below is my approaches but I am getting error. I have commented direct declaration
 //@Input() public data: User[] = [] not using this type declaration
   // @Input() public type: UserType = 'A1'; not using this type declaration

 @Input() set  type(value: UserType) {

 }

 @Input() set  data(value: User[] ) {

 }

Issues I am getting
1) Not able to define variable type like public when I am doing this I am getting error
 @Input() set public type(value: UserType) {

 }

2) Not able to set default value
3) Confused how to call getAllUsersList

A: private type: UserType = 'A1';
@Input('type') set setType(type: UserType) {
   this.type = type;
   this.userList();
}

private data: User[] = [];
@Input('data') set setData(data: User[] ) {
   this.data = data;
   this.userList();
}

private userList() {
   if (this.data && this.user.length) {
      this.userService.getAllUsersList(changes.type.currentValue, changes.data.currentValue);
   }
}

ngAfterViewInit() {
   // If there is no input value, then setter is never called.
   // So we have to call it.
   this.userList();
}

A: Create a class with the properties you need for the component:
class myOptions{
  data: User[] = [];
  type: UserType = 'A1';
}

in your TypeScript code use:
@Input() public options: myOptions

and use it in your HTML code as a single parameter:
<my-component ... [options]="myOptions" />

That replacement of a simple parameter to a class will allow you to make any settlers you want (and run any code you need) on any property by simply replacing field to a property, like this:
class myOptions{
  myValuesHaveChange: Function;
  private _data: User[] = [];
  get data(): User[] { return this._data;};
  set data(value: User[]): void {
        this._data = value;
        this.myValuesHaveChange(value)};
  type: UserType = 'A1';
}

A: install property-watch-decorator from npm.
npm i property-watch-decorator

Then use @OnChange decorator before @input
export class TestComponent {

   @OnChange(TestComponent.prototype.userList)
   @Input() type: UserType = 'A1'

   @OnChange(TestComponent.prototype.userList)
   @Input data: User[] = [];

   private userList() {
      if (this.data && this.user.length) {
         this.userService.getAllUsersList(changes.type.currentValue, changes.data.currentValue);
      }
   }

   ngAfterViewInit() {
      // To handle default values.
      this.userList();
   }
}

A: I tried in this way please suggest is this is correct approach. As I don't want to add other variables
public type: UserType = 'A1';
  @Input('type') set  SetType(value: UserType) {
    this.type = value;
    this.userList = this.userService.getAllUsersList(value, this.data);
  }

  @Input() public data: User[] = [];
  @Input('data') set  setData(value: User[]) {
      this.data = value;
      this.userList = this.userService.getAllUsersList(this.type, value);
  }


text:
Q: How to get array from a closure object in php I have an object which yields the following when var_dump()ed
object(Closure)#78 (3) {
  ["static"]=>
     array(3) {
        ...
     }
}

Is there a means by which i can retrieve the array labeled static?
I have tried the following:
ReflectionClass::getProperty('static');//returns property static does not exit

ReflectionClass::getStaticPropertyValue('static');//Class Closure does not have a property named static

ReflectionClass::getProperties();// returns an empty array

ReflectionClass::getStaticProperties();//returns an empty array

$obj->static;//Closure object cannot have properties

get_obj_vars($obj);//returns an empty array

(array)$obj;//wraps $obj in an array, but does not CONVERT to an array

json_decode(json_encode($obj));//returns object(stdClass)#79 (0) {}

Thanks.

A: The static property you see here is an implementation detail of the \Closure class and solely internal to PHP. The class captures the used variables in this property.
You cannot access this property and the only thing you can do with a \Closure object is calling it or passing it around.
Via reflection you can only access the scope using ReflectionFunctionAbstract::getClosureScopeClass and ReflectionFunctionAbstract::getClosureThis respectively.

A:
private static function getRegistrar($callable)
    {
        if(is_callable($callable))
        {
            if(is_a($callable,'Closure'))
            {
                preg_match_all('/\[this\] => (.+) Object/', print_r($callable,true), $matches);
                if(count($matches)>1)
                    return $matches[1];
            }
            else if (is_array($callable) && count($callable)>0 && is_a($callable[0],'Object'))
            {
                return gettype($callable[0]);
            }

        }
    }


text:
Q: How to get data from JavaScript to Angular2+ component? I am using current Angular 7. I am using recorderjs to record audio. My set up is like this.
In Angular Component:
Step 1: Import Main.JS
import {mainmodule} from '../../shared/scripts/recorderjs/main.js';

Step 2: Call record function of Main.Js from Angular Function.
mainmodule.toggleRecordingMethod(e); //inside angular component

this method will either start recording or will stop the recording.
Step 3: Main.js will use recorderjs to record audio.
// This will be called from angular component (Inside main.js).
main.prototype.toggleRecordingMethod = function toggleRecordingMethod(e) {
    enableRecordingVisualization = true;
    toggleRecording(e);
};

// inside main.js
function toggleRecording(e) {
    if (e.classList.contains("recording")) {
        // stop recording
        audioRecorder.stop();
        e.classList.remove("recording");
        e.classList.remove("pause");
        enableRecordingVisualization = false;
        audioRecorder.getBuffer(gotBuffers);
    } else {
        // start recording
        if (!audioRecorder) {
            initAudio();
        }

        e.classList.add("recording");
        audioRecorder.clear();
    }
}

Till step 3, i am successful. Now main.js which uses recorderjs to record audio is working and recording audio.
In main.js i have following function. it returns undefined in Angular. I have set up breakpoints and i found that javascript immediately retuns undefined rather than waiting for exportWAV to return audio.
main.prototype.saveRecordingMethod = function saveRecordingMethod() {
return audioRecorder.exportWAV(function(blob){return blob;});
};

exportWAV is function from recorderjs which accepts call back.I have passed callback which returns blob which is audio. How do i get audio blob rather than undefined?
I want to send this recorded audio in angular. How do i do that?


text:
Q: How can I add an image into a list in Unity C#? I'm attempting to index multiple folders of images into multiple lists. Currently, I'm trying to use System.IO's DirectoryInfo and FileInfo to do this, but my lists' types are Texture2D and so it cannot convert them. So how can I add these images to the lists?
Relevant code:
    using UnityEngine.UI;
    using System.IO;

    public List<Texture2D> daytimeImages = new List<Texture2D>();

    private void Start() {
        DirectoryInfo daytimeDirectory = new DirectoryInfo(daytimePath);
        FileInfo[] daytimePictures = nighttimeDirectory.GetFiles();
        foreach (FileInfo file in nighttimePictures)
        {
            daytimeImages.Add(file);
        }
    }

A: From one of the answers here
This function may help you, it converts image from file path to Texture2d using the LoadImage function:
public static Texture2D LoadImage(string filePath)
{
    Texture2D tex = null;
    byte[] fileData;

    if (File.Exists(filePath))     //you can skip this since you are only passing files that exist
    {
        fileData = File.ReadAllBytes(filePath);
        tex = new Texture2D(2, 2);
        tex.LoadImage(fileData);
    }
    return tex;
}

You can use it as follows (EDITED to add .FullName)
foreach (FileInfo file in nighttimePictures)
{
    daytimeImages.Add(LoadImage(file.FullName));  //edited
}


text:
Q: How to pick out classes that start with a particular string This might be hard to explain, but I need a way to loop through a bunch of elements I've already selected and for each one find classes that start with the word "icon". So for example I might have the following elements

So, I begin by selecting the elements and looping through them....
$(".button").each(function(){
    // Some code here

});

Now, I could put the following code in the loop...
if ($(this).hasClass("iconStar")){
    $(this).append("");

}

I would then have to repeat that for each possible icon, which seems very inefficient.
What I'd like to do in the "each" loop is just cycle through all the classes that $(this) has and pick out the one that begins with ICON and then use that to append the image.
Can anyone help?

A: I recommend against using classes if you're not going to associate the class with the image. (which would be the most correct way) What I would do instead is put a link to the image in the rel tag.
This does what you want, and will still validate as valid css.

iconStar

iconPlus

iconLeft

iconRight

iconUp

iconDown

See the example here: http://jsbin.com/acasu
Note, if you're using a lot of tiny images, you're going to want to use CSS Sprites. As it will greatly improve the performance of your page.
If you absolute had to do it the way you are suggesting, you could do the following:
$(".button[class^='button icon']").each(function() {
   var iconSrc = $(this).attr('class').substr("button icon".length)
   $(this).append("");
});

A: Try using this selector:
$(".button[class^='button icon']")

This should select only elements that have the class button, and also have a class that start with 'icon'.
Of course, this selector also assumes that your CSS class always begins with "button" first and not "icon".

A: For each element, get the value of the class attribute, split it by ' ', take the second part and call the image.
From the top of my head
$(".button[class^='button icon']").each(function (el) {
    classStr = el.className;
    classes = classStr.split(' ');
    image = 'images/' + classes[1] + '.jpg';
});

Not entirely sure of the syntax, bit rusty!


text:
Q: How to group and filter this array of hashes. Ruby I have this data:
@complete_transactions = [{"timestamp"=>"2018-01-18T02:57:34.959Z", "toAddress"=>"Alice", "amount"=>"50"},
 {"timestamp"=>"2018-01-18T02:57:35.016Z", "fromAddress"=>"Alice", "toAddress"=>"Bob", "amount"=>"12.5"},
 {"timestamp"=>"2018-01-18T16:53:16.747Z", "toAddress"=>"50", "amount"=>"50"},
 {"timestamp"=>"2018-01-18T16:53:27.572Z", "fromAddress"=>"50", "toAddress"=>"alice", "amount"=>"50"},
 {"timestamp"=>"2018-01-18T16:53:38.853Z", "fromAddress"=>"alice", "toAddress"=>"Alice", "amount"=>"50"},
 {"timestamp"=>"2018-01-23T23:35:03.792Z", "fromAddress"=>"Alice", "toAddress"=>"alice", "amount"=>"10"},
 {"timestamp"=>"2018-01-23T23:35:25.464Z", "fromAddress"=>"Alice", "toAddress"=>"Bob", "amount"=>"1"},
 {"timestamp"=>"2018-01-23T23:35:48.835Z", "fromAddress"=>"Alice", "toAddress"=>"Bob", "amount"=>"1"},
 {"timestamp"=>"2018-01-23T23:47:46.485Z", "fromAddress"=>"Alice", "toAddress"=>"Bob", "amount"=>"1"},
 {"timestamp"=>"2018-01-23T23:48:31.953Z", "fromAddress"=>"Alice", "toAddress"=>"Bobz", "amount"=>"1"},
 {"timestamp"=>"2018-01-24T18:11:04.444Z", "fromAddress"=>"Alice", "toAddress"=>"Bobz", "amount"=>"1"},
 {"timestamp"=>"2018-01-24T18:28:40.680Z", "fromAddress"=>"Alice", "toAddress"=>"bob", "amount"=>"3"},
 {"timestamp"=>"2018-01-24T18:36:53.179Z", "fromAddress"=>"Alice", "toAddress"=>"Sally", "amount"=>"3"},
 {"timestamp"=>"2018-01-24T18:39:14.926Z", "fromAddress"=>"Alice", "toAddress"=>"Sally", "amount"=>"3"},
 {"timestamp"=>"2018-01-24T18:39:40.937Z", "fromAddress"=>"Alice", "toAddress"=>"Sally", "amount"=>"3"},
 {"timestamp"=>"2018-01-24T18:40:11.686Z", "fromAddress"=>"Alice", "toAddress"=>"bob", "amount"=>"2"},
 {"timestamp"=>"2018-01-24T18:40:13.720Z", "fromAddress"=>"Alice", "toAddress"=>"bob", "amount"=>"2"},
 {"timestamp"=>"2018-01-24T18:41:32.832Z", "fromAddress"=>"Alice", "toAddress"=>"bob", "amount"=>"2"},
 {"timestamp"=>"2018-01-24T18:49:10.052Z", "fromAddress"=>"Alice", "toAddress"=>"bob", "amount"=>"2"},
 {"timestamp"=>"2018-01-24T18:49:11.729Z", "fromAddress"=>"Alice", "toAddress"=>"bob", "amount"=>"2"},
 {"timestamp"=>"2018-01-24T18:50:09.862Z", "fromAddress"=>"Alice", "toAddress"=>"bob", "amount"=>"2"},
 {"timestamp"=>"2018-01-24T19:14:46.326Z", "fromAddress"=>"Alice", "toAddress"=>"bob", "amount"=>"2"},
 {"timestamp"=>"2018-01-24T20:29:30.973Z", "fromAddress"=>"Alice", "toAddress"=>"Bob", "amount"=>"3"},
 {"timestamp"=>"2018-01-24T20:31:37.491Z", "fromAddress"=>"Alice", "toAddress"=>"bob", "amount"=>"2"},
 {"timestamp"=>"2018-01-24T20:35:06.693Z", "fromAddress"=>"Alice", "toAddress"=>"bob", "amount"=>"2"},
 {"timestamp"=>"2018-01-24T21:29:21.465Z", "fromAddress"=>"Alice", "toAddress"=>"bob", "amount"=>"2"},
 {"timestamp"=>"2018-01-24T21:29:27.637Z", "fromAddress"=>"Alice", "toAddress"=>"bozb", "amount"=>"2"},
 {"timestamp"=>"2018-01-26T19:04:56.197Z", "fromAddress"=>"Alice", "toAddress"=>"bob", "amount"=>"2"},
 {"timestamp"=>"2018-01-28T19:53:12.502Z", "toAddress"=>"1444", "amount"=>"50"},
 {"timestamp"=>"2018-01-28T19:53:21.318Z", "fromAddress"=>"1444", "toAddress"=>"0297bc77", "amount"=>"1"},
 {"timestamp"=>"2018-01-28T19:53:30.947Z", "fromAddress"=>"1444", "toAddress"=>"0297bc77", "amount"=>"1"},
 {"timestamp"=>"2018-01-28T19:54:11.119Z", "fromAddress"=>"1444", "toAddress"=>"0297bc77", "amount"=>"1"},
 {"timestamp"=>"2018-01-28T21:26:58.551Z", "fromAddress"=>"1444", "toAddress"=>"Alice", "amount"=>"1"},
 {"timestamp"=>"2018-01-28T21:28:13.499Z", "fromAddress"=>"1444", "toAddress"=>"Alice", "amount"=>"2"},
 {"timestamp"=>"2018-01-28T21:31:47.454Z", "fromAddress"=>"1444", "toAddress"=>"something else", "amount"=>"2"},
 {"timestamp"=>"2018-01-28T21:39:16.644Z", "fromAddress"=>"1444", "toAddress"=>"Alice", "amount"=>"3"},
 {"timestamp"=>"2018-01-28T21:39:41.527Z", "fromAddress"=>"1444", "toAddress"=>"Alice", "amount"=>"2"},

What I'd like is to group the data by the toAddress field and total the amounts.
I'd like something like this (notice timestamp is irrelevant):
[
   {
    'toAddress' => 'bob', amount: '20', fromAddress: ['Alice', '1444']
   },
   {
    'toAddress' => 'Sally', amount: '9', fromAddress: ['Alice'],
   },
   ...
]

Any suggestions on how to do this?
This results in a correct data I think... but feels gross:
 complete_transactions.group_by {|trans| trans['toAddress']}.map do |group, transactions|
  transactions.reduce do |h1, h2|
    h1.merge(h2) do |key, old, new|
      if key == 'amount'
        old.to_i + new.to_i
      elsif key == 'fromAddress'
        [old, new].flatten.uniq
      else
        old
      end
    end
  end
end

leads to the right outcome, but it feels gross. Is there a better way?
Here's a small sample of data and the desired outcome:
 transactions
=> [{"timestamp"=>"2018-01-23T23:48:31.953Z", "fromAddress"=>"Alice", "toAddress"=>"Bobz", "amount"=>"1"}, {"timestamp"=>"2018-01-24T18:11:04.444Z", "fromAddress"=>"Alice", "toAddress"=>"Bobz", "amount"=>"1"}, {"timestamp"=>"2018-01-24T18:11:04.444Z", "fromAddress"=>"Another", "toAddress"=>"Bobz", "amount"=>"1"}]

transactions.reduce do |h1, h2|
irb(main):007:1* h1.merge(h2) do |key, old, new|
irb(main):008:2*   if key == 'amount'
irb(main):009:3>      old.to_i + new.to_i
irb(main):010:3>   elsif key == 'fromAddress'
irb(main):011:3>      [old, new].flatten.uniq
irb(main):012:3>   else
irb(main):013:3*      old
irb(main):014:3>   end
irb(main):015:2>   end
irb(main):016:1> end
=> {"timestamp"=>"2018-01-23T23:48:31.953Z", "fromAddress"=>["Alice", "Another"], "toAddress"=>"Bobz", "amount"=>3}

A: I believe this is what you need here.
result = @complete_transactions
         .group_by{|hash| hash['toAddress']}
         .map do |key, value|
           {
             'toAddress' => key,
             'amount' => value.sum {|val| val['amount'].to_i},
             'fromAddress' => value.map {|val| val['fromAddress']}.uniq
           }
         end

p result

This is for Ruby versions after 2.4.0. For prior versions, calculate the sum of amounts  with this.
'amount' => value.map {|val| val['amount'].to_i}.inject(:+)

The following statement groups all the hashes by their 'toAddress' values.
.group_by{|hash| hash['toAddress']}

The followins statement iterates through each of the resulting hash and creates a new hash.
.map do |key, value|

In the following block, we create our desired hash by operating on the values of each hash.
{
  'toAddress' => key,
  'amount' => value.sum {|val| val['amount'].to_i},
  'fromAddress' => value.map {|val| val['fromAddress']}.uniq
}

For Ruby versions prior to 2.4.0, the code becomes.
{
  'toAddress' => key,
  'amount' => value.map {|val| val['amount'].to_i}.inject(:+),
  'fromAddress' => value.map {|val| val['fromAddress']}.uniq
}

Hope this helps.

A: I have written a method that provides what you are asking for but in addition I included something you didn't ask for: the contribution of each "fromAddress" to the total "amount" for each "toAddress". (I misread the question. ¯\_(ツ)_/¯)
Code
def doit(transactions)
  transactions.each_with_object(Hash.new(0)) do |g,h|
    a = [g["fromAddress"], g["toAddress"]]
    h.update(a => h[a] += g["amount"].to_f)
  end.
  group_by { |(_from, to), _amt| to }.
  map { |k,v| { toAddress: k, amount: v.map(&:last).sum.to_s,
                from_address: v.map { |(from, _to), amt| [from, amt.to_s] }.to_h } }
end

Example
Let's reduce the example to something more manageable. I've eliminated a number of elements (hashes) of @transactions and from each of the hashes that remain I've eliminated the key "timestamp" because it's not relevant to the question.
transactions = [
  { "toAddress"=>"Alice", "amount"=>"50" },
  { "fromAddress"=>"Alice", "toAddress"=>"Bob", "amount"=>"12.5" },
  { "toAddress"=>"50", "amount"=>"50" },
  { "fromAddress"=>"50", "toAddress"=>"Alice", "amount"=>"50" },
  { "fromAddress"=>"Alice", "toAddress"=>"Alice", "amount"=>"50" },
  { "fromAddress"=>"Alice", "toAddress"=>"Bob", "amount"=>"1" },
  { "fromAddress"=>"1444", "toAddress"=>"0297bc77", "amount"=>"1"},
  { "fromAddress"=>"1444", "toAddress"=>"0297bc77", "amount"=>"1"},
  { "fromAddress"=>"1444", "toAddress"=>"Alice", "amount"=>"1"},
  { "fromAddress"=>"1444", "toAddress"=>"Alice", "amount"=>"2"}
]

doit(transactions)
    #=> [
    #     {:toAddress=>"Alice", :amount=>"153.0",
    #      :from_address=>{nil=>"50.0", "50"=>"50.0", "Alice"=>"50.0", "1444"=>3.0}},
    #     {:toAddress=>"Bob", :amount=>"13.5",
    #      :from_address=>{"Alice"=>"13.5"}},
    #     {:toAddress=>"50", :amount=>"50.0",
    #      :from_address=>{nil=>"50.0"}},
    #     {:toAddress=>"0297bc77", :amount=>"2.0",
    #      :from_address=>{"1444"=>"2.0"}}
    #   ]

If you do not wish the return value to contain certain elements you will need to remove the corresponding hashes from transactions as the first step (e.g., transactions.reject { |h| .... }.each_with_object...).
Explanation
The steps are as follows.
h = @transactions.each_with_object(Hash.new(0)) do |g,h|
  a = [g["fromAddress"], g["toAddress"]]
  h.update(a => h[a] += g["amount"].to_f)
end
  #=> {[nil, "Alice"]=>50.0, ["Alice", "Bob"]=>13.5, [nil, "50"]=>50.0,
  #    ["50", "Alice"]=>50.0, ["Alice", "Alice"]=>50.0, ["1444", "0297bc77"]=>2.0,
  #    ["1444", "Alice"]=>3.0}
g = h.group_by { |(_from, to), _amt| to }
  #=> { "Alice"=>[[[nil, "Alice"], 50.0], [["50", "Alice"], 50.0],
  #              [["Alice", "Alice"], 50.0], [["1444", "Alice"], 3.0]],
  #     "Bob"=>[[["Alice", "Bob"], 13.5]], "50"=>[[[nil, "50"], 50.0]],
  #     "0297bc77"=>[[["1444", "0297bc77"], 2.0]]}
g.map do |k,v|
  { toAddress: k, amount: v.map(&:last).sum.to_s,
    from_address: v.map { |(from, _to), amt| [from, amt.to_s] }.to_h }
end
  #=> <return value shown in example>


text:
Q: Pandas Dataframe Mul on Multiindex I have a Dataframe with a multi index, df
               'A'     'B'
1/1/12  T1     100     200
1/2/12  T1     40       20
1/3/12  T2     50       40

I then have a lookup table, lookup_table
     A     B
T1   0.5   0.25
T2   2      4

cols=['A','B']

I wanted to multiply the dataframe by the lookup_table based on the second index match.
So far I have this; but not working
df[cols].reindex(df.index,level=1).mul(lookup_table[cols])

A: I think you can just do:
df.mul(lookup_table, level=1)

Output:
               A      B
1/1/12 T1   50.0   50.0
1/2/12 T1   20.0    5.0
1/3/12 T2  100.0  160.0


text:
Q: Need data from rails join table, has_many :through I have 3 tables - users, things, and follows. Users can follow things through the follows table, associating a user_id with a things_id. This would mean:
class User
  has_many :things, :through => :follows
end

class Thing
  has_many :users, :through => :follows
end

class Follow
  belongs_to :users
  belongs_to :things
end

So I can retrieve thing.users with no problem. My issue is if in the follows table, I have a column named "relation", so I can set a follower as an "admin", I want to have access to that relation. So in a loop I can do something like:
<% things.users.each do |user| %>
  <%= user.relation %>
<% end %>

Is there a way to include relation into the original user object? I have tried :select => "follows.relation", but it doesn't seem to join the attribute.

A: For people using rails 4, the usage of :order, :select, etc has been deprecated. Now you need to specify as follows:
has_many :users, -> { select 'users.*, follows.is_admin as is_follow_admin' }, :through => :follows

A: To do this you need to use a bit of SQL in the has_many. Something like this should hopefully work.
has_many :users, :through => :follows, :select => 'users.*, follows.is_admin as is_follow_admin'
Then in the loop you should have access to
user.is_follow_admin

A: You might be able to do something like:
<% things.follows.each do |follow| %>
  <%= follow.relation %>
  <%= follow.user %>
<% end %>


text:
Q: How to wildcard DNS records in Windows Server DNS to catch all records My friend creating a White-Label-Website and he asked me if they can wildcard all domain so the buyer only set their domain NS, point to their DNS server, and the DNS server return single IP for all request if non exists...
Since i had my own server and i happen to have Windows Server with DNS launched too, i tried several way, but non resolve...
I had a .(root) zone, i add a * folder and and new host too it... didn't worked...
I also create * and . zone recently and and add Empy host record to them with the IP address i want, that didn't worked too either...
What should i do?

A: I am afraid it is not working as you suppose to ...
There is nothing link "general catch all" record in DNS system. There is defined wildcard as "all the rest" or if you want catch all but it works just as a record (one level of domains) and it cannot be used for subdomain(s).
Let say you have domain example.com. Zone file contain following records :
$TTL 3H
@   IN SOA  @ admin.example.com. (
                    0   ; serial
                    1D  ; refresh
                    1H  ; retry
                    1W  ; expire
                    3H )    ; minimum
    IN NS   @
    IN A    127.0.0.1
    IN AAAA ::1
a   IN A 127.0.0.2
*   IN A 127.0.0.3

in case you will request DNS you will get these answers
example.com => 127.0.0.1
a.example.com => 127.0.0.2
b.example.com => 127.0.0.3
xyz.example.com => 127.0.0.3
www.b.example.com => NXDOMAIN (error Not Existing Domain)

The reason of the error (last example) is that subdomain doesn't exists. Wildcard cover <anything>.example.com but it is not cover any subdomain so it is not covering <anything>.<else>.example.com...
Your question expect catch all record over even more then one domain level so I am afraid there is no way how to achieve this goal :-(.


text:
Q: Neo4j Multiple Relationship combine I have created a Cypher file which creates hundreds of different types of Nodes all with unique Labels
Here is an example of each type I have created :
CREATE (G1034:Rooms{Name:"G1034"})
CREATE (GroupA:Groups{Name:"GroupA"})
CREATE (Donald:Lecturers{Name:"Donald"})
CREATE (Monday:Days{Name:"Monday"})
CREATE (Slot1:Times{Name:"9am-10Am"})
CREATE (FinalYearProject:Module{Name:"Final Year Project"})

what I was trying to do is create a Relationship between them like a timetable slot
 CREATE
 (Donald)-[:TEACHES]->(FinalYearProject)-[:To]->(GroupA)-[:IN]->(G1034)-[:AT]->(Slot1)-[:ON]->(Monday)

but it doesn't seem to be right syntax I have.I am new to Neo4j  and have searched the internet for a solution but most examples have like two nodes related at most.
does anyone know is there a way to create a relationship like this and if so is there a way to do this
any help greatly appreciated

A: You miss the concept of the "Lesson" or "Event"
If you want to create these relationships later, find your nodes first, then create the connecting relationship. There is a good discussion in the (free) "GraphDatabases" Book about those "Event"/"Message" nodes.
MATCH (G1034:Rooms{Name:"G1034"})
MATCH (GroupA:Groups{Name:"GroupA"})
MATCH (Donald:Lecturers{Name:"Donald"})
MATCH (Monday:Days{Name:"Monday"})
MATCH (Slot1:Times{Name:"9am-10Am"})
MATCH (FinalYearProject:Module{Name:"Final Year Project"})

CREATE (lesson:Lesson)

CREATE
 (Donald)-[:TEACHES]->(lesson),
 (lesson)-[:TO]->(GroupA),
 (lesson)-[:IN]->(G1034),
 (lesson)-[:AT]->(Slot1),
 (lesson)-[:ON]->(Monday)
 (lesson)-[:FOR]->(FinalYearProject)


text:
Q: Why does Jupiter return to cleaning toilets? In Jupiter Ascending, the main character starts out as a maid. Later, she

 Finds out she owns the earth

Shouldn't that change her socioeconomic status? Why does she keep scrubbing toilets?

A: I thought it was obvious. Humility. She never wants to be like the others. They disgust her.

Balem Abrasax: [scoffing] No, my mother never cleaned a toilet in her life.
Jupiter Jones: Maybe that was her problem

A: she is probably dealing with PTSD = post traumatic stress disorder and doing what she is familiar with to ground herself and get her mind in order before she does whatever is necessary to ensure the survival/ non harvesting of earth
They also assumed it would do well enough to warrant a sequel which would have shown her being a Commonwealth Universal Revolutionary/ Entitled trying not to live the decadent life of an entitled


text:
Q: How to make dropdownlist How make a dropdownlist? [Edited - almost working code]
View:

        Firma

        @Html.DropDownListFor(x => x.ID_firma, Model.firmaList)
        @Html.ValidationMessageFor(model => model.nazwa)

Model:
 public class produktModel
{
    [Required(ErrorMessage="Proszę podać nazwę.")]
    public string nazwa { get; set; }

    [Required(ErrorMessage = "Proszę podać ilść produktu.")]
    public decimal ilosc { get; set; }

    [Required(ErrorMessage = "Proszę podać jednostkę produktu (np. kg, l, szt.).")]
    public string jednostka { get; set; }

    [Required(ErrorMessage = "Proszę podać cenę produktu.")]
    public decimal cena { get; set; }

    public string ID_firma { get; set; }

    public IEnumerable<SelectListItem> firmaList { get; set; }
}

Controller:
 public ActionResult dodaj()
    {

        var firma = baza.Firmas;
        var model = new produktModel
        {
            firmaList = firma.AsEnumerable().Select(x => new SelectListItem
            {
                Value = x.ID_firma.ToString(),
                Text = x.nazwa
            })
        };

        return View(model);
    }

    [HttpPost]
    public ActionResult dodaj(produktModel model)
    {

        Produkt prod = new Produkt();

        prod.nazwa = model.nazwa;
        prod.ilosc = model.ilosc;
        prod.jednostka = model.jednostka;
        prod.cena = model.cena;
         prod.ID_firma = model.ID_firma;

        baza.Produkts.InsertOnSubmit(prod);
        baza.SubmitChanges();

        return RedirectToAction("zarzadzaj_produktami", "Produkt");
    }

It almost work...
I have only one problem (I hope)...
Value is string, and I save his value to database... (I don't now how to write it...)

prod.ID_firma = model.ID_firma;

prod.ID_firma is int. model.ID_firma is this value which is string. So I have an error:

Error 1   Cannot implicitly convert type 'string' to 'int?'

A: change your model a bit, i have assumed the column names change them according to your code
   public class produktModel
        {
            [Required]
            public string name { get; set; }
            public decimal price { get; set; }
            [Required]
            public int companyID {get; set;}
            public List<Company> compList {get; set;}
        }

    public class Company{
        public int CompanyID {get;set;}
        public string CompanyName {get;set;}
       }

ActionResult should look like
public ActionResult add()
        {
            produktModel model = new produktModel();
            model.compList= (from b in base.Companies
                               select new Company{
                                 CompanyID = b.CompanyID,
                                 CompanyName = b.CompanyName
                                }).ToList();

            return View(model);
        }

in your (strongly typed) view
@model produktModel

....

            Company

            @Html.DropDownListFor(model => model.companyID,
                                new  SelectListItem(model.compList,
                                           "CompanyID ",
                                           "CompanyName "))
            @Html.ValidationMessageFor(model => model.company_name)

...

A: Your question isn't clear enough.
Any way you can use the telerik combox\dropdown list or the default mvc dropdown list. you can find a lot of examples on google for that.
With Telerik write something like this:
@(Html.Telerik().ComboBox()
            .Name("ComboBox")
            .BindTo(new SelectList("CompanyID", "CompanyName")))

see this Telerik demo for more information.


text: Q: Gibbons-Hawking-York (GHY) boundary term In the Hilbert action, apart from the bulk term, there is a boundary term called GHY $\int d^{3}x\sqrt{h}K$. Why do we choose to calculate this on the $r=$constant hypersurface instead of the $t=$const or $\theta, \phi=$ const?