Dummit and Foote 7.4 ex 34

Question: Let $\mathcal{R}=\mathcal{C}[\mathbb{R}\rightarrow\mathbb{R}], M_c=\{f \in \mathcal{R}: f(c)=0\}, I=\{f \in \mathcal{R},f$ has compact support$\}$.  Show a) $I$ is not a prime ideal b) If $I \subset M$ and $M$ is a maximal ideal then $M$ is not $M_c$ for any $c$
My attemept;
a) Take $f(x)=max\{sin(x),0\}$, $g(x)=max\{sin(x-\pi),0\}$ Then $(fg)(x)=0$ and clearly $0 \in I$ but neither $g,f$ are in $I$
b) Given $c \in \mathbb{R}$, $2c|1-\frac{x}{2c}|\chi[|x|\leq 2c]$ is in $I$ and so in $M$ but not in $M_c$
a) feels good but b) feels sketchy. I never use that $M$ is maximal or even any properties of the ideal.
Answer: b) It is indeed enough to show that $I\not\subseteq M_c$ for every $c$. Pick real $c$. Consider any piecewise linear continuous function $f(x)$ which is equal to $c+1$ on the interval $[c-1,c+1]$ and zero on the intervals $(-\infty, c-2]$ and $[c+2,\infty)$. Then $f$ is in $I$ but not in $M_c$.
Comment: I don't understand how do you define $f$ on $(c+1,c+2)$ and $(c-2,c-1)$ such that $f$ become continuous on whole $\mathbb{R}$
Comment: You can draw a graph of $f$. The graph is $0$ outside $[c-2,c+2]$, a constant $c+1$ on $[c-1,c+1]$, a line interval (segment) on $[c-2,c-1]$ and a line interval on $[c+1,c+2]$. These line intervals make the function continuous.
Comment: Hmm, yes. But here I have one question, we know a maximal ideal $\iff$ prime ideal in this PID . So how this  assume $I\subset M $ , where $M$ is maximal , is correct, as we know $I$ is not a prime ideal.
Comment: I do not understand your question. What does PID have to do with the OP or my answer?
Comment: I am saying about this **If $I \subset M$ and $M$ is a maximal ideal**,. How is it possible,as $I$ is not prime ideal.
Comment: How do $M$ look like , if there some?
Comment: If $I$ is not inside $M_c$ then any maximal ideal containing $I$ is not inside $M_c$ either. Just draw a Venn diagram.
Comment: You do not need to know how $M$ looks like, You only need to know that $M$ exists. In a unital ring every ideal is inside a maximal ideal (it follows from Zorn lemma).
Comment: Thanks, for the reply!!

Dummit and Foote 7.4 ex 34


DFS Nameserver is broke

Question: Our RAID array which housed the File server VMDK is no more.
This was a Windows Server 2003 install which was the file server and contained the DFS Namespaces.
The RAID array with all the files is intact and the data is working fine.
We have created a new VM and installed Server 2008 SP2 which we were able to mount the data volumes as RAW LUN hard drives in VMWare.
I need to know if there is any possibility of restoring the DFS Namespaces and structures.
Sadly... There appears to be no system state or even a backup of the Server 2003 VMDK. :(
There is however what appears to be a backup of the namespaces in the way of a .bat file.
So it looks like the previous sysadmin had a script running to backup the DFS to the .bat file. (I will restore this tomorrow to see if that is right.)
My question to you is:
Is it possible to restore DFS from this .bat backup file?
Is it possible to restore Server 2003 DFS namespaces to a Server 2008 SP2 install?
Is there any other place where the DFS info may extracted from? (The DC is on another server, is this info stored in Active Directory and can I pull it out and manually start building a new DFS namespace?)
Thanks for the input.
Comment: Question: if the raid array holding the file server broke, why do you say the files are intact? Or are you saying the array holding the OS volume of the file server broke and you had another array holding the file share data? Just trying to clarify your question.
Comment: The RAID array holding the VM had died and there is a second array holding the Data.
Answer: I'm going to assume that the batch file was running an export of the DFS namespace:
<code>dfsutil/root:<namespace> /export:<exportfilename>)
</code>
That being the case, Microsoft has a KB article on restoring the namespace from such a backup (option 2 on KB article KB969382).

To recover a namespace via an export file, perform the following:
a.  If the root doesn't already exist, create it using DFS Management.
Add all appropriate root targets.  Dfsutil.exe will fail to import the
configuration if the root itself doesn't already exist and will not
add root targets as defined in the file.  However, you may review the
contents of the export file to identify which root targets should be
manually added.
b.  Import the configuration file to create all of the hosted links
via the commands:
Windows Server 2003:
dfsutil /root:\contoso.com\DATA /import: DATA-dfs-Root.txt
Windows Server 2008:
dfsutil  root import set DATA-dfs-Root.txt \contoso.com\DATA
(Where the domain is contoso.com, "DATA" is the root's name, and
"DATA-dfs-Root.txt" is the export file)
Attempting the import before the root has been created will result in
the error "Element not found."
Attempting to add a root target that already has registry
configuration data associated with the root results in the errors "The
device is not ready for use" or "Cannot create a file when that file
already exists."  To remove the registry data from the affected
server, utilize the "clean" option within DFSUtil:
Windows Server 2003:
dfsutil /clean /server:servername /share:sharename
Windows Server 2008:
dfsutil diag clean servername sharename
c.  Verify the import was successful.  You may have to reopen any DFS
management tools to observe the imported links.
Comment: Soo, I restored the .bat file I found and it was basically 32000 something lines of commands. E.g.
dfscmd /map "\\NameSpace\Public\Folder Name\Folder Name" "\\Server Name\Network Share Name" ""
Considering it was not what I expected, and there were a lot more shares than I expected.
With nothing more to loose, I created a new NameSpace and ran the Batch Script.
This recreated all the folder paths a lot of which are old so I will see on Monday who logs a ticket and manually fix it.
Comment: Thanks again for the answer Rex, I have not had a chance to try the steps you posted, because the file I thought was going to be a DFS backup, turned out to not be. In any case, I hope the answer helps someone else.

DFS Nameserver is broke


Changing to background/text color of a ComboBox depending on the value chosen

Question: I would like to be able to change the background color of a combo box depending on the value chosen in a wpf.
I have tried using python to do this  but I am new to programming (and IT in general)
Could you point me in the right direction, please?
Current code:
from System import Decimal

from System.Windows import MessageBox

from System.Windows import LogicalTreeHelper

from System.Windows.Input import KeyEventHandler

from System.Windows.Media import Brush, Brushes, ColorConverter

import sys

from time import sleep

class PythonDemo(object):

    def Init(self,_tikitDbAccess,_tikitSender):

        self._tikitDbAccess=_tikitDbAccess
        self._tikitSender=_tikitSender

        self.combobox=LogicalTreeHelper.FindLogicalNode(self._tikitSender, 'ComboBox1')

        self.combobox.LostFocus += self.ColorChange

        def ColorChange(self,sender,e):
            #List of things i have tried
            self.combobox.Background.Color="Red"# also tried "#FF00FF00"

            self.combobox.Background="Red"

            self.combobox.SelectedItem.Background="Red"

oPythonDemo=PythonDemo

Comment: You should add code of whatever you have tried and the exact problem you faced when trying it!
Comment: I see you have a c# tag, is a c# solution fine?
Answer: I see you have included a C# tag, so I will give you a solution in C#. If you need a solution in Python I can't help you, but you made it sound as if you didn't care, so here is my best effort.
I don't know what your XAML looks like, so I can only give you a rough implementation, but you should be able to implement this easily.
Here is the XAML:
<Grid>
    <ComboBox Name="ComboBox1" SelectionChanged="ComboBox1_SelectionChanged" Height="50" Width="Auto">
        <ComboBoxItem Name="GreenOption" Content="Green"/>
        <ComboBoxItem Name="BlueOption" Content="Blue"/>
        <ComboBoxItem Name="PinkOption" Content="Pink"/>
        <ComboBoxItem Name="RedOption" Content="Red"/>
    </ComboBox>
</Grid>

Again, that should be replaced with whatever you happen to have, this is just an example. Here is the C#:
using System.Windows.Media;

/*The rest of your code goes here*/

private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var foo = sender as ComboBox;
        var bar = foo.SelectedItem as ComboBoxItem;

        switch (bar.Name)
        {
            case "GreenOption":
                foo.Background = Brushes.Green;
                break;
            case "PinkOption":
                foo.Background = Brushes.Pink;
                break;
            case "RedOption":
                foo.Background = Brushes.Red;
                break;
            case "BlueOption":
                foo.Background = Brushes.Blue;
                break;
        }
    }
/* Or Here */

It's very possible that there are more elegant solutions, and I don't know how it would be done in Python, but the basic principle should be the same. Make sure you remember the using System.Windows.Media; directive, and this should work like a charm.
Comment: Thanks for you help @Cubemaster. I have tried to implement this and I get the following error:  Failed to create a 'SelectionChanged' from the text 'ComboBox1_SelectionChanged'
Comment: Try going into the XAML and deleting and retyping the `SelectionChanged` portion of the tag. The autocomplete should say something like "Complete Method" or "Add New Event Handler". Click that if it comes up, and put the code into that handler.

If that doesn't work, let me know


How to replace constants terms from python API in clingo / gringo?

Question: Suppose I have a the following file foo.lp:
foo(x).

Now when I run gringo -t -c x=1 foo.lp I obviously get:
foo(1).

Now I want to know how to achieve the same behavior as the -c command line option from the Python API, like when I have:
from clingo.control import Control
ctl = Control()
ctl.load('foo.lp')

#ctl.ground() # What to do here exactly?

So that I can access the ground program / models of the solved program with the constant term replaced.
Comment: I think you are interested in grounding subprograms, i.e. use the program directive with arguments and ground as you like. Here are some examples: https://github.com/potassco/clingo/blob/master/examples/clingo/multishot/opt.py
Answer: Turns out it's possible to initialize Control with the command-line parameters, so this does the trick:
ctl = Control(["-c", "x=1"])


Exhausting Heat in Server Rack

Question: I was recently provided a 4 post Server Rack/Cabinet (48U) to fit all my equipment cleanly. One of the items they provided was a Tripp Lite Rackmounted A/C Unit (SRCOOL7KRM). This was truly Awesome thinking on their part, although I wish they had spoken with me before purchasing as I have no way to direct the Exhaust up and out of the little 'Closet' the Rack is located in.
What I am looking for is not exactly 'Low Cost' solutions, but I am not shy when it comes to DIY solutions either. I have a Drop Ceiling in the room with No A/C Ducts nor vents into the room (reason why Management gave me the unit.). I was originally thinking of something simply like using the same type of Ducting that you would find with a Clothing Dryer. That would work to get the hot air through the Ceiling, but the trick is catching the Hot Air and guiding it to that exhaust duct. Anyone have any thoughts? Anyone out there with a SRCOOL7KRM in the same situation as me come up with something?
I Thank you in Advance for any Advice and/or Guidance provided in your Replies.
Answer: Hope you figured something out already, but take a look at the SRCOOL7KDUCT. Its meant to duct the heat out the back door and into a drop ceiling like you describe.
https://www.tripplite.com/smartrack-duct-kit-srcool7krm~SRCOOL7KDUCT/
I'd love to hear how you make out. We're still playing around with this device to get it to be effective in a similar situation with just 4 servers in the rack.

Exhausting Heat in Server Rack


Content Type and Fields programmatically

Question: I make a module in Drupal 8 who create a new content type programmatically.
Module name : Annonce
In config/install I add this file:
node.type.annonce_type.yml
type: annonce_type
name: 'Ajouter une annonce'
description: 'Formulaire pour ajouter une annonce'
help: ''
new_revision: false
display_submitted: true
preview_mode: 0
status: true
langcode: fr

All is good, my new content type is create in backoffice.
But now I want to add some fields programmatically, and I don't find a core module who are doing that.
Comment: Please don't downvote without adding a comment as to why!
Answer: I answered pretty much the same once already I think, but I can't find that answer anymore.
You add fields and their widget and formatter configuration in the same way. By adding all the relevant config entities.
You can find almost all of them by exporting configuration into the staging folder and then search for files that contain "announce_type" in the file name. That gives you the fields, the form and view displays configurations.
Then you also need the field storages. These are shared across bundles, so they don't have the node type in them (unless you prefixes your fields with your node type/module, which is a good idea if you want to make them part of your module).
Put all those fields in config/install and you're done.
Comment: Can you plz provide a sample code for field creation..
Comment: Ok that work but i have 3 files yml for one field... core.entity_form / core.entity_view and field.field.node


How do I add Google +1 to Addthis Button?

Question: I am using the Addthis Module version 6.x-3.0-beta2, the problem is that google +1 doesn't appear as one of the services. Anyone knows how to fix this ? Thanks !
Answer: There is a tutorial http://www.addthis.com/features/google-plus1-button
Anyway, +1 is not a sharing service, I'm not sure that Addthis will add this (like there is no Facebook Like button). You can use the Customize service that addthis.module supports to add code described here.
Comment: The tutotial explains how to add it to the toolbox, I need to add it to the button. And Google +1 is listed on the AddThis Service Directory http://www.addthis.com/services/list. Any other ideas ?
Comment: I think that the +1 is implemented with the code I gave above. The services list is just a marketing. Even at addthis.com, when you click on "More options" there is no +1.
Comment: So there is no way to add the google +1 button inside of addthis, right ? Just outside ..


Create a base fluent ordered constructor

Question: EDIT:
Ok, seem example is unuseful...
I have an ordered fluent constructor that is common to many object (all have tha same properties). Is there a way to put all the code in the same base factory class and have only the final costructor in the derived factory?
I use constructor like this
.InitCreation()
.WithID()
.WithPoperty1()
.Create()

where only the Create() make the new object and ID is a mandatory field.
Generics seem me to need rewriting all methods in all factory, instead i want to rewrite only the Create() method to return the right object.
Other way is to grant mandatory field in fluent constructor without using an ordered fluent but don't find nothing to do it
EDIT2
The baseFactory:
    namespace FunzIA.DL.Factory
{
    public class BaseObjectFactory : IBaseObjectCreated, IBaseObjectWithMandatoryField1, IBaseObjectWithFields
{
    internal int mandatoryField1 { get; set; }
    internal string mandatoryField12 { get; set; }
    internal bool optionaField1 { get; set; }

    private BaseObjectFactory(){}

    public static IBaseObjectCreated InitCreation()
    {return new BaseObjectFactory(); }

    public IBaseObjectWithMandatoryField1 WithMandatoryField1(int number)
    {
        mandatoryField1 = number;
        return this;
    }

    public IBaseObjectWithFields ConmandatoryField12(string text)
    {
        mandatoryField12 = text;
        return this;
    }

    public IBaseObjectWithFields optionaField1(bool optionaField1P)
    {
        optionaField1 = optionaField1P;
        return this;
    }

    public BaseObject Create()
    {return new BaseObject(this);}
}

public interface IBaseObjectCreated
{IBaseObjectWithMandatoryField1 WithMandatoryField1(int number);}

public interface IBaseObjectWithMandatoryField1
{IBaseObjectWithFields ConmandatoryField12(string text);}

public interface IBaseObjectWithFields
{
    IBaseObjectWithFields optionaField1(bool optionaField1);
    BaseObject Create();
}
}

The old Example
i create a class Struttura in this way:
namespace FunzIA.DL.Oggetti
{
public class Struttura
{
    public int IdStruttura { get; set; }
    public string Descrizione { get; set; }
    public bool Annullato { get; set; }

    private Struttura(){}
    public Struttura(StrutturaFactory factory)
    {
        IdStruttura = factory.idStruttura;
        Descrizione = factory.descrizione;
        Annullato = factory.annullato;
    }
}
}

And his Fuent Constructori is this:
namespace FunzIA.DL.Factory
{
    public class StrutturaFactory : IStrutturaCeato, IStrutturaConChiave, IStrutturaConProprieta
{
    internal int idStruttura { get; set; }
    internal string descrizione { get; set; }
    internal bool annullato { get; set; }
    internal IList<Processo> processi { get; set; }

    private StrutturaFactory(){}

    public static IStrutturaCeato IniziaCreazione()
    {return new StrutturaFactory(); }

    public IStrutturaConChiave ConCodice(int codiceP)
    {
        idStruttura = codiceP;
        return this;
    }

    public IStrutturaConProprieta ConDescrizione(string nome)
    {
        descrizione = nome;
        return this;
    }

    public IStrutturaConProprieta Annullato(bool annullatoP)
    {
        annullato = annullatoP;
        return this;
    }

    public Struttura Crea()
    {return new Struttura(this);}
}

public interface IStrutturaCeato
{IStrutturaConChiave ConCodice(int chiave);}

public interface IStrutturaConChiave
{IStrutturaConProprieta ConDescrizione(string nome);}

public interface IStrutturaConProprieta
{
    IStrutturaConProprieta Annullato(bool annullato);
    IStrutturaConProprieta ConProcessi(IList<Processo> processi);
    Struttura Crea();
}
}

In this way i can write constructor in this way
Struttura actual = StrutturaFactory.IniziaCreazione()
                                .ConCodice(1)
                                .ConDescrizione("MiaDescrizione")
                                .Crea();

But now i see that i have many object with similar fields (ID, description, canceled) so i try to write a common fluent constructor:
namespace FunzIA.DL
{
public class OggettoBaseFactory : IOggettoBaseCeato, IOggettoBaseConChiave, IOggettoBaseConProprieta
{
    internal int id { get; set; }
    internal string descrizione { get; set; }
    internal bool annullato { get; set; }

    private OggettoBaseFactory(){}

    public static IOggettoBaseCeato IniziaCreazione()
    {return new OggettoBaseFactory();}

    public IOggettoBaseConChiave ConCodice(int codiceP)
    {
        id = codiceP;
        return this;
    }

    public IOggettoBaseConProprieta ConDescrizione(string nome)
    {
        descrizione = nome;
        return this;
    }

    public IOggettoBaseConProprieta Annullato(bool annullatoP)
    {
        annullato = annullatoP;
        return this;
    }

    public OggettoBase Crea()
    {return null;}
}

public interface IOggettoBaseCeato
{IOggettoBaseConChiave ConCodice(int chiave);}

public interface IOggettoBaseConChiave
{IOggettoBaseConProprieta ConDescrizione(string nome);}

public interface IOggettoBaseConProprieta
{
    IOggettoBaseConProprieta Annullato(bool annullato);
    OggettoBase Crea();
}
}

And modify my Factory
namespace FunzIA.DL.Factory
{
    public class StrutturaFactory : OggettoBaseFactory
    {
        public Struttura Crea()
        {return new Struttura(this);}
    }
}

But now when i write
Struttura actual = StrutturaFactory.IniziaCreazione()
.ConCodice(idExpected)
.ConDescrizione(descrizioneExpected)
.Annullato(annullatoExpected)
.Crea();
i get this error:

Error 5   Cannot implicitly convert type 'FunzIA_DL.OggettoBase' to 'FunzIA.DL.Oggetti.Struttura'. An explicit conversion exists (are you missing a cast?)

Is there a way to do it or i have to rewrite the same logic in all my fluent constructor?
Comment: Providing a shorter example code with English identifiers might be a good idea if you want to get answers.
Comment: You have to use generics.
Comment: I short it a bit more but it's the minimal code for understand the question. Identifier name don't mean much for the problem...
Comment: I too am searching it and found this article: http://stackoverflow.com/questions/1677938/generic-tthis-for-fluent-classes but see no way to integrate it with an ordered fluent.
Comment: I edited the first post tryng to be as simple as i can. Thanks for your patience
Comment: Using generics i find this way: http://stackoverflow.com/questions/6529611/c-sharp-create-new-t and edit my base contructor in this way: public T Create()
  {
   return (T)Activator.CreateInstance(typeof(T), this);
  } but at runtime i got error message that non constructor found where y class have the empty parameter constructor
Comment: It work, the error was a Nunit visualizer refresh problem :)
Answer: Just cast it like this:
Struttura actual = (Struttura)StrutturaFactory.IniziaCreazione() .ConCodice(idExpected) .ConDescrizione(descrizioneExpected) .Annullato(annullatoExpected) .Crea();

Comment: Ok, but in this way you are using "Crea()" method of the base class and it does nothing, i want to use the "Crea()" method of the derived class
Comment: This solves the exception problem. That you want to use the method of the derived class is not expressed well in your original question. I can't make sense of your code in ?Italian?. You'll have to cut down the clutter and try English identifiers as suggested in other comments.
Comment: I edited the first post tryng to be as simple as i can. Thanks for your patience
Comment: Why mark as solution if is not th solution to my problem? The solution is below...
Comment: You are the person who marked this as the solution. Try to undo it.
Comment: iam shure to have clicked other one...  In fact, I can not mark my correct as yet, but I have to wait a few more hours
Answer: I solved using Generics in this way in the BaseFactory:
public T Create<T>()
        {
            return (T)Activator.CreateInstance(typeof(T), this);
        }

then my DerivedFactory is simply this:
namespace FunzIA.DL.Factory
{
    public class SocietyFactory : BaseFactory
    {}
}

so i can write
Society actual = SocietyFactory.InitCreation()
                    .WithCode(idExpected)
                    .Create<Societa>();


Integral and Area between two functions

Question: I have two functions and I need to find the area between them: y^2=4x and x=3. I calculated the integral of 2*sqrt(x) on the interval [0,3] and I got 6.9282 for an answer. According to my homework solutions, this is incorrect. Is there something wrong in my setup or am I calculating something wrong?
Comment: The region extends both above **and below** the $x$-axis; your calculation caught only the upper half.
Answer: The upper boundary of the region is the curve $y=2\sqrt x$, but the lower boundary is $y=-2\sqrt x$, not $y=0$. You calculated the area of the upper half of the region.
This is a good example of a problem that can be done about as easily with $y$ as the independent variable. Instead of chopping the region up into 'infinitely narrow' vertical strips, chop it up into horizontal strips instead. The line $x=3$ intersects the parabola $y^2=4x$ at $y=\pm2\sqrt 3$, so your $y$-values will range from $-2\sqrt3$ to $2\sqrt3$. The horizontal strip at height $y$ runs from a low $x$-value of $\frac{y^2}4$ to a high $x$-value of $3$, so its length is $3-\frac{y^2}4$, and the area is given by the integral
$$\int_{-2\sqrt3}^{2\sqrt3}\left(3-\frac{y^2}4\right)dy=\left[3y-\frac{y^3}{12}\right]_{-2\sqrt3}^{2\sqrt3}=12\sqrt3-4\sqrt3=8\sqrt3\;.$$
Comment: Darn. 2 minutes too late. :)
Comment: @anonymous: Actually, I *think* that you posted while I was adding the second paragraph, so it's at worst a tie!

Integral and Area between two functions


Point between two points given time?

Question: Let's say there are two separate points in a 3 dimensional space. An object at point A can move to point B at any speed given (let 'S' be units per second). If I start moving the object from point A to point B at 'sT' (let 'sT' be the start time in milliseconds), and I want to get the point it would be at 'eT' (let 'eT' be the elapsed time in milliseconds) milliseconds later, how would I go about calculating it?
(Edit: Now I actually have the time it'll take for the object to point A to point B at 'S' speed. So now I just need to get the point it'll be at after some 'eT'.)
For example, here is an object at point A moving to point B:
[movement]1
If point A is at (1, 12, 4) (in X, Y, Z format), point B is at (3, 5, 5), the object is moving at 2 units per second, and it started moving at 12323 milliseconds; how can I get the position it would be at 17421 milliseconds?
Edit. I now have the following information to work with: start time (ms), time it will take for the entire movement (ms), speed (units/second), points A and B. I tried setting up an equation given the answer by Eli Rose, but it's failing. It is returning very off value, but I probably just did something wrong.
(Ps. Apparently I can't post images until I have 10 reputation, I hope leaving links to the image is allowed.)
Comment: Time = AB/speed ; Time fraction = length fraction
Comment: I actually already have the time it will take in milliseconds, I just need to know where it will be after 'eT' milliseconds.
Comment: Can you not locate the point by proportion?
Comment: That's exactly what I don't know how to do...
Answer: Every second, your object moves $2$ units towards $(3, 5, 5)$. It moves some number of units $v_x$ in the $x$ direction, some number of units $v_y$ in the $y$ direction, etc. can be written as a list of components $(v_x, v_y, v_z)$.
If we can find $(v_x, v_y, v_z)$ then we can just multiply each $v$ by the difference in times $\Delta t$ (which is $5.098$ seconds in your case) to get the distance it will have moved in the $x$-direction, in the $y$-direction, etc.
Then the position it's at will be $(1 + v_x\Delta t, 12 + v_y\Delta t, 4 + v_z \Delta t)$.
So what are $(v_x, v_y, v_z)$ ? It might seem like they would be $(2, 2, 2)$ but that would actually make for an object that's traveling too fast. Think about it in two dimensions -- if you're traveling two units to the right and two units up every second, you're traveling faster than two units per second overall.
How much faster? The Pythagorean Theorem can tell us, since the distance you cover is the hypotenuse of a right triangle whose legs are length $2$ and $2$.
$$\sqrt{v_x^2 + v_y^2} = \sqrt{2^2 + 2^2} = \sqrt{8} \approx 2.8 \text{ units per second}$$
Suppose you made the whole journey in one second. Then your $(v_x, v_y, v_z)$ would equal $(3 - 1, 5 - 12, 5 - 4) = (2, -7, -1)$. But this is too fast. How fast?
$$\sqrt{2^2 + (-7)^2 + (-1)^2} = \sqrt{54} \text{ units per second}$$
If we divide every $v$ by $\sqrt{54}$
$$(\frac{2}{\sqrt{54}}, \frac{-7}{\sqrt{54}}, \frac{-1}{\sqrt{54}})$$
then we get what $(v_x, v_y, v_z)$ would be if you traveled at $1$ unit per second. But this is too slow for us -- we want twice that.
$
\begin{aligned}
v_x &= \frac{4}{\sqrt{54}}\\
v_y &= \frac{-14}{\sqrt{54}}\\
v_z &= \frac{-2}{\sqrt{54}}
\end{aligned}
$
In math, this concept is called vectors. In particular you are trying to find the velocity vector of your object. What you get by dividing everything by $\sqrt{54}$ is called a unit vector. This is what all physics engines for games, animations, etc. are based on.
Comment: So, how do I put everything you just said in an equation using the variables I listed first? I noticed that you explained it all with my example, that's where I got lost...
Comment: If $A = (A_x, A_y, A_z)$ and $B = (B_x, B_y, B_z)$ then my $(2, 7, 1)$ is instead $(B_x - A_x, B_y - A_y, B_z - A_z)$. What you are doing is the vector subtraction $B - A$. You could also do $A - B$, it should make no difference.
Comment: Well, this is for a game that is scripted in C++. If you could maybe provide a script example that would be nice. If you don't know how to script C++, could you show me the steps using my variables (Ax, Ay, Az, Bx, By, Bz, S, sT, eT, and return Vx, Vy, Vz)?
Comment: On another note, could you just show me how to do if I know how many milliseconds (let that be 'm') it'll take to get from point A to point B? I just realized that I actually already have that.

Point between two points given time?


Apriori Algorithm Visualization & Interpretation in R

Question: I would like to visualize the items that are frequently bought together. Also I would like to know how to interpret the visualization. The dataset is taken from https://www.kaggle.com/sivaram1987/association-rule-learningapriori . The code is as follows
df <- read.transactions(
  'C:\\Users\\write\\Documents\\R\\data\\Market_Basket_Optimisation.csv',
  sep = ",",
  rm.duplicates = TRUE
  )

set.seed(250)

rules1 <- apriori(df,
                parameter = list(supp = 0.004,conf = 0.2))

arules::itemFrequencyPlot(df,
                          topN = 20,
                          col=brewer.pal(8,'Pastel2'),
                          main = 'Relative Item Frequency Plot',
                          type = 'relative',
                          ylab = 'Item Frequency'
                          )

plot(
  rules1[1:10],
     method = 'matrix',
     control = list(reorder='none')#lift
  )

The visualized result is as follows.

How to interpret the result?
Answer: Here is how you can interpret for matrix-based visualization (refer to https://cran.r-project.org/web/packages/arulesViz/vignettes/arulesViz.pdf):
Formally, the visualized matrix is constructed as follows. We start with the set of association rules $R = \{<a_1, c_1, m_1>, \ldots <a_i, c_i, m_i>, \ldots <a_n, c_n, m_n>\}$ where $a_i$ is the antecedent (LHS of an association rule), $c_i$ is the consequent (RHS of a rule) and $m_i$ is the selected interest measure (LIFT e.g.,) for the $i^{th}$ rule for $i = 1, \ldots, n$.
In R we identify the set of $K$ unique antecedents and $L$ unique consequent. We create a $L × K$ matrix $M$ with one column for each unique antecedent and
one row for each unique consequent. Finally, we populate the matrix by setting $M_{lk} = m_i$ for $i = 1, \ldots, n$ and $l$ and $k$ corresponding to the position of $a_i$ and $c_i$ in the matrix.
Note that $M$ will contain many empty cells since many potential association rules will not meet the required minimum thresholds on support and confidence.
Now, let's first see top 10 association rules the apriori has produced as output:
DATAFRAME(rules1[1:10])

Let's find the unique antecedents (LHS items in the rules)
unique(DATAFRAME(rules1[1:10])[,1])
[1] {}                     {body spray}           {cider}                {nonfat milk}          {pasta}                {extra dark chocolate}
[7] {gums}
Levels: {} {body spray} {cider} {nonfat milk} {pasta} {extra dark chocolate} {gums}

and consequents (RHS items in the rules)
unique(DATAFRAME(rules1[1:10])[,2])
[1] {mineral water} {french fries}  {eggs}          {escalope}      {shrimp}        {spaghetti}
Levels: {mineral water} {french fries} {eggs} {escalope} {shrimp} {spaghetti}

With the above, it's straightforward to interpret the visualization matrix, as shown below:

the cells represent lifts, color-coded, for association rules $l \to r$, if present in the apriori output
the x axis corresponds to antecedents (LHS items $l$) and
the y axis corresponds to consequents (RHS items $r$) corresponding to the association rules.
Comment: what does the {} in LHS imply?
Comment: Also how did you extracted the LHS and RHS from rules? Please explain what does [,2] imply in the unique( ).
Comment: This is a single item rule, which denotes the probability of the mineral water in an itemset alone, that's why the support and confidence are same for the item, i.e., $P(mineralwater \cap \{\})=P(mineralwater|\{\})$.
Comment: 2nd column in the data frame


delay output one by one php

Question: In this code , it have 5 output .
how to delay output like
show output 1 -delay 1 sec.-
and then show output 2 -delay 1 sec.-
and then show output 3 -delay 1 sec.-
and then show output 4 -delay 1 sec.-
and then show output 5 -delay 1 sec.-
<code><?php
for($i=0;$i<5;$i++)
{
    $strSQL = "SELECT * FROM test_grid order by id Limit $i,1 ";
    $objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
    $objResult = mysql_fetch_array($objQuery);
    echo nl2br($objResult["text"]);
}
?>
</code>
Comment: RTFM: http://php.net/sleep and realize that you can NOT control with 100% reliability how things get sent from your server to the client and displayed.
Comment: This sounds like a task for JavaScript.
Answer: In order to do this the best way, please refer to JavaScript Timing Events.
Answer: The sleep command might work, but as Marc B said it might not work on some or all servers.
I personally agree with Matt Ball on this one. It's a job for javascript using either setTimeout (http://www.w3schools.com/jsref/met_win_settimeout.asp) or setInterval (http://www.w3schools.com/jsref/met_win_setinterval.asp)

delay output one by one php


OSError: file.so: cannot open shared object file: No such file or directory

Question: I have built an .so file used in our python package. We use the package on Dietpi 64bits. When I import our package I get the error:
OSError: file.so: cannot open shared object file: No such file or directory

I know for a fact that the file is there and the path is good.
What is puzzling me is that when I try the same code on a Virtual Machine (also Diepi 64bit), the dynamic library is found and loaded properly. I did that to try an isolate the difference between my setup and my colleague's setup.

File exists
Same location in both cases
File has the same rights (chmod 777)
He is using python 3.6, while VM 3.7

What am I missing?
What can cause the OS to raise a No such file or directory exception when the directory DOES exists and file IS there?

Edit
Here is the code that I'm using
import os
import ctypes

shared_library_name = "libFoo"

print("current working directory: {}\n".format(os.getcwd()))
current_path = str(os.path.dirname(os.path.abspath(__file__)) + "/natives/")
os.chdir(current_path)
current_path = os.path.abspath(os.getcwd())

path_to_so = os.path.abspath(current_path + "/" + shared_library_name + ".so")
print("new current_path: ", current_path)
print("\n path_to_so: {}\n".format(path_to_so))
# prints the right path with the right file, and I can cd to it in the terminal

print("path exist {}".format(os.path.isdir(current_path)))
print("file exist {}\n".format(os.path.isfile(path_to_so)))
# prints False

dll = ctypes.cdll.LoadLibrary(path_to_so)
# fails saying that the file is not there...

Comment: you could pass strace on your call and see if it is not an error reported by the loader of a lib of a second level (a so needed by a so you call explicitely)
Comment: how do you start you program?
Comment: Either a script in python or Python in the terminal
Comment: strace doesnt seem to indicate any missing .so or obvious errors
Comment: Can somebody explain the downvote?
Answer: The shared library that I was trying to open was not build for the architecture used by your Virtual Machine.
aarch64 vs x84_64
When I asked the question, I was not aware that my target (NanoPi Neo2) needed different flags than the virtual machine when building the shared library.
https://unix.stackexchange.com/questions/461179/what-is-the-difference-between-different-implemetation-of-arm64-aarch64-for-lin
Differences between arm64 and aarch64


Vector field induced by $X$ via charts on $M$

Question: Let $M^n$ a smooth manifold and $X \in \mathfrak{X}(M)$ a vector field on $M$. I'm trying to transfer the Tubular Flow Theorem from $\mathbb{R}^n$ to $M$. For this, let $p \in M$ a non-singular point of $X$ and $(U,x)$ a chart over $p$ in $M$. The question is:
How to transfer "correctly" $X|_U=\sum a_i\dfrac{\partial}{\partial x_i}$ from $U$ to $x(U)\subset \mathbb{R}^n$?
My idea is define, for $u \in x(U)$, a vector field $Z(u)=(a_1(x^{-1}(u)),\dots,a_n(x^{-1}(u)))$. I think this is OK, in the textbook I'm using, the author uses notation $x_*X$ for a "vector field induced by $X$ on $x(U)$" but does'nt defines what precisely it is...
Someone have a definition for this? My definition of $Z$ agrees with $x_*X$?
Answer: Technically, what you call $X\vert_U$ seems already to be the vector-field on $x(U)$.
$x_*X$ is the pushforward  of $X$ via $x$, i.e. is the vector-field such that, given $f:x(U)\to\mathbb R$, you have
$$x_*X (f)=X(f\circ x)\;.$$
When you write
$$\sum a_i\frac{\partial}{\partial x_i}$$
you are writing a vector-field on $\mathbb R^n$ with respect to the coordinates $x_1,\ldots, x_n$, because that derivation/vector-field/partial derivative with respect to $x_i$ makes sense only in $\mathbb R^n$.
The only meaning this writing has on a manifold is with respect to local coordinates, that is, in a chart, where you define vector-fields $\partial_1,\ldots,\partial_n$ in $\mathfrak{X}(U)$ such that
$$x_*\partial_j=\frac{\partial}{\partial x_j}\;.$$
Now, in the same way, one usually writes coefficients $a_1,\ldots, a_n$ as functions of the local coordinates, so you will already have $a_j=a_j(x_1,\ldots, x_n)$, because the frame $\partial_1,\ldots, \partial_n$ exists only on $U$, so the writing
$$X=\sum a_j\partial_j$$
makes sense only on $U$. Therefore, it is harmless to suppose that $a_j$ is a function of $x_1,\ldots, x_n$.
With these assumptions (which are the only reasonable ones under which your expression makes sense), the coordinates of $x_*X$ in $\mathbb R^n$ are exactly the functions $a_1,\ldots, a_n$, viewed as functions of $x_1,\ldots, x_n$.
If you instead for some reason want to remember that $a_1,\ldots, a_n$ are functions on $U$, then, you will write, as you say, $a_j\circ x^{-1}$.
Note: I strongly doubt that any book about vector-fields can "forget" to define the pushforward, so I would suggest you to read more carefully the previous pages (or chapters), in particular when the definition of vector-field is given.
Comment: I forgot to write ^n :D Nice development on my question, Mr. Wisefool. Now I found the page that the author mentions the definition of $x_* X$, but in very few lines. But it's sufficient for what i need. Thanks!


what is the use of universal unique identifier ,why its so much important in deployment?

Question: What is the use of universal unique identifier in drupal7, why its play important role in deploy and service
Answer: UUID is used to identify the same objects (like nodes, taxonomy_terms and users) across environments.
All of these has an ID, for nodes it's the nid (node id), but that is not reliable to use across environments, since it's serial (1, 2, 3 ...). Fx the about page on content staging environment might have id 5 while it on the production environment might have id 1.
Deploy is all about pushing content between environments, so if you make a change on your content staging site, you want to be able to push those changes to the correct node. Since nids can't be used, as they aren't universially unique, but only unique for the specific environment, we need something that is. That is exactly what uuids and the uuid module provide.
Comment: thanks for your awesome explanation , now i have one more doubt if on staging content site nid-13 haveing 123-4566-789 uuid so on after deploying content my nid will get change but uuid will remain constant ??
Comment: @Harshil The UUID will never change, so if you push a node from staging to production, the UUID will be the same (but the nid might not be) which makes it possible to push updates as well (since the UUID is the same, the system knows which node to update).


Otimização jogo Touros e Vacas

Question: Fiz esse código de um jogo chamado Bulls and Cows (touros e vacas) onde é um jogo de adivinhação, porém, é um pouco diferente, vou dar um exemplo:
Os números escondidos são 1 2 3 4.
Se você colocar 1 2 6 7, você tem Dois Touros (números certos nas posições certas)
Se você colocar 3 2 4 5, você tem 3 vacas e 0 touros (vacas são números certos
nas posições erradas) de modo que 1 2 3 4 sejam 4 touros.
Quatro touros = jogo encerrado.
É um dos exercícios primários do primeiro livro do Bjarne.
Ao ponto: preciso dar uma otimizada no código, sei que há meios mais fáceis de fazer isso, não quero que otimizar seja necessariamente ter menos código, apenas algo mais simples e que não deixe de ser manutenível e fazer seu dever, alguém tem alguma ideia? (:
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <ctime>
using namespace std;

int main()
{

int touro = 0;
int vaca = 0;
int num1 = 0;
int num2 = 0;
int num3 = 0;
int num4 = 0;
srand(time(0)); // Pega o tempo do PC para gerar a seed
int segredo[4] = {rand()%25,rand()%25,rand()%25,rand()%25};

cin >> num1 >> num2 >> num3 >> num4;

for(int x = 0; x<4; x++){
  if(num1 == segredo[x]||num2 == segredo[x]||num3 == segredo[x]||num4  ==segredo[x])  // se for o numero (Não necessariamente a ordem) vaca++
  vaca++;

 }

int tourosVec[4] = {num1,num2,num3,num4};

for(int y = 0; y<4; y++){
   if(tourosVec[y] == segredo[y]) // compara exatamente números e posições
       touro++;
   }

cout << "vacas: " << vaca << endl;
cout << "touros: " << touro<<endl;

 if(touro == 4){
     cout << "Ganhou!" << endl;
     }
     return 0;
     }

Answer: O que você pode fazer é melhorar a organização do código, não amontoe tudo e não escreva cada hora de um jeito.
Fora isto pode fazer pouca coisa, até onde entendi.
Pode transformar num de 1 à 4 em um array e quem sabe fazer um for interno para comparar e simplificar o if. Aí tourosVec deixaria de ser necessário (ou poderia usá-lo no lugar dessas 4 variáveis). Isto não é exatamente uma simplificação e muitos programadores achariam até que está piorando o código em algo tão curto.
Isto está mais C e pouco C++. Usar um vector no lugar de um array me parece ser um objetivo do exercício. Aí poderia usar outros algoritmos como o random_shuffle ou find.
Comment: É porque eu não sei como eu comparo dentro de um for UM numero com o resto do vetor, normalmente da mesma forma que ele soma 1 para o comparador, também soma 1 para o que vai ser comparado.. Eu não conheço essas funções mas irei pesquisar, valeu. (:

Otimização jogo Touros e Vacas


Overriding int on a bit enum

Question: I saw some .NET 2.0 code which looked like this:
 public enum abc : int
 {
  value1 = 1,
  value2 = 2,
  value3 = 4
 }

etc...
Now I know the flags enum can be used for bit values (like above, right?) so you can do | "or" &, etc, but what is the reason for not using that? What is the point in overriding int?
If I design an enum for choosing multiple values I would use the flags attribute and not override anything (what I don't understand). What does the above approach net?
Thanks
Answer: It's not "overriding" int, it's indicating what type the enumeration is based on. The default is int so this actually isn't achieving anything, but in some cases you might want to base an enum on long to store more flags, or byte to save space if there will be very many instances of the enum around and it only has a few values, however the recommendation in the framework design guidelines is to use int unless you have a very good reason not to.
If this is intended to be a flags enumeration then it should be marked with [Flags], and this appears to be the intention here, so the omission looks like a mistake. You can still combine the values using the bitwise operators even if it isn't marked with [Flags], but from memory I think you get a compiler warning (or it might be an FxCop warning, or possibly a ReSharper warning...).
Answer: The ": int" is specifying what to use as the underlying type for enum values; any integral type other than char can be used here.  The default is int, so it is redundant in this case.
Answer: FlagsAttribute only tells the user that fields in this enum can be combined; it doesn't actually set the fields of the enum to "flaggable" values. This, you will have to do yourself, just like you have already.
Answer: I don't see any benefit.  Probably lack of experience on the programmer's part.
Answer: If you are asking the scenario for choosing specific values, I don't know a good example offhand, but I can imagine something like
enum Color = {
  Red = 0xFF0000,
  Green = 0x00FF00,
  Blue = 0x0000FF }

maybe being useful.
Answer: Setting the values on a non-Flags enum to use a 1-hot encoding just for the sake of using a 1-hot encoding doesn't really make any sense. I guess it might make sense if you thought you might make it a Flags enum in the future. Otherwise, the values should either be not overridden or assigned a value based on their meaning (eg. Color.Red = 0xFF0000).
Answer: In reference to the ": int" specifying the underlying type, if I saw that, I'd have a look around and see if they delcare all their enums that way. If so, they probably just learnt to write enums that way ( or maybe they are a hyper-explicit coder). If however, just this enum was declared this way, perhaps the programmer is trying to say something (that might have been better said with a comment) that it is critical that this has an underlying "int" type. Perhaps it is being binary serialised or deserialised somewhere.
As for the [Flags] attribute, as far as C# is concerned, you can use bitwise operators on any enum, not just those declared with [Flags]. From your above example, without any [Flags], the following is totally legal:
abc myAbcValue = value1 | value2;
The primary difference with respect to the [Flags] is in the ToString() and Parse() methods of Enum. Without [Flags], myAbvValue.ToString() will return "3", but with [Flags] it will return "value1, value2". Likewise, with the [Flags],
abc yourAbcValue = (abc)Enum.Parse( typeof(abc), "value1, value2") ;
will set the underlying value of yourAbcValue to 3.
Note that the IsDefined() method of Enum() does not allow for multiple values with [Flags] enums, so:
Enum.IsDefined( typeof(abc), "value1, value2")
returns false regardless of the use of [Flags].
Also note that [Flags] provides information for any reflection access, and other languages may treat the restriction on flagged enums differntly to normal enums.

Overriding int on a bit enum


Concurrent modification during backup: rsync vs dump vs tar vs?

Question: I have a Linux log server where multiple applications write data. Data is written in bursts, and in a lot of different files. I need to make a backup of this mess, preferably preserving as much coherence between the file versions as possible and avoiding getting truncated files. Total amount of data on the server is about 100Gb. What I really would want (but can't) is to shut-down, backup the system cold and then start it up again.
What kind of guarantees against concurrent modification does the various backup tools give? When do they "freeze" the file versions? I am looking at rsync, dump and tar at the moment, but I am open for other (open source) alternatives.
Changing the application or blocking writing for backups is sadly not an option. System is not running LVM (yet), but I have considered that for rebuilding the system and then snapshots.
Comment: LVM snapshots are very good idea in this situation. Most of the unix standard backup tools expect you to control file modification during backup, i.e. shutdown a database or make sure applications don't update files during backup. Rsync may give you better results, as it may be quick enough to capture changed file between updates. The safest method is using lvm snapshots IMHO.
Answer: isn't some sort of log rotation an option for you? just back up log files that are already rotated - wont it be a solution?
and yes - otherwise snapshot on the LVM level would be your best choice [ remember that when snapshot is active your write performance degrade ].
Answer: If you're using syslog, you can configure your log server to replicate logs live to another server (e.g. rsyslog) for real-time backup.
Then backup all rotated files as already suggested for long-term archival.
logrotate can be configured for custom applications, too, and can apply bash scripts on rotated logs. So you may skip /var/log in external backup tools altogether and copy logs to an archive directory which is more static.
Answer: None of the tools you are considering provide guarantees against concurrent modification.  However, do you really need a point in time snapshot.  If so use the LVM snapshot option given above.  As you have given rsync as an option I assume that disk to disk backup is an option.
Least secure is dump which takes a copy of the disk blocks as they are read.  Given the size of your data there is likely to be significant differences between the directory information and the data.  For disk to disk backup you could consider dd to partitions of the same size as an alternative.  Both solutions do essentially the same thing and have the same problems.
Tar will read the files one by one and will read to the end of each.  If a file is renamed or deleted while tar is backing it up tar will back up the file it started reading.   It is a reasonable solution for log files.
Rsync behaves like tar, but only copies changes.  Essentially it will copy all changes to the directories.  With a date based log rotation scheme (logfile.yyymmdd) instead of the common rotated version scheme (logfile.1 logfile.2gz ...).  It can efficiently backup your logfiles.
Comment: `dump` will check the inode mod time after it writes a file; if the file is modified during the write it's flagged and retried again at the end of the dump.  If the writes are bursty as the OP says, this might well be enough to find a window of stability and save the file.
Comment: @mpez That is a very interesting bit of information. Thanks!
Comment: Some versions of tar will also retry modified files.  If the writes are sufficiently bursty, the file can be read on a second or third try.  Frequently written large files can be a problem.


Block is displayed on page even though no region is selected, how is this possible?

Question: I am fairly new to drupal, while doing some maintenance I came across a situation that I don't understand

A block, which is defined inside a view has no region selected, yet it appears on pages determined by the "Only the listed pages" option below
It appears in a specific region, an  named as "region-sidebar-second"
I'm unable to find anywhere in admin, or in the code to determine that is the region where this block should appear.
What could I be missing?
Comment: Drupal 7 or 8? I'd guess that the block is being added programmatically somewhere.
Answer: This happened to me once, turns out it was added through the context module. So check if your site has it.
Else, could have been added through the Panels module or the Display Suite module. So check if you have any of these modules also.
If you have non of the above modules are installed then maybe it was added via a template file. So check your template files in your theme's template folder.
Last but not least, perhaps through a preprocess function? check your template.php file if on D7 or themename.theme file if you're on D8.
Good luck detective.
Comment: Thank you, it was hidden away in the context module as you suggested. I never would have thought to look in there


Sufficient statistic function for $f(x) = \theta x^{-2}, \; \; 0 < \theta \leq x < \infty$.

Question: Exercise :

Let $X_1, \dots, X_n$ be a random sample from a distribution with probability density function $f(x) = \theta x^{-2}, \; \; 0 < \theta \leq x < \infty$, where $\theta$ unknown parameter.
(i) Check if the given distribution belongs to the Exponential Family of Distributions.
(ii) Find a sufficient statistic function $T$ of $\theta$.

Attempt :
(i) It is :
It does not belong to the Exponential Family of Distributions, since the support of $X$ depends on $\theta$.
(ii) To try and find a sufficient statistic function, we must write $p(x|\theta)$ in the form of $G(t,\theta)H(x)$.
Thus :
$$p(x|\theta) = \prod_{i=1}^n \theta x_i^{-2} \mathbb{I}_{[\theta, + \infty]}(x_i)$$
How should I continue to find a sufficient statistic function from here on?
Comment: Cross posting on two different SE-sites is against the rules. You exacerbated the problem by not crosslinking the two versions. The CV version has a higher upvoted answer, so I am migrating this there. The CV-moderators can then merge (and later remove this comment).
Answer: Using the factorization criteria you have
$$
\prod_{i=1}^n \theta x_i^{-2}I[x_i\ge \theta]=\theta^nI[x_{(1)}\ge\theta]\times \prod_{i=1}^n\frac{1}{x_i^2}I[x_i\ge x_{(1)}]=g(\theta ; T(X))H(X),
$$
i.e., the MSS is $T(X)=X_{(1)}=\min\{X_1,...,X_n\}$. It is minimal as it one dimensional like $\theta$. The last step follows from the fact that $\prod_{i=1}^nI[x_i \ge \theta] = I[x_{(1)} \ge \theta]\prod_{i=2}^nI[x_i \ge x_{(1)}]$.
And note that as the support of $X$ depends on $\theta$, thus it cannot belong to the exponential family.
Another approach is to verify that $X_{(1)}$ is the MLE, hence it must be a function of the sufficient statistics, and as $X_{(1)}$ is the identity function and it is one dimensional then it is the minimal sufficient statistic.
Comment: Presumably you are saying $I[x_i\ge x_{(1)}]=1$ for all $i$.  And I think you have shown $\min\{X_1,...,X_n\}$ is a sufficient statistic (as requested) rather than a minimal sufficient statistic
Comment: @Henry It is minimal as $x_{(1)} \in \mathbb{R}$.
Comment: What exactly is $X_{(1)}$ and how did you yield that result ?
Comment: @Rebellos I edited the answer. Hope it helps
Comment: The expression that you yield has the factor $x_{(1)}$ in both parts, thus it cannot be a sufficient statistic function (I think), since you need to have the $x_i$ in a different place such as $H(x)$.
Comment: @Rebellos Please see the edited answer. Hope it clear now


Greatest Integer Function linear equation

Question: Given that $2[x]=x+2(x)$, $[x]$ if the Greatest Integer Function and $(x)$ is the fractional part of $x$, find the value (s) of $x$.
I tried replacing $(x)=x–[x]$ but for an equation in $x$ and $[x]$. How do I proceed???
Answer: Let $x = n + r$ where $n \in \mathbb{Z}$ and $0 \le r \lt 1$. Then $[x] = n$ and $(x) = r$, so your equation becomes $2n = (n + r) + 2r \; \Rightarrow \; n = 3r$. Since $0 \le 3r \lt 3$, this gives $3$ choices for $n$ of $0, 1, 2$. You can then determine the matching values of $r$ and $x$.
Comment: Thanks!!! Really helpful
Comment: @PranavGupta53535 You are welcome. Doing this type of substitution is the first thing I would try, and it often works to solve the problem
Comment: Yeah... I forgot to use the inequality in (x")
Answer: The equation you get by putting $(x)=x-[x]$ is $4[x]=3x$.
Now I believe the best approach would be to graph $[x]$ and $\frac34x$, both of which are pretty basic and easy to plot.
Search for the intersection points which are the required solutions.
Comment: Thanks bro... Appreciate the help


Get the last 2 rows of a table while grouping one of the column. MySQL

Question: Consider Facebook. Facebook displays the latest 2 comments of any status. I want to do something similar.
I have a table with e.g. status_id, comment_id, comment and timestamp.
Now I want to fetch the latest 2 comments for each status_id.
Currently I am first doing a GROUP_CONCAT of all columns, group by status_id and then taking the SUBSTRING_INDEX with -2.
This fetches the latest 2 comments, however the GROUP_CONCAT of all the records for a status_id is an overhead.
SELECT SUBSTRING_INDEX(GROUP_CONCAT('~', comment_id,
                                    '~', comment,
                                    '~', timestamp)
                        SEPARATOR '|~|'),
        '|~|', -2)
FROM commenttable
GROUP BY status_id;

Can you help me with better approach?
My table looks like this -
status_id comment_id comment timestamp
1          1    xyz1     3 hour
1          2    xyz2     2 hour
1          3    xyz3     1 hour
2          4    xyz4     2 hour
2          6    xyz6     1 hour
3          5    xyz5     1 hour

So I want the output as -
1          2    xyz2     2 hour
1          3    xyz3     1 hour
2          4    xyz4     2 hour
2          6    xyz6     1 hour
3          5    xyz5     1 hour

Comment: Read this: http://stackoverflow.com/questions/573646/mysql-select-from-n-last-rows
Answer: Here is a great answer I came across here:
select status_id, comment_id, comment, timestamp
from commenttable
where (
   select count(*) from commenttable as f
   where f.status_id = commenttable.status_id
         and f.timestamp < commenttable.timestamp
) <= 2;

This is not very efficient (O(n^2)) but it's a lot more efficient than concatenating strings and using substrings to isolate your desired result.  Some would say that reverting to string operations instead of native database indexing robs you of the benefits of using a database in the first place.
Comment: This is not tested, it could have some typos.
Answer: After some struggle I found this solution -
The following gives me the row_id -
  SELECT a.status_id,
         a.comments_id,
         COUNT(*) AS row_num
  FROM comments a
       JOIN comments b
       ON a.status_id = b.status_id AND a.comments_id >= b.comments_id
  GROUP BY a.status_id , a.comments_id
  ORDER BY row_num DESC

The gives me the total rows -
SELECT com.status_id, COUNT(*) total
FROM comments com
GROUP BY com.status_id

In the where clause of the main select -
row_num = total OR row_num = total - 1

This gives the latest 2 rows. You can modify the where clause to fetch more than 2 latest rows.


Using Logic Laws to prove $p \leftrightarrow q \equiv (p\lor q)\to(p \land q)$

Question: I am trying to prove that

$p \leftrightarrow q \equiv (p\lor q)\to(p \land q)$

and am really lost in the steps to solve this.
So far I have:

$p \leftrightarrow q \equiv (p\to q)\land(q\to p) \qquad$|equivalence
   $p \leftrightarrow q\equiv (\neg p\lor q)\land(\neg q\lor p) \qquad$|implication

and I am not sure how to proceed from here. Any advice would be greatly appreciated!
edit:
Thanks to lord farin i now have

≡ (~p ∨ q) ∧ (q → p)  Implication Law
  ≡ (q → p) ∧ (~p ∨ q)  Commutative Law
  ≡ (q → p ∧ ~p ) ∨ (q → p ∧ q) Distributive Law
  ≡ (~p ∧ q → p) ∨ (q ∧ q → p) Commutative Law

but i am unsure of how to get there still.
Comment: i forgot to add that the first step

p↔q≡(p→q)∧(q→p)p↔q≡(p→q)∧(q→p)|equivalence

is mandatory and i am to work from there to prove it
Answer: The trick is to expand only one of the two implications materially at first:
$$\begin{align*}
(p\to q)\land(q \to p) &\equiv (\neg p \lor q)\land (q\to p)\\
&\equiv \underbrace{(\neg p \land q \to p)}_{\downarrow} \lor \underbrace{(q \land q\to p)}_\downarrow& & \text{distribution}\\
&\equiv \underbrace{(\neg p \land \neg q) \hspace{1.5em} \lor\quad(p \land q)}_\downarrow\\
&\equiv \hspace{2em}(p \lor q) \to (p \land q)
\end{align*}$$
I'll leave it up to you to take care of the transitions represented by the arrows.

Additional details: For the first two, you can rewrite the conditionals, then use distribution of the $\land$. For e.g. the first, this will leave $(\neg p \land \neg q) \lor (\neg p \land p)$, the second term of which is always false. Thus the whole expression is equivalent to $\neg p \land \neg q$.
A similar approach works for $q \land q \to p$.
Comment: im really sorry but can you please expand on the first arrow transitions? Ive spent a few hours to no avail on how to get it there.
Comment: @DamienLim See edit.
Answer: \begin{align}
(p\lor q)\to(p \land q) & \equiv (p\lor q)'\lor(p \land q)\\
 & \equiv (p'\land q')\lor(p \land q)\\
 & \equiv (p'\lor(p \land q))\land (q'\lor(p \land q))\\
 & \equiv ((p'\lor p) \land (p'\lor q))\land ((q'\lor p) \land (q'\lor q))\\
 & \equiv (T \land (p'\lor q))\land ((q'\lor p) \land T)\\
 & \equiv (p'\lor q)\land (q'\lor p)\\
 & \equiv (p\rightarrow q)\land (q\rightarrow p)\\
 & \equiv p \leftrightarrow q
\end{align}
Comment: To downvoter: could you please explain what is wrong with this answer?
Answer: $(1)$ equivalence consists of two implications in opposite directions
$(2)$ it is enough to negate just one of the two implications in order to negate the equivalence
$(3)$ truth can imply no lie, therefore, to negate an implication, the second predicate must be negated, while the first stays unchanged
Having in mind these simple facts, no other tool is required.
$$\neg(\neg P)\equiv P$$
$$\neg(\neg (p\iff q))\equiv p\iff q$$
$$\neg((p\wedge \neg q)\vee(\neg p\wedge q))\equiv p\iff q$$
Neutral for disjunction:
$$\neg(((p\wedge \neg q)\vee (q\wedge \neg q))\vee((\neg p\wedge q)\vee (p \wedge \neg p)))$$
Distribution:
$$\neg(((p\vee q)\wedge\neg q)\vee ((p \vee q)\wedge \neg p))\equiv\neg((p\vee q)\wedge(\neg p \vee \neg q))\equiv \neg((p\vee q)\wedge \neg(p\wedge q))$$
Finally:
$$\neg(\neg((p\vee q)\implies(p\wedge q)))\equiv(p\vee q)\implies(p\wedge q)$$
Hope it helps. So, you can see how, using 'primitive' elementary tools, we can transform more complicated statements.
Answer: You could write equivalence as $(p \land q) \lor (\lnot p \land \lnot q)$, which gives us, using commutation and implication law, the result you desire.


Explaining the harmony of Wagner's Wanderer motif

Question: Recently I listened to the Wanderer leitmotif from Wagner's Ring cycle. I was both impressed and perplexed by the motif's harmony. The picture below tries to explain the possible modulations that this motif implies. It's quite pedantic, since I think most perfect cadences weren't necessary, but I wanted to establish the tonality and then modulate to a new key center.
The Wanderer motif: Wagner - Wanderer motif
and the short piece I wrote:

Explanation of symbols:

+M is the Medianté (is it called chromatic mediant in English?), i.e. the III degree chord of a major scale with a major third (e.g., the +M of C major is E major),
oTr is the chord that's relative (r) to T minor (o=minor and T=tonic). To explain it more accurately, the oTr chord of D (major or minor) is F major.
oSr is the same as oTr, where S stands for subdominant. For example, the oSr chord of C (major or minor) is Ab major, i.e., the relative key of F minor (IV of C minor).

Lastly, as I haven't found the above symbols elsewhere except in my Harmony textbook: are there any equivalent symbols to describe these chords in the international music bibliography?
Answer: Interesting exercise!
I see two questions in your text:

"is it called chromatic mediant in English?"

Yes; although the term "chromatic mediant" can mean a few chords, this chord would be one of them. Some theorists (like David Kopp) would call this an "upper sharp mediant," because it's the chord built on the upper mediant and it involves raising pitches.

"are there any equivalent symbols to describe these chords in the international music bibliography?"

You're using Riemannian function labels, which should be understood by someone in academic music theory. But a non-academic in America almost certainly wouldn't recognize them. If you want a more universal system that others will understand, I would recommend using Roman numerals for most of these chords. The B major chord in m. 3, for instance, would be III♯, because it's built on scale-degree 3 (hence III), and the ♯ shows that you raise the chordal third to D♯, thus making it major. The B♭ chord in m. 9, since you're in D major, would be ♭VI6: ♭VI because it's built on the lowered scale-degree 6 in D, and 6 because it's in first inversion.
Comment: After reading stevtomato's comment on the YouTube video, I think the most easy way to understand how it works is the following: First two bars are in A major, the rest are in G major. The sequence has this chord progression: V/V -> IV -> II Neap. -> V. Thus, between the first and the last chord, the music "wanders", since it doesn't go straight from V/V to V. And the whole "magical sound" of this motif is maybe due to the false relation between the D# in the bass on the first chord and the D in the upper voice on the second chord.


Need help finding name of function

Question: My friend sent me an encoded string which I would assume is Java or C#, but since I code in neither of them I could need some help. The string is as follows:
0x579fb13

I thought about it being base 64 or so at first, but the 0x indicates it's hex or something.
Any help appreciated.
Comment: It is a 7 byte hex (91880211). So, what would you like help with?
Comment: How did you manage to decode it, abhinav? I read about decoding hex values without any luck, also tried several online decoders. Any function I can use or tutorial how to do it?
Answer: The 0x would indeed normally indicate that it's hex. That looks like a memory location to me, and as such may be (inadvertently) the pointer to the structure containing the encrypted string.

Need help finding name of function


Levar dados do QR Code para meus campos

Question: Estou fazendo a leitura de um QR Code conforme código abaixo:
// Botão para abrir câmera e usar o QR Code (Irá abrir a Store para baixar um app nativo)
    btnQR = (Button) findViewById(R.id.btnQR);
    btnQR.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent("com.google.zxing.client.android.SCAN");
            intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
            startActivityForResult(intent, 0);
        }

        public void onActivityResult(int requestCode, int resultCode, Intent intent) {
            if (requestCode == 0) {
                if (resultCode == RESULT_OK) {

                    String contents = intent.getStringExtra("SCAN_RESULT");
                    String format = intent.getStringExtra("SCAN_RESULT_FORMAT");

                    // Handle successful scan

                } else if (resultCode == RESULT_CANCELED) {
                    // Handle cancel
                    Log.i("App","Scan unsuccessful");
                }
            }
        }

        private final String TAG = MainActivity.class.getSimpleName();
        private CompoundBarcodeView barcodeView;

        private BarcodeCallback callback = new BarcodeCallback() {
            @Override
            public void barcodeResult(BarcodeResult result) {
                if (result.getText() != null) {
                    barcodeView.setStatusText(result.getText());
                }

                String barcode = "35151022986022000105590000400630036591770797|20151013131745|21.26|";
                String[] resp = barcode.split("\\|");

                String cnpj = resp[0].substring(6, 20); // são 14 dígitos, iniciado da posição 7
                String coo = resp[0].substring(30, 35); // supondo que tenham sempre 6 dígitos
                String data = resp[1].substring(0, 5); // 6 primeiros dígitos corresponde a data
                String total = resp[2];

                System.out.println(cnpj);
                System.out.println(coo);
                System.out.println(data);
                System.out.println(total);

                try {
                    Date date = new SimpleDateFormat("yyyyMMdd").parse(data);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                String dataFormatada = new SimpleDateFormat("dd/MM/yyyy").format(data);

            }

            @Override
            public void possibleResultPoints(List<ResultPoint> resultPoints) {
            }
        };
    });

Preciso que, ao ler o QR Code, volte para min ha aplicação já com os campos preenchidos.
Campos:
- CNPJ
- Data
- COO
- Total

Comment: Pode postar a string ou parte dela na pergunta, para vermos se tem algum padrao para tratar e separar como você quer.
Comment: Adicione na pergunta clicando em [edit] para ela ficar mais completa.
Comment: Aparentemente tem um padrao nessa string, são separados por `|`. Porém nesse trecho que você postou, só tem 3 sequencias separadas, qual a ordem das informações?
Comment: **35151022986022000105590000400630036591770797|20151013131745|21.26|** - Tem mais, porém preciso desse começo só
Comment: Nessas 3 sequências tem os 4 campos que preciso. o CNPJ começa na casa 7 (22.986.022/0001-05), depois o COO, na casa 31 (003659), depois a data, no segundo bloco (13/10/2015), e por fim, o valor, no último bloco (21.26)
Answer: Você pode utilizar o Split para separar a String em um array usando um delimitador, no exemplo que você postou, aparenetemente seu delimitador é o "|", portanto faça algo assim:
String[] resp = result.getText().split("|");

Ai basta percorrer este array e coletar as informações que você precisa.
Me parece que o primeiro campo é uma chave de NFe, correto!?
Então o CNPJ está na posição 7 com 14 digitos, para pegar com Substring use:
String CNPJ = resp[0].subsring(7, 14);

Comment: String[] resp = result.getText().toString().split("|");
Comment: obrigado pela resposta. No **resp[0]** ele tá me falando `Array type expected; found: 'java.land.String`. Poderia me ajudar nisso, por favor?
Comment: O programa rodou, mas ainda não trouxe os dados para meu campo...creio que tenho que apontar para qual campo tem que ir. Por exemplo, costumo usar muito o `findViewById`, tem algo similar?
Comment: Oque acontece em modo de depuração?
Comment: Obrigado @HiagoSouza pelas edições!
Comment: Disponha @CelsoMarigoJr, não conssegui mudar uma parte, mas você pode onde esta "String CNPJ = resp[0].subsring(7, 14);" na verdade é "String CNPJ = resp[0].substring(7, 14);"... faltou um "T"
Comment: Assim, erro ele não mostra nada. Ele coleta a string do QR Code, mas quando fecha o leitor, meu campo ainda está vazio. Nessa solução do @CelsoMarigoJr eu meio que não informo qual meu campo que deverá ser preenchido, não?
Comment: Qual a necessidade de se passar a string para um vetor pra depois usar substring? Não seria mais pratico pegar direto da string, já que o OP já sabe onde pegar as substrings?
Comment: @MarioPueblaJunior "txtView" essa variavel esta referenciando o textView que você esta querendo colocar a resposta correto? Caso seja tente colocar txtView.setText( CNPJ );
Comment: @HiagoSouza na verdade essas duas linhas de comando eu coloquei só pra testar e ver se o app traria a String gigante que ela trouxe.
Comment: @DiegoFelipe Tem alguma sugestão então no código?
Comment: @MarioPueblaJunior basta você tratar a string diretamente, usando substring para pegar os dados que você me disse em resposta na sua pergunta, como foi sugerido neste código.
Comment: @DiegoFelipe Coloquei assim, vê se tem algo de errado: `EditText cnpj = (EditText) findViewById(R.id.cnpj); cnpj.setText(result.getText().substring(7,14);`. Não aconteceu nada, tem alguma coisa errada?
Comment: @HiagoSouza olha a resposta acima
Comment: Vou postar a resposta @MarioPueblaJunior
Answer: Complementando a resposta do @CelsoMarigoJr, você pode usar o método split para facilitar tratar os dados, porém, há uma correção a se fazer: o método dito não irá funcionar corretamente sem que o caractere | seja escapado, pois o método split espera como um de seus parâmetros uma expressão regular, e o pipe é um caractere especial de ER, conforme esta resposta no SOEn.
Então altere:
String[] resp = result.getText().split("|");

para:
String[] resp = result.getText().split("\\|");

Fazendo um teste com a string informada por você nos comentários, veja o resultado:
String barcode = "35151022986022000105590000400630036591770797|20151013131745|21.26|";
String[] resp = barcode.split("\\|");
String cnpj = resp[0].substring(6, 20); //são 14 digitos, iniciado da posicao 7
String coo = resp[0].substring(30, 35); // supondo que tenham sempre 6 digitos
String data = resp[1].substring(0, 5); // 6 primeiros digitos sao da data
String total = resp[2];

Veja aqui o código funcionando.
Na data você pode usar a classe SimpleFormatDate para formatar a data e exibi-la de forma mais amigável.
Date date = new SimpleDateFormat("yyyyMMdd").parse(data);
String dataFormatada = new SimpleDateFormat("dd/MM/yyyy").format(date);

Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/30877/discussion-between-mario-puebla-junior-and-diego-felipe).

Levar dados do QR Code para meus campos


Is there a way to add an example for plain text content type in OpenAPI?

Question: Using OpenAPI 3.x.x, is there a way to add an example of request body that accepts plain text format?
/path/to/api/:
  ... more properties
  requestBody:
    required: true
    content:
      text/plain:
        schema:
          $ref: '...path/to/schema'
        example:
          value:

I need to add example of a string input "hello", but it expects a JSON object.
Answer: The OAS 3.x.x Example schema indicates the value property accepts any JSON Schema primitive value since constraints are undefined. This can be interpreted as type: ["object", "array", "boolean", "string", "number", "integer", null]
The recommended keyword for the latest version of OAS is examples vs example.
https://github.com/OAI/OpenAPI-Specification/blob/main/schemas/v3.0/schema.yaml#L394-L417

MediaType:
    type: object
    properties:
      schema:
        oneOf:
          - $ref: '#/definitions/Schema'
          - $ref: '#/definitions/Reference'
      example: {}
      examples:
        type: object
        additionalProperties:
          oneOf:
            - $ref: '#/definitions/Example'
            - $ref: '#/definitions/Reference'
      encoding:
        type: object
        additionalProperties:
          $ref: '#/definitions/Encoding'
    patternProperties:
      '^x-': {}
    additionalProperties: false
    allOf:
      - $ref: '#/definitions/ExampleXORExamples'
Example:
    type: object
    properties:
      summary:
        type: string
      description:
        type: string
      value: {}
      externalValue:
        type: string
        format: uri-reference
    patternProperties:
      '^x-': {}
    additionalProperties: false

The schema for text/plain can be only described as type: string, not a schema object. Using a $ref would only be viable if the referenced schema was defined as a type: string.
Thus, the value for a text/plain request can be defined as a string value.
content:
    text/plain
      schema:
        type: string
      examples:
        test_request:
          value: "hello"


Creating a View of nodes with field for workbench moderation state without showing every revision?

Question: I am trying to create a table view of nodes with fields for node title and moderation state. (There are other fields but I'm omitting them for simplicity).
Currently, it's displaying a new table row for every single revision of the node. I only want to see one row per node, whatever the current state is. Grouping is not sufficient, since there are fields that are not the same across revisions.
Answer: Immediately after asking this question, I realized there is a filter criterion that can be added for this.
Workbench Moderation: Current can be set to filter based on whether a revision is the current one, and all previous ones can be excluded.
This will also exclude nodes that haven't been created or edited since the enabling of Workbench Moderation for their node type but will include newly created or edited ones.


Seemingly acceptable iptables rule blocking NIS (ypbind) from operating

Question: I am not an iptables expert.
I have a use case to block all outgoing traffic that does not destined for either 10.0.0.0/8 or 220.127.116.11/16.  I have two NIS servers (10.57.132.11, 10.57.132.40).  I generated the below iptables ruleset which I thought would work, but if I run service iptables start, I am unable to also get ypbind to load.  It times out on hitting the two NIS servers.  I see nothing in the logs other than a timeout.
# Generated by iptables-save v1.4.7 on Fri Jul 17 11:08:39 2015
*filter
:INPUT ACCEPT [78622:10507056]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-I OUTPUT -d 10.57.132.11 -j ACCEPT
-I OUTPUT -d 10.57.132.40 -j ACCEPT
-I OUTPUT -d 184.108.40.206/16 -j ACCEPT
-I OUTPUT -d 10.0.0.0/8 -j ACCEPT
-P OUTPUT DROP

COMMIT
# Completed on Fri Jul 17 11:08:39 2015

Any thoughts on what I'm doing wrong?  Thanks, Jack.
UPDATE: To clarify, ypbind binds when iptables is off, but won't bind when I turn the above ruleset on.  Since it is only filtering OUTPUT and those rules seem correct, I don't understand the problem and I can't find anything useful in the logs.
Comment: The obvious one would be that portmapper isn't running?
Comment: Portmapper is running normally: rpcbind (pid  1342) is running...
Comment: Are your name servers within the ip-ranges specified?
Comment: Yes - all the NS are in that 10.57.132.0 network.
Comment: Time to put in a logging rule.
Comment: Thanks @MichaelHampton - that was the hint I needed to solve it (see my answer below)!
Answer: tl;dr: iptables is really literal, don't forget localhost rules.
Okay! Got it.  Michael Hampton gave me the idea to use a logging rule (this was my first time).  So I did the following:
 Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  10.0.0.0/8           anywhere
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED

Chain FORWARD (policy DROP)
target     prot opt source               destination

Chain OUTPUT (policy DROP)
target     prot opt source               destination
ACCEPT     all  --  anywhere             10.0.0.0/8
ACCEPT     all  --  anywhere             126.96.36.199/16
ACCEPT     all  --  anywhere             nis1.example.com
ACCEPT     all  --  anywhere             nis2.example.com
LOGGING    all  --  anywhere             anywhere

Chain LOGGING (1 references)
target     prot opt source               destination
LOG        all  --  anywhere             anywhere            limit: avg 2/min burst 5 LOG level warning prefix `IPTables-Dropped: '
DROP       all  --  anywhere             anywhere

From there, I started iptables and then attempted to restart ypbind and immediately saw this:
Jul 22 22:53:04 host1 ypbind[9844]: Unable to register (YPBINDPROG, YPBINDVERS, udp).
Jul 22 22:53:31 host1 kernel: IPTables-Dropped: IN= OUT=lo SRC=127.0.0.1 DST=127.0.0.1 LEN=40 TOS=0x00 PREC=0x00 TTL=64 ID=1476 DF PROTO=TCP SPT=18660 DPT=7606 WINDOW=2305 RES=0x00 ACK URGP=0
Jul 22 22:53:50 host1 ypbind: NIS server for domain example is not responding.
Jul 22 22:54:01 host1 kernel: IPTables-Dropped: IN= OUT=lo SRC=127.0.0.1 DST=127.0.0.1 LEN=40 TOS=0x00 PREC=0x00 TTL=64 ID=1506 DF PROTO=TCP SPT=18660 DPT=7606 WINDOW=2305 RES=0x00 ACK URGP=0

OH NO! It's blocking localhost.  I added that to the output rule and got:
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  10.0.0.0/8           anywhere
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED

Chain FORWARD (policy DROP)
target     prot opt source               destination

Chain OUTPUT (policy DROP)
target     prot opt source               destination
ACCEPT     all  --  localhost            localhost
ACCEPT     all  --  localhost            localhost
ACCEPT     all  --  localhost            localhost
ACCEPT     all  --  localhost            localhost
ACCEPT     all  --  anywhere             10.0.0.0/8
ACCEPT     all  --  anywhere             220.127.116.11/16
ACCEPT     all  --  anywhere             nis1.example.com
ACCEPT     all  --  anywhere             nis2.example.com
LOGGING    all  --  anywhere             anywhere

Chain LOGGING (1 references)
target     prot opt source               destination
LOG        all  --  anywhere             anywhere            limit: avg 2/min burst 5 LOG level warning prefix `IPTables-Dropped: '
DROP       all  --  anywhere             anywhere

One more ypbind restart and
Jul 22 22:54:38 host1 ypbind: NIS domain: example, NIS server: nis1.example.com

There you have it!


ESXi Connection issue

Question: We have a server currently running VMware ESXi. The VMSphere client is having some issues connecting; giving the "Can not establish a secure connection" when clicking on Console as well as both lag issues when trying to perform any task such as clicking on tabs and windows. On top of this we are getting "Error connecting: A secure connection to the host could not be established. Try again?" every few moments.
Does anyone know what could be causing this problem? Is it on our side or on the server hosting side? Our server host is "Joe's Data Center" so if anyone has any idea on their reputation as well please feel free to input your experience.
Answer: Sounds like network bandwidth or latency problems.  Use vSphere client to look at the network topology and make sure that your vcenter NIC is not also used for data traffic.  I'm not sure how much you can see in the free version if you're using that, but using the same physical NIC for vcenter as you use for a high traffic VM will do this.  You can ping the service console or use a scp tool that shows traffic to see if there's latency or bandwidth clogs on the service console nic.
Install a small WinXP VM in your ESXi and load vsphere client.  Can it connect reliably?  If not, you need to know about the network topology to know what that means exactly, but it will rule out the internet as the problem.  If it does disconnect, does it disconnect in lockstep with your local vsphere client?
Answer: The console connection is very bandwidth intensive so I'm not surprised you are having slowness issues with that.  Our console connection is currently a 1GB connection but when it was 100MB we had some slowness and an occasional disconnect.
I would recommend contacting Joe's Data Center about not being able to establish a secure connection.
Answer: Please try this command
Log into console via ssh run this command
Service mgmt-vmware restart and try to connect via vsphere
Comment: SSH for ESXi is not enabled by default or recommended by VMware.

ESXi Connection issue


how to perform post method in windows 8 metro?

Question: I have followed the HttpClient samples but couldn't figure it out how to post a method with 2 parameters.
Below is what I tried but it return bad gateway error:
        private async void Scenario3Start_Click(object sender, RoutedEventArgs e)
    {
        if (!TryUpdateBaseAddress())
        {
            return;
        }

        Scenario3Reset();
        Scenario3OutputText.Text += "In progress";

       string resourceAddress =  "http://music.api.com/api/search_tracks";
        try
        {
            MultipartFormDataContent form = new MultipartFormDataContent();
        //    form.Add(new StringContent(Scenario3PostText.Text), "data");
            form.Add(new StringContent("Beautiful"), "track");
            form.Add(new StringContent("Enimem"), "artist");

            HttpResponseMessage response = await httpClient.PostAsync(resourceAddress, form);
        }
        catch (HttpRequestException hre)
        {
            Scenario3OutputText.Text = hre.ToString();
        }
        catch (Exception ex)
        {
            // For debugging
            Scenario3OutputText.Text = ex.ToString();
        }
    }

I looked all over the internet, but couldn't find any working examples or documents that show how to perform the http post method. Any materials or samples would help me a lot.
Comment: Are you sure the server is expecting `multipart/form-data`? Have you tried `ByteArrayContent` that contains something like `artist=Enimem&track=Beautiful`?
Comment: I take it music.api.com isn't real, so I can't verify if it expects form data. But in general rest apis do not expect form-data. Form-data primarily used for user submitted forms and file uploads.
Comment: hmm, maybe I was wrong on the multipart/form, because that was the sample I found. If it's byteArray, how can i pass the parameters in? thanks guys
Answer: Try FormUrlEncodedContent instead of MultipartFormDataContent:
var content = new FormUrlEncodedContent(
    new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("track", "Beautiful"),
        new KeyValuePair<string, string>("artist", "Enimem")
    }
);

Answer: I prefer to take the following approach where you set the POST data into the request content body.  Having to debug it is much easier!
Create your HttpClient object with the URL you're posting to:
string oauthUrl = "https://accounts.google.com/o/oauth2/token";
HttpClient theAuthClient = new HttpClient();

Form your request with the Post method to your url
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, oauthUrl);

Create a content string with your parameters explicitly set in POST data format and set these in the request:
string content = "track=beautiful" +
  "&artist=eminem"+
  "&rating=explicit";

request.Method = HttpMethod.Post;
request.Content = new StreamContent(new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)));
request.Content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

Send the request and get a response:
try
{
    HttpResponseMessage response = await theAuthClient.SendAsync(request);
    handleResponse(response);
}
catch (HttpRequestException hre)
{

}

Your handler will be called once the request returns and will have response data from your POST.  The following example shows a handler that you could put a breakpoint into to see what the response content is, at that point, you could parse it or do whatever you need to do with it.
public async void handleResponse(HttpResponseMessage response)
{
    string content = await response.Content.ReadAsStringAsync();

    if (content != null)
    {
        // put your breakpoint here and poke around in the data
    }
}


Windows phone (IE 10) won't play html5 video (through redirection)

Question: I have an issue with HTML5 video occurring on Windows Phone 8.0 (IE 10). The exact model I can manually reproduce it on is a Nokia Lumia 521.
So I have an HTML5 video on my page:
<video poster="http://cdn.example.com/img.png" controls>
    <source src="http://example.com/proxy">
</video>

At this point, the video won't play and the poster image won't show.
The poster image is a direct link to our CDN. The source src is pointing to a proxy on our server who'll redirect to a video resource on our CDN. Here are the headers:
HTTP/1.1 302 Found
Date: Wed, 22 Apr 2015 00:22:59 GMT
Content-Type: video/mp4
Content-Length: 0
Connection: close
Server: Apache
Cache-Control: private
Location: http://cdn.example.com/resource.mp4
Vary: User-Agent

For some reason, if I load the mp4 directly in Windows Phone, it'll open the video app and play the content correctly.
It looks like something is going wrong when redirecting the video source through a 302.

You can reproduce this issue on yelp http://m.yelp.com/biz_photos/tropisue%C3%B1o-san-francisco-3?select_video=DoP8vwCSm2AcTp3RvBwybg
Comment: Since the file type can't be inferred from the proxy src, you might try adding a type attribute to the source. Like this: .
Comment: @TimHayes That did work. Mind posting as answer so I can accept it?
Answer: Since the file type can't be inferred from the proxy's src extension, you might try adding a type attribute to the source. Like this:
<video poster="http://cdn.example.com/img.png" controls>
    <source src='example.com/proxy' type="video/mp4">
</video>


How do I create a merge request for a project?

Question: I'd like to create a merge request for a drupal.org project. I found a page on drupal.org titled Issue forks & merge requests which seems to address this but I'm not really getting anywhere. The page says:

On an issue page, make sure the fork is created and you have access.

If the fork has not been created yet, click "Fork {project}"
If you do not have push access yet, click "Get push access"
If you see "✓ You have push access," you're all set!

The only place I could find a "Fork" button was on https://git.drupalcode.org/project/project_name/-/forks. But when I click on that I see just see a namespace with my name, and a greyed out "select" button, which, if I hover over it, displays "You have reached your project limit". But I think I'm in the wrong place anyway.
The instructions start with "...on the issue page" so I created an issue on drupal.org for the project, on the issue page there are no links that mention "fork" anywhere to be seen.
What am I doing wrong?
Comment: I'm not sure, but maybe the ability to fork a project needs to be enabled by every project's maintainer manually first?
Answer: As said in Issue forks & merge requests drupal.org only implements (so far) issue forks and merge requests related to those issue forks. Issue forks are still in development and enabled only on those projects that opted-in, a list of which is available in Opt-in core issues into the Drupal.org Issue Forks and Merge Requests Beta: The list doesn't include the projects maintained from the Drupal Association, for which issue forks have been directly enabled from a Drupal Association employee.
The plan is making them available on all projects on November 10, 2020.
When issue forks are enabled, an issue opened for that project contains a button as in the following screenshot, taken from Show commit activity for issue fork branches without merge requests.

When an issue fork has been created, there will be a different button, as in the following screenshot.

I didn't watch at the code used on drupal.org, but I expect the code checks users have the Git user role on drupal.org, which is given to the users who accepts the Git access agreement, or a Git account on Drupal.org, before allowing them to create an issue fork or obtain push access on an issue fork.

Merge requests aren't tested on DrupalCI, until Test merge requests made in GitLab with DrupalCI is marked as fixed. That could happen before, or after, issue forks are enabled on every project.
As for today, December 24, 2020, issue forks and merge requests have been enabled on every project hosted on drupal.org. Merge requests are tested by the DrupalCI instance running for drupal.org.


My html form clears when I hit submit and try to check for form validation

Question: When I run my code on chrome and try and enter each input one at a time, when I hit submit, all of my input clears! Help me please
Javascript code :
function data_validation()
{
    var sfn = form1.sfn.value;
    var sln = form1.sln.value;
    var sid = form1.sid.value;
    var grad = form1.grad.value;

    var RegExpText = /^[A-Z a-z]+$/;
    var RegExpId = /^[0-9]{6}$/;

    if (!RegExpText.test(sfn))
    {
        alert("Please enter your first name");
        document.form.sfn.focus();
        document.form.sfn.select();
        return false;
    }
    else if(!RegExpText.test(sln))
    {
        alert("Please enter your last name");
        document.form.sln.focus();
        document.form.sln.select();
        return false;
    }
    else if(!RegExpId.test(sid))
    {
        alert("Please enter a 6-digit Student ID");
        document.form.sid.focus();
        document.form.sid.select();
        return false;
    }
    grad = -1;
    for(i=0;i<document.client.grad.length; i++)

        if(document.client.grad[i].checked)
    {
        grad = i;
        var gradYear = document.client.grad[i].value;
    }

    if(grad == -1)
    {
        alert("Please select a grade level.");
        return false;
    }

    else if ((form1.php.checked == "") && (document.client.js.checked == "")     && (document.client.c.checked == ""))
    {
        alert("Please select at least one programming language.");
        form1.php.focus();
        return false;
    }
    else
    {
        alert("Thank you for submitting!");
        return true;
    }
}

Here is the HTML: I have tried adding return false to onSubmit and I have also tried many other things. My teacher never taught this and I can't find another answer online that works for me.
<!DOCTYPE html>

<link href="../common/stylesheet.css" type="text/css" rel="stylesheet">

<meta charset="utf-8">
<title>Form Validation</title>

    <form name = "form1" id = "form1" onsubmit = "return data_validation();" method="post">

Student Skills Form

            Student First Name:
            <input name="sfn" size="20" >

            Student Last Name:
            <input name="sln" size="20" >

            Student ID:
            <input name="sid" size="6" maxlength="6">

            Programming Languages

                <input type="checkbox" value="PHP" name="php">PHP

                <input type="checkbox" value="JS" name="js">JavaScript

                <input type="checkbox" value="C++" name="c">C++

            Expected Date of Graduation:

                <input type="radio" name="grad" value="2015">2015

                <input type="radio" name="grad" value="2016">2016

                <input type="radio" name="grad" value="2017">2017

                <input type="radio" name="grad" value="2018">2018

                <input type="submit" name="s" value="Send Data">
                <input type="reset" name="r" value="Clear Data">

    </form>

Comment: You haven't specified an `action` for the form, so it posts to the current URL, and that reloads the page.
Answer: It is always good to separate the process of validating form data and the submitting.
In your code, you do them together. The default behavior of submit button is to upload all your form data and clean all the input data, so it behaves correctly as it is meant to be.
What you need to do to make it work is to add event onto those fields.
You can use jQuery .blur() to do that.
.blur() method will be triggered when the field lost focus. So here is where you should trigger your validation process.
I hope it helps.
Cheers,

Update:
Add events to the fields which you need to validate.
For example, you need to do some validation on the sln textbox.
$('input[name="sln"]').on("blur", function(){
.....Your validation here...........
});
By the way, where are the IDs for those input components???(they only have names....)
Comment: What fields do I need to add events too?


Three.js how check collision with shader heightmap

Question: How check collision with terrain mesh in this example http://stemkoski.github.io/Three.js/Shader-Heightmap-Textures.html
All intersection as plane
Answer: Can't check for collision using raycaster as usual because the geometric object is actually a plane, which just appears different because of the shader code.  The best work-around is to write a method that generates geometry object based on image texture, then you can remove shader code, and check for intersections as usual.
Comment: Why not simple use the imagedata? more [here](http://stackoverflow.com/questions/15687678/issue-with-terrain-collision-using-three-js).


Get the node ID value after submitting an attached Webform to that node

Question: I have a Webform attached as a field to a specific content type.
After the node is loaded and the Webform is submitted, I am using the below custom webform handler to get the $webform_submission values.
<?php

namespace Drupal\my_custom_module\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;

use Drupal\node\Entity\Node;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Do something when a webform submission is submitted.
 *
 * @WebformHandler(
 *   id = "Do something",
 *   label = @Translation("Do something"),
 *   category = @Translation("any category"),
 *   description = @Translation("Do something"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class customWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  // Function to be fired while submitting the Webform.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Get (Full Name) from (full_name) text element available on the webform.
    $fullnamevalue = $values["full_name"];

However, I would like to get the "nid" of that node from where the Webform is submitted, so I can load this node by nid to use it in my custom code.
How to get the "nid" of that node from where the Webform is submitted ?
Comment: This information is already available via Tokens in your Email/Handlers.

[current-page:url:args] The specific argument of the current page (e.g. 'arg:1' on the page 'node/1' returns '1').
Comment: I am aware of the tokens but I need to do the explained above via a custom code... Can you clarify more on how to use the tokens from inside the custom code ? Thank you
Answer: I have found an answer here: https://www.drupal.org/project/webform/issues/3046808
if ($source_entity = $webform_submission->getSourceEntity()) {
   $nid = $source_entity->id();
}
else {
  $nid = NULL;
}

Answer: I found only the real Node-ID with the referenced webform submission with this code:
$source_entity = $request_handler->getCurrentSourceEntity('webform');
$arrayData = $source_entity->toArray();
$nodeId = intval($arrayData['entity_id'][0]['value']);

$nodeId will be the node where the webform was in.