Twig renders / display only the view path

Question: I'm creating an mvc structure for learning/teaching purpouses and so far I could set up the structure and a controller plus twig as template system.
The structure is:

index.php
controllers/

error.php

inc/

controller_base.php
view_manager.php

views/

.cache/
error/

view.html

So:

index instantiate twig autoloader (and mvc autoloader by spl_register).
index instantiate error controller inheriting controller_base.
controller_base is holding the view_manager.
error call view_manager to display the error/view.html and the only thing I get on the browser is error/view.html.

No errors on the apache log. (error_reporting(E_ALL))
Twig cache files created correctly, but the content doesn't look good to me:
protected function doDisplay(array $context, array $blocks = array()) {
    // line 1
    echo "error/view.html";
}

Anyone knows why, and how can I print the actual view?
Thanks in advance.
Code:
index.php: Declaring autoloaders
function __autoload($class_name)
{
if(file_exists("controllers/$class_name.php")):
    include strtolower("controllers/$class_name.php");
elseif(file_exists("models/$class_name.php")):
    include strtolower("models/$class_name.php");
elseif(file_exists("inc/$class_name.php")):
    include strtolower("inc/$class_name.php");
endif;
}
spl_autoload_register('__autoload');

require_once 'vendor/autoload.php';

Twig_Autoloader::register(); has been avoided cause Twig installation was done by composer.
Adding it doesn't bring any change.
error.php (controller): called method.
public function show($param)
{
    $this->viewMng->display(get_class().$data['view'], array())
}

controller_base.php:
class base
{
    protected $viewMng;

    public function __construct()
    {
        $this->viewMng = new viewmanager();
        }
}

viewmanager.php: whole class
class viewmanager {

    private $twig;
    protected $template_dir = 'views/';
    protected $cache_dir = 'views/.cache';
//  protected $vars = array();

    public function __construct($template_dir = null) {

        if ($template_dir !== null) {
            // Check here whether this directory really exists
            $this->template_dir = $template_dir;
        }

        $loader = new Twig_Loader_String($this->template_dir);
        $this->twig = new Twig_Environment($loader, array(
                        'cache' => $this->cache_dir));
    }

    public function render($template_file, $data = array()) {

        if (!file_exists($this->template_dir.$template_file)) {
            throw new Exception('no template file ' . $template_file . ' present in directory ' . $this->template_dir);
        }

        return $this->twig->render($template_file, $data);

    }

    public function display($template_file, $data) {

        if (!file_exists($this->template_dir.$template_file)) {
            throw new Exception('no template file ' . $template_file . ' present in directory ' . $this->template_dir);
        }
        $tmpl = ($this->twig->loadTemplate($template_file));//print_r($tmpl);
        $tmpl->display($data);
    }
}

view.html:
 Hello

Comment: can you post the code of "error call view_manager to display the error/view.html"?
Comment: Sorry, I've added all the relevant code. If there's something else you want to see, just ask. Thanks for taking a look!
Comment: what happens when you call `echo $this->viewMng->render(get_class().$data['view'], array())`? Also why are there brackets: `$tmpl = ($this->twig->loadTemplate($template_file));` ?
Comment: render function produce exactly the same result.
No reason for the brackets. Probably resulting of different options edited and tried. They will go away at the end, for sure.
Also tried to place the template at the view root folder, same result. It's not a problem on the path cause otherwise it produces an exception.
Edited on the question: doDisplay in the "compiled file" only contains "echo 'error/view.html';". Don't know if this is normal, but maybe it helps solving the problem.
Answer: The problem is based on the loader.
According to the Twig documentation:

Twig_Loader_String loads templates from strings. It's a dummy loader
  as the template reference is the template source code This
  loader should only be used for unit testing as it has severe
  limitations: several tags, like extends or include do not make sense
  to use as the reference to the template is the template source code
  itself.

That's why it only prints the passed in string.
Twig_Loader_String, should be replaced by the proper loader.
In this case it works perfectly well Twig_Loader_Filesystem.
$loader = new Twig_Loader_Filesystem($this->template_dir);

This solve the problem and the MVC structure works completely fine.
Thanks taking a look, guys.


Updating JavaFX BarChart data causes memory leak

Question: I've discovered what I believe is a memory leak in JavaFX (1.8u40 GA and 1.8u60 b10 EA) BarChart triggered by replacing all the data values in the series. This is exasperated by our application which does this several times a second.
Using jvisualvm shows an uncontrolled growth in the number of javafx.scene.layout.StackPane instances which eventually results in an OutOfMemoryError. Styled StackPane nodes are used internally by BarChart for the bars.
I've tried a different strategies to update the list. All exhibit the same issue.
// 1
series.getData().clear();
series.getData().addAll(list);
// 2
series.getData().setAll(list);
// 3
series.setData(list)

Interestingly the example in the Oracle BarChart tutorial updates values by adding all the bars/points first, and then mutating them using XYChart.Data.setYValue(). This could work, but is not convenient for us as the number of data points can vary dynamically.
Specific questions

Is there anyway to avoid this issue, other than a extra logic using the setYValue() approach above.
Have I stumbled across an actual memory leak in JavaFX? or just an artefact of my misuse of the API? Surely freeing internal nodes when data is updated is JavaFX responsibility

Example
public class ChartUpdate extends Application {
    private int clock;
    public static void main(String[] args) {
        launch(args);
    }
    @Override
    public void start(Stage stage) {
        CategoryAxis xAxis = new CategoryAxis();
        NumberAxis yAxis = new NumberAxis(0, 100, 10);
        yAxis.setAutoRanging(false);
        BarChart<String, Number> graph = new BarChart<>(xAxis, yAxis);
        graph.setAnimated(false);
        Series<String, Number> series = new Series<>();
        graph.getData().add(series);
        stage.setScene(new Scene(graph));
        stage.show();

        Timeline timeLine = new Timeline();
        timeLine.getKeyFrames().add(
                new KeyFrame(Duration.millis(500),
                        (e) -> {
                            ObservableList<Data<String, Number>> list = FXCollections.observableArrayList();
                            for (int i = 0; i < 100; i++) {
                                list.add(new Data<>(String.valueOf(i), (clock + i) % 100));
                            }
                            series.setData(list);
                            clock++;
                        }));
        timeLine.setCycleCount(Animation.INDEFINITE);
        timeLine.play();
    }
}

Update (16th April 2015) Raised https://bugs.openjdk.java.net/browse/JDK-8094805 and posted to OpenJFX mailing list
Comment: I think that this bug in fixed in 8u60. But it's a beta version.
Comment: I've had a look in JavaFX JIRA, but I couldn't find the JIRA, do you know the reference?
Answer: In summary this was a genuine issue accepted by JavaFX team and fixed by JDK-8094805 in 8u60
See https://bugs.openjdk.java.net/browse/JDK-8094805 for more detail.


Show that $u, v, w$ are in the span of $\{u+v, 2u+3v, 4v+6w\}?$

Question: I know this has to do with linear combinations, namely that you would set out to solve the following set of equations to show that $c_{1}, c_{2}$, and  $c_{3}$ exist and are not all 0, but I'm unclear as to how I actually solve for those in this case.
That is, I know I should have these equations:
$u = c_{1}(u+v) + c_{2}(2u+3v) + c_{3}(4v+6w)$
$v = c_{1}(u+v) + c_{2}(2u+3v) + c_{3}(4v+6w)$
$w = c_{1}(u+v) + c_{2}(2u+3v) + c_{3}(4v+6w)$
Do you not need to solve for c to do this proof?
Comment: you mean $2u+3v$??
Answer: HINT: Notice that $(2u+3v)-2(u+v)=v$.
Answer: HINT: What is the rank of the following matrix?
$$
\begin{pmatrix}
  1 & 2 & 0 \\
  1 & 3 & 4 \\
  0 & 0 & 6
\end{pmatrix}
$$
Answer: If you write the matrix $\begin{bmatrix}u & v & w\end{bmatrix}$ with $u,v,w$ as columns, then the linear combination $au + bv + cw$ can be written as
$$au + bv + cw = \begin{bmatrix}u & v & w\end{bmatrix} \begin{bmatrix}a \\ b \\ c\end{bmatrix}.$$
Therefore,
$$\begin{bmatrix}u+v & 2u+3v & 4v+6w\end{bmatrix}
=
\begin{bmatrix}u & v & w\end{bmatrix}
\begin{bmatrix}1 & 2 & 0\\1 & 3 & 4\\0 & 0 & 6\end{bmatrix}.
$$
Now $u,v,w$ are linear combinations of $u+v, 2u+3v, 4v+6w$ if and only if there is some $3 \times 3$ matrix $A$ such that
$$
\begin{bmatrix}u & v & w\end{bmatrix}
=
\begin{bmatrix}u+v & 2u+3v & 4v+6w\end{bmatrix}
A
=
\begin{bmatrix}u & v & w\end{bmatrix}
\begin{bmatrix}1 & 2 & 0\\1 & 3 & 4\\0 & 0 & 6\end{bmatrix}
A.
$$
Does such a matrix exist?
Comment: I figured out the solution, but in a different way...why are u, v, w col vectors here?
Comment: Actually they don't have to be: you *could* think of $[u\,\,v\,\,w]$ as a row vector whose elements are vectors, and the matrix manipulations still work. But maybe it's best to avoid that idea if it's confusing.
Answer: The solution I got is as follows:
$u = 3(u+v) + -1(2u+3v) + 0(4v+6w)$
$v = -2(u+v) + 1(2u+3v) + 0(4v+6w)$
$w = \frac{4}3(u+v) + \frac{-2}3(2u+3v) + \frac{1}6(4v+6w)$


set specific time to cron for specific php script

Question: Actually i want all unpublish nodes to be delete automatically whose created date is 2 days ago. I can write php script for that and also include that code in hook_cron api.
but i am confused that my site is set to be run cron after every 3 hours and i want that php script to be run after 24 hours. can i set specific cron time for specific job. i dont want change the site cron job time.
Answer: Set system cron to every 5 minutes, and use Elysia Cron to manage particular tasks:

Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

[NEW IN 2.0] Set the timings and frequencies of each cron task (you can run some jobs every day at a specified hour, other only monthly and so on...). For each task you can simply choose between some frequently used options ("once a day", "once a month" ...), or use a powerful "linux crontab"-like syntax to set the accurate timings. You can even define your frequently used options to speed up site configuration.
Answer: I would suggest you to do it by including condition in your code whether to execute particular part or not in each run.
On first run enter time value in database then in each run check if current time and db time has difference of 24 hrs or more then only execute that part, otherwise just skip it.
Hope it works for you.


Voice leading a plagal cadence

Question: I was wondering if the above plagal cadence in Eb major was correct or not. Also, are the stem directions right? And am I right to assume that I had to write it in only 2 part? or is it actually 4 part?
Comment: A bit TOO small, I think  :-)
Comment: If you add an alto voice to handle the C then the soprano can go from Eb to Gb, which is a smaller jump.
Answer:
The plagal cadence, IV–I, would in fact have A♭–E♭ in the bass. Although your soprano C and G do fit the chords, it's a pretty big leap (a perfect fifth) for the soprano to make. C–B♭ may be better, or perhaps A♭–G (but use the lower octave if you go that route).
Your stem directions are correct.
As for whether this should be a two- or four-part exercise, that depends on the assignment; you'll have to consult your instructor (or the worksheet) for that one. If it is two-part, your instructor might prefer you to use the C and G as you have written to fill out the chords with the root and third. (Just doublecheck what is being asked of you!)
Comment: But if i use Ab to G or C to Bb as you suggested, the upper parts won't be moving in **contrary** motion to the bass. And isn't it necessary for them to move in contrary motion in all cadences?
Comment: It's a good rule of thumb, but it's certainly not required; it's just a rule we give to automatically prevent parallel perfect fifths and octaves.
Comment: Contrary movements are less important than smoother voice leading.
Answer: A plagal cadence in Eb will be an Ab chord followed by an Eb one.   Your bass line is correct.  The melody notes fit the chords.  Beyond that, I'm afraid I can't give you many marks.
If there are going to be two more voices added (this sort of exercise is usually asking for 4-part writing) the stem directions are correct.  But as it stands, with just two voices, the notes in the upper stave should have stems down.  And are those melody notes, with the jump up, REALLY what you'd sing to the 'A-men' at the end of a hymn?
I think the requirement is for something like one of these two possibilities.  (And I'm not doing any MORE of your homework for you!)
Contrary motion helps with a full sound, and can help avoud consecutives.  But don't get obsessed with it.  Particularly in  a plagal cadence with it's feeling of 'settling down' into the tonic chord rather than having a rising leading note.

Voice leading a plagal cadence


Accessing Expression.DebugView from code

Question: I'm creating an expression tree manually like this
var innerAddition = Expression.Add(Expression.Constant(5), Expression.Constant(9));
var mult = Expression.Multiply(innerAddition, Expression.Constant(2));
var top = Expression.Add(Expression.Constant(3), mult);

When I look at DebugView in debug mode, I see 3 + (5 + 9) * 2, which is what I would like to output from my program. I understand this is using the expression tree visualizer. Is there a way to use this from my code?
Thanks!
Comment: I've written a [library which can generate a string from an expression tree in multiple formats](https://github.com/zspitz/ExpressionTreeToString), among them a better C#-style alternative to `DebugView`.
Answer: Here is a simple extension method to get the internal property's value using reflection.
public static string GetDebugView(this Expression exp)
{
    if (exp == null)
        return null;

    var propertyInfo = typeof(Expression).GetProperty("DebugView", BindingFlags.Instance | BindingFlags.NonPublic);
    return propertyInfo.GetValue(exp) as string;
}

Comment: this is real the solution
Answer: The classes that implement the debug view features are intentionally internal so that you cannot access them without reflection.  Although this seems unfair, the purpose of debugging is debugging and it is not intended as a supported API and therefore could change at any time, perhaps to improve debugging!  Using the supported public APIs will ensure compatibility with future versions.
Here is another StackOverflow question using the public APIs:

Print out Linq Expression Tree Hierarchy
Answer: While the classes are internal, the source code is public :-)
http://referencesource.microsoft.com/#System.Core/Microsoft/Scripting/Ast/DebugViewWriter.cs,05c213f459ccd9cb
Obviously you have to fix up a few things but its not too difficult to get it to work.
Answer: http://referencesource.microsoft.com/#System.Core/Microsoft/Scripting/Ast/ExpressionStringBuilder.cs gives the mouse-over text you see for an expression in Visual Studio when debugging.
Depending on your needs either that or DebugViewWriter.cs as Andrew Jackson mentioned should cover things.


proof of upper bound on differential entropy of f(X)

Question: I asked a similar question yesterday,
but I organized my question here a little and further asked my second question.
Suppose $X$ is a continuous random variable with the pdf $f_x$, and $Y=g(X)$.
If $g$ is a bijection, then via the change of variable method,
the pdf of $Y$ is $f_y = f_x/|J|$, where $|J|$ is the Jacobian of $g$.
Therefore,
$$h(Y)=h(X)+\int f_x \log |J| dx$$.
From Wikipedia, if $dim(X)=dim(Y)$, there exists an upper bound on $h(Y)$ for a general map $g$:
$$h(Y)\leq h(X)+\int f_x \log |J| dx \tag{1}$$
My first question is how to derive the inequality in Eq.(1).
Second, is there a general approach to derive $h(Y)$ or an upper bound on it if $dim(X)\neq dim(Y)$.
I'd appreciate any help and suggestions!
Answer: If $g$ maps between two sets that have the same dimension, the inequality may be strict. The inequality appears in Papoulis' book on Probability, Random Variables, and Stochastic Processes - an exact value, albeit depending on the function $g$ in a complicated way, can be found in Corollary 1 in this paper:
$$h(Y) = h(X)+\int f_x\log |J|dx - H(X|Y). $$
If $g$ maps between sets of different dimension, then the Jacobian matrix is not square and computing its determinant does not make sense. I'm not sure if there is an easy way to derive the differential entropy of $Y$ from the differential entropy of $X$ in this case...
Comment: Thank you Bernhard. I found the reference while reading your dissertation as well.
Comment: @whuber: Thanks, I have added the full proof [here](https://statproofbook.github.io/P/dent-noninv).


Getting latest data from SQL

Question: I'm having trouble getting the latest data out of this.
I have a table with these data:
ItemId, ShipmentId, Date

Items can be shipped many times and a shipment can contain multiple items.
I need to get the latest shipment for every item.
Table looks like this:
11  12 2011-05-13
11  2  2011-07-01
12  2  2000-03-02
...

The result should be
11 2 2011-07-01
12 2 2000-03-02

I can't find a solution to be exclusive.
How can I get the latest shipment for every item?
Comment: Thank you for all your post Damien_The_Unbeliever got the solution for me!
Answer: Assuming you're working with a database engine that supports ranking functions, use a CTE or subquery to order the results:
;With OrderedItems as (
     select ItemId,ShipmentId,Date,
         ROW_NUMBER() OVER (PARTITION BY ItemId ORDER By Date desc) as rn
     from ItemsTable
)
select * from OrderedItems where rn = 1

Answer: select t1.ItemId, t1.ShipmentId, t1.Date
from tab t1
join (
    select ItemId, max(Date) as Date
    from tab
    group by ItemId
) t on t1.ItemId = t.ItemId and t1.Date = t.Date

Comment: That won't select the shipmentId that belongs to the latest shipment date.
Comment: if i try your solution i get error: Column 'ShipID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Answer: Didn't test it, but this general idea should work:
SELECT * FROM YOUR_TABLE T1
WHERE
    NOT EXISTS (
        SELECT * FROM YOUR_TABLE T2
        WHERE T1.ItemId = T2.ItemId AND T1.Date < T2.Date
    )

In plain English: select rows such that there is no other row with the same ItemId but later Date.
Answer: you can use rank() also in CTE
;With Ordered as (
     select ItemId,ShipmentId,dates,
         rank() OVER ( PARTITION by itemID ORDER By dates desc) as DateRank
     from ItemsTable
)
select * from Ordered where DateRank = 1

Getting latest data from SQL


Python Child Class with multiple init methods?

Question: I have an application I'm building in Python2.7 that works as-is, but doesn't feel clean, nor is it very explicit in what's happening, so if I walk away from the code for a while I have a hard time remembering how it's actually working under the hood, which is obviously not good. I've refactored the code and it seems more explicit, but not really any cleaner.
I'm trying to figure out the cleanest way to initialize these classes in two different ways - 1) from a user-generated instantiation (in the event of adding a new object from scratch during program execution), or 2) from importing the history of an object (from a previous program execution) from JSON. Here's my latest way of going about this:
class Device(object):
    def __init__(self, dev_type, preset_prefix, default_preset,
                 from_json=False, json_path=None, **device_attrs):

    if not from_json:  # otherwise set in child class __init__
        self.name = device_attrs['name']
        self.sn = device_attrs['sn']
        self.mfg = device_attrs['mfg']
        self.tech = device_attrs['tech']
        self.model = device_attrs['model']
        self.sw_ver = device_attrs['sw_ver']
        self.hours = 0
    else:
        self.hours = device_attrs['hours']

    self.type = dev_type
    self.json = json_path
    self.preset_prefix = preset_prefix
    self.preset = default_preset

class Monitor(Device):
    def __init__(self, name, sn, mfg, tech, model, sw_ver, from_json=False,
                 json_path=None, **monitor_dict):
        if from_json:
            self.__dict__ = monitor_dict
        device_properties = {'name': name, 'sn': sn, 'mfg': mfg, 'tech': tech,
                             'model': model, 'sw_ver': sw_ver}
        monitor_dict.update(device_properties)
        super(Monitor, self).__init__('monitor', 'user', 1, from_json,
                                      json_path, **monitor_dict)
        if cals:
            self._init_cal_from_json(monitor_dict['cals'])

Now I can initialize from a previously saved JSON (generated from this object so I can be sure the key/value pairs are correct):
my_monitor = Monitor(from_json=True, json_path=device_json_file, **device_json_dict))

Or as a new object from scratch:
my_monitor = Monitor('monitor01', '12345', 'HP', 'LCD',
                     'HP-27', 'v1.0')

This seems a little bit messy, but still better than my original version which didn't have any positional arguments for the child init (making it hard to know what data MUST be passed in), it just took **monitor_dict hoping it contained the right key/value pairs. However this method of taking those arguments and merging them into a dict seems strange, but I've refactored this multiple times and this seems to be the cleanest way of going about it.
Is this the best way to handle initializing an object in multiple ways or can I somehow create two separate init functions, one for loading from JSON, and one for new creation of brand new objects?
Comment: Having additional constructor methods (using the `@classmethod` decorator), as shown in the [answer below](https://stackoverflow.com/a/45292417/2437514), is a pretty typical Python idiom. There are a number of examples in the standard library (one that comes to mind is the `dict.fromkeys()` method). Use `__init__` for the most-used- or most expected- constructor, and create other constructors as  needed. So I suggest adding a `from_json` method.
Comment: Hi @ice, I've checked the edited question, if you may a suggestion, you should probably ask another question, with the new problems, I mean, my answer solve only your main and original question (for python 3, my mistake), if you ask a new question, with the new problems (and also a link to this question) you will success, i can guarantee it happend before to someone else i help. If you ask a new question let me know please, with all the details :), I hope I could help more
Answer: I prefer to create new constructors as class methods, something like this, you could create more if you need, or adjust it if necesary:
class Device(object):
    def __init__(self, dev_type, preset_prefix, default_preset, json_path=None, **device_attrs):

      self.name = device_attrs['name']
      self.sn = device_attrs['sn']
      self.mfg = device_attrs['mfg']
      self.tech = device_attrs['tech']
      self.model = device_attrs['model']
      self.sw_ver = device_attrs['sw_ver']
      self.hours = 0

      self.type = dev_type
      self.json = json_path
      self.preset_prefix = preset_prefix
      self.preset = default_preset

class Monitor(Device):

    @classmethod
    def new_from_json(self, name, sn, mfg, tech, model, sw_ver, json_path=None, **monitor_dict):
        self.__dict__ = monitor_dict
        device_properties = {'name': name, 'sn': sn, 'mfg': mfg, 'tech': tech,
                             'model': model, 'sw_ver': sw_ver}
        monitor_dict.update(device_properties)
        super(Monitor, self).__init__('monitor', 'user', 1,
                                      json_path, **monitor_dict)

As an example:
class Parent():
    def __init__(self,some):
        self.some = some

class Object(Parent):

    @classmethod
    def new_from_dict(self,some):
        Parent.__init__(self,some)
        self.adress = {"Me": 123}
        return self

then:
obj = Object.new_from_dict("ME")
obj.adress

{"Me": 123}

obj.some

"ME"

Comment: Thank you, I've read about classmethods and factories before but didn't really put two and two together on how to apply it here. A little extra reading after your answer here got me what I think is a clean, logical solution. I've updated my question to include a revised version.
Comment: I actually was trying something closer to what you did here for a different type  of class I have where my revised code doesn't really apply or work. The problem I'm having that I can't understand - in the code you provided, what is self referring to in new_from_json()? At that point in the code, nothing has been initialized so self is not referring to any particular object, and the self.__dict__ would not actaully work? Am I missing something?
Comment: @iceblueorbitz I will add an example for you at the end, so maybe you could see it better
Comment: Doing exactly this is still causing the same problem: TypeError: unbound method `__init__() must be called with Parent instance as first argument (got type instance instead)`.  When using the classmethod decorator, PyCharm is suggesting to use cls instead of self, and then initializing with cls(some), but this will call the subclass "Object" __init__, which in this case doesn't exist.
Comment: @iceblueorbitz try change the class for super, I did it in python 3.6 and worked fine as it is. that's error is odd..
Comment: I'm in Python 2.7, and no matter what I do, I cannot make your code work.  Since this is a classmethod of the child class, Python is expecting the first argument to be 'cls' instead of 'self', since there is no self instance to refer to yet.
Comment: @iceblueorbitz aaah I get why now, you are in python 2.7, so the sintaxis is a little different, I will edit this soon
Comment: As to avoid convoluting the original question - I'm just leaving the original question and code. I still don't think your answer is valid, however, as there is no object to pass into the Parent `__init__` instance method when you call it. I asked this in a [separate question](https://stackoverflow.com/questions/45429815/child-class-constructor-using-super-getting-unbound-method-init/45430293#45430293) and based on that response and my research, your answer is still not valid from what I see unless you first create an instance with `__new__`.


Angular 6 App and Server project structure

Question:
What is the proper project structure when creating an Angular 6 application, and an API server that share type definitions?
Example:
On the client:
this.httpService.get<Hero[]>(apiUrl + '/heroes')

On the server:
app.get('/heroes', async (req, res) => {
  const heroes: Hero[] = await db.Heroes.findAll<Hero>()
  res.status(200).send(heroes)
}

I need to share the Hero definition between projects.

Do I build my server in a sub-directory of the angular app?
Do I build my server app first, then reference its source code somehow from the Angular app?
Do I build a third Models project, write all the definitions there, and somehow reference them?
Answer: You need to have a structure as follows,

where web is the front end and services is going to be your node/go services.
Do I build my server in a sub-directory of the angular app?
No , you can separate both.
Do I build my server app first, then reference its source code somehow from the Angular app?
Yes thats better so you do not have to worry about Model when you start with your angular app.
Do I build a third Models project, write all the definitions there, and somehow reference them?
Not necessary. You can have your models in your node project itself.
I need to share the Hero definition between projects.
I would strongly suggest not to do that, becauase sometimes you are not binding all properties on the front end. Have a separate Interface for your front end models.
Comment: Different models will be the exception.. How do I make a shared library for the majority?
Comment: You can use a share folder to use the shared ones


Error distribution for linear and logistic regression

Question: With continuous data, a linear regression $Y=\beta_1+\beta_2X_2+u$ assumes that the error term is distributed N(0,$\sigma^2$)
1) Do we assume that Var(Y|x) is likewise ~N(0,$\sigma^2$)?
2) What is this error distribution in logistic regression? When the data is in the form of 1 record per case, where the "Y" is 1 or 0, is the error term distributed Bernoulli (i.e. variance is  p(1-p) )) and when the data is in the form #successes out of #of trials, is it assumed binomial (i.e. variance is np(1-p)), where p is the probability that Y is 1?
Comment: You are not being precise.The model assumption is that the error terms are independent and identically distributed with a distribution that is N(0,σ$^2$) and is unrelated to the COVARIATE. What is Var(Y|x)? Are you conditioning on X$_2$ =x? Does the model assume the covariate is random in some way or so we assume that the covariate is fixed according to a design matrix? I think it is the latter and therefore Var(Y|X$_2$=x) is implied by the assumptions and does not need to be assumed.
Comment: @MichaelChernick Why does the model assume that $X_2$ is fixed? It certainly *can* be the case that it is fixed, but it can also be random. Nothing in the question implies either one to me.
Comment: @PeterFlom I read into the question that linear regression with that assumed error distribution meant OLS which does require X$_2$ to be fixed and known.  If someone has Deming regression (i.e. error in variables regression) it would be specified in the question. Looking at the answer Stat gave indicates that he interpeted the question that way too.
Comment: @Michael, I was assuming fixed X.
Answer: 1) If  $u$ has normal distribution i.e. $N(0,σ^2)$ then $Var(Y|X_2)=Var(β_1+β_2X_2)+Var(u)=0+σ^2=σ^2$, since $β_1+β_2X_2$ is not a random variable.
2) In the logistic regression, it is assumed that the errors follows a binomial distribution as mentioned here. It is better to write it as $Var(Y_j|X_j)=m_j.E[Y_j|X_j].(1-E[Y_j|X_j])=m_j\pi(X_j).(1-\pi(X_j))$, since those probabilities depend on $X_j$, as referenced here or in Applied Logistic Regression.
Comment: Yes, this is correct. If $Y_i=p_i+e_i$ with $P(Y_i=1)=1-P(Y_i=0)=p_i$, then $e_i=1-p_i$ with probability $p_i$ or $e_i=-p_i$ with probability $1-p_i$. Hence $e_i$ has a distribution with mean $0$ and variance equal to $p_i(1-p_i)$.
Comment: Stat, So, it is correct to say that the variance for the ith individual error, $e_i$, is $p_i$(1-$p_i$) which is equivalent to what you have shown assuming that there are more than 1 observation in the data with the same covariate pattern (i.e. else $m_j$ = 1 for all j)?
Comment: One additional point here, Stat, we HAVE to assume that the X are fixed, non random for Var(Y|X) = Var(e) for both the cases of linear and logistic regression correct?
Comment: NB $e_i=1−p_i$ with probability $p_i$ or $e_i=−p_i$ with probability $1−p_i$ is *not* a binomial distribution for $e_i$.
Comment: B_Miner: $\operatorname{Var}(Y|X)=\operatorname{Var}(Y|X=x)$ means the variance of $Y$ conditional on the random variable $X$'s taking an observed value $x$. So it's immaterial whether your predictors are fixed by an experiment or observed in a sample: what @Stat's saying is they're *no longer* being considered as random variables for the purposes of regression.


Are there any publicly available databases ( not just web apps ) of guitar chords?

Question: I need guitar chords in a database for a project I'm working on ( preferably MySQL, CSV or some other easily portable format ). I can imagine many formats by which one could store this information, so I don't particularly care how it's setup.
This information must exist in databases all over the internet, but is there anything freely and publicly available?
Comment: Any reason you can't just compute them?
Comment: when you say "database of chords", do you mean "chord progressions"?
Or do you mean just a list of how to construct all the minor, major, 7th, sus2, etc types of chords?
Answer: As mentioned by JimR in the comments, it's not too hard to calculate chord data. You can either populate your own database or calculate them on the fly.
In my ungolfed program here I derive the scales from tetrachords, and treat the A and E shapes uniformly  (the E shape occurs when the A shape falls off the bottom [I just re-read the code, I had remembered it backwards.]).
The only fancy operations you need are summing an array and adding a constant to each element of an array.
Well, those were the operations that postscript didn't have built-in. Conceptually, it can get tricky if you're not certain of exactly how chords are built, and then applied to the guitar. So how's about I work through an example case of how my code generates a chord.
D#m was my edge case because it's the highest up the neck that the requirements ... um ... required.
So the input was an ascii string. 'A' = 65, 'B' = 66, 'C' = 67. So 'D' is 68.
My program creates a mapping between these values (integer) and procedures which add a constant to an array. The array has been constructed to describe an A Major chord as if played on 8 strings all tuned to low E. [ 0 5 12 17 21 24 29 0 ]. [My code comments call this the "abstract fretstop" form.] So if it's an A chord we need, we leave it alone for now. But for a D, we need to add 5 to everything (we're treating just barre chords, here, so just slide the A up the neck). The constants are derived from seven notes of the aolian scale (the one that starts with 'A' but has no sharps or flats: perfect for decoding).
This produces a new template [ 5 10 17 22 26 29 34 5 ]. Doesn't look like much just yet, but we'll fix that after dealing with the sharp and the fact that it's a Minor chord, not Major.
To make it sharp, just add one to everything, producing [ 6 11 18 23 27 30 35 6 ].
Then to make it Minor, we just tweak the third, which is still in position 4 (counting from 0) of the chord template (not really a template anymore, it's our working copy). This produces [ 6 11 18 23 26 30 35 6 ].
Finally, we "re-tune" the abstract guitar by adding this array [0 -5 -10 -15 -19 -24 -29] to the chord array, producing [ 6 6 8 8 7 6 6 6 ]. And the first 6 elements of this resulting array are the desired fretstops of a D♯ Minor chord.
587(1)07:23 PM:~ 0> gs -q -- tabb.ps D\#m
e 6---
B 7---
G 8---
D 8---
A 6---
E 6---

For E, F, and G, I added -12 to the template to shift everything down an octave and trimmed any initial elements that were below zero (signifying that that note had fallen off the nut and out of the range of the guitar). That's why the template had to have more elements than strings, and this is how the E shape arose from the A shape.

To generate the chord template, We start with a one-octave scale [ 2 2 1 2 2 2 1 ] (aka. 2 disjunct tetrachords 2 2 1 separated by a whole tone 2). Extend it to 2.5-octaves [ 2 2 1 2 2 2 1 2 2 1 2 2 2 1 2 2 1 2 ]. Then we convert these relative intervals to absolute intervals by taking a running sum [ 0 2 4 5 7 9 10 12 14 16 17 19 21 22 24 26 28 29 ]. Now the intervals are all relative to the root rather than to their neighbors.
Then we select elements from the scale according to the figured bass of the desired chord. Let's take an E chord [ 1 5 8 10 12 15 ]. Subtract 1 to change from cardinal numbers to ordinal numbers (indices) [ 0 4 7 9 11 14 ].
Selecting these indices from the scale yields [ 0 7 12 16 19 24 ], the "abstract fretstop" form; also, an arpeggio on one string.
Convert this to actual fretstops by subtracting the intervals to which the strings are tuned [0 -5 -10 -15 -19 -24] to yield the desired chord [ 0 2 2 1 0 0 ].
In order to unify the A and E shapes, I made the template describe an A/E chord. But since notes are described in strict ascending order, it had to have E as the root. Thus A/E is the IV chord of E mixolydian. You could go further and unify the D/F# shape with these, but you'd have to use the phrygian mode.

Now, finally to get around to answer the question! Given the ability to plot chords in any key, what remains is the much simpler task of enumerating the figured-bass representations of your basic forms. The CAGED shapes, 7th chords, 9th chords. [Plus, additional heuristics/editing to eliminate "impossible" shapes. I rather glossed over this snag. Eg., 'Cm' described below would give you a '-1' on the high E string. Perhaps, throw it out (ie. display the chord with that string muted); or substitute a higher chord tone.]
C [ x 1 3 5 8 10 ] and G [ 1 3 5 8 10 15 ] can be considered the same form (from the figured-bass point of view). As can E A and D [ x x 1 5 8 10 12 15 ]. And the minor shapes can use the same form selected from a minor scale. This treatment, unfortunately, glosses over the fact that Cm and Gm are more often played as Am- and Em- shaped barres. :)

This usenet thread has a partial translation of my postscript program to APL.
Answer: A quick google of "downloadable guitar chords" took me to the Chordpda site. It is an app for windows mobile devices but it has an XML database of chords so that would be simple to use.
Free and downloadable - I'm giving no assurances as to how good it is, but there must be more - that was just a 5 second google search.


What is the probability that a coin is a loaded coin?

Question: If you randomly pick a coin from a box that contains $90\%$ fair coins and $10\%$ loaded coins, (a loaded coin gives heads $90\%$ of the time), toss it $5$ times and get all heads. What is the probability that this is a loaded coin?
$$n = 5, x = 5, p = 0.1(0.9)^5$$
Where $n$  is the number of flips, $x$ is number of heads, and  $p$ is the probability of getting heads.
so
$$( 0.1 (0.9)^5 ) + (0.9 (0.5)^5) = 0.087$$
Can anyone see if the answer I provided is correct or not !
Comment: This is a duplicate of his earlier question but not of Checking whether a coin is fair. I vote to leave it open.
Comment: It looks like you asked this question before and we told you what the right formula is. It looks like the parentheses are messed up .It might be right if the second multiplication sign was a plus sign.  There should not be a term involving 0.9 raised to the 10th power which it seems you have.
Answer: Guide:
Try using these formula.
From Bayes Theorem
$$P(\text{loaded }| 5\text{ heads}) = P(5\text{ heads|loaded}) \frac{P(\text{loaded})}{P(\text{5 heads)}}$$
where by law of total probability:
$$P(5 \text{ heads}) =P(5\text{ heads|loaded}) P(\text{loaded})+ P(5\text{ heads|fair}) P(\text{fair})$$
Comment: You might want to state what do you think  the values for $P(\text{fair})$, $P(5 \text{ heads}|\text{fair})$, $P(\text{loaded})$, $P(5 \text{ heads}|\text{loaded})$ are explicitly before you apply the formula.
Comment: I can see that you mean $0.5^5$. Now you have all the ingredient, you  just have to sustitute them to get the desired quantity.
Comment: That is what we suggested in the previous post. I gave you +1 anyway.
Comment: I made an edit to my question see if now my answer is correct, then I will approve your posted answer :)
Comment: You have the formula right now.
Comment: @MichaelChernick I had the formula before as well, but I wasn't sure as where to put my values in the formula, that's why I asked if the way I put my values are now Okay ?
Comment: @SiongThyeGoh +1 your comment, so here $$P(fair) = 0.9, P(5 heads|fair) = 0.9^5, P(loaded) = 0.1, P(5 heads|loaded) = 0.9^5 $$ and see my question I applied there as well, now do you think my final result is right ?
Comment: $P(5 \text{ heads}|\text{fair})$  is not quite right. Try again? Also, the quantity of interest would be $P(\text{loaded} | 5 \text{ heads})$.
Comment: @SiongThyeGoh oh yeah you are right, I just changed it $$0.5^5$$. check now
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/66806/discussion-between-siong-thye-goh-and-hazmat).


Grouping Regex in Ruby

Question: Sample Text
    outline: 4 0
      corner: 1 347980000 -2540000 0
      corner: 2 347980000 -20320000 0
      corner: 3 482600000 -20320000 0
      corner: 4 482600000 -2540000 0

    outline: 4 1
      corner: 1 0 -2540000 0
      corner: 2 345440000 -2540000 0
      corner: 3 345440000 -20320000 0
      corner: 4 0 -20320000 0

    outline: 8 2
      corner: 1 0 0 0
      corner: 2 0 35560000 0
      corner: 3 53340000 35560000 0
      corner: 4 53340000 76200000 0
      corner: 5 449580000 76200000 0
      corner: 6 449580000 30226000 0
      corner: 7 482600000 30226000 0
      corner: 8 482600000 0 0

    outline: 4 3
      corner: 1 0 38100000 0
      corner: 2 50800000 38100000 0
      corner: 3 50800000 76200000 0
      corner: 4 0 76200000 0

    outline: 4 4
      corner: 1 482600000 76200000 0
      corner: 2 482854000 31750000 0
      corner: 3 450850000 31750000 0
      corner: 4 450850000 76200000 0

/^\s+corner:\s*(\d+)\s+(-?\d+)\s+(-?\d+)\s+(\d+)/m
Captures all values for corners.
/^\s*outline:\s*(\d+)\s+(\d+)$.*?\s+corner:\s*(\d+)\s+(-?\d+)\s+(-?\d+)\s+(\d+)/m
Captures all outlines, but only the first corner of each outline.
/^\s*outline:\s*(\d+)\s+(\d+)$.*?(^\s+corner:\s*(\d+)\s+(-?\d+)\s+(-?\d+)\s+(\d+)$).*?/m
Does the same thing as the second, but looks like this:
4
0
corner: 1 347980000 -2540000 0
1
347980000
-2540000
0

I am trying to get it to capture all of the outlines and related corners. It's obviously not properly grouped - Any suggestions?
Thank you ;-)
Answer: Since the number of captures you want varies (probably without limit), you cannot do that in one regex. String#scan comes in handy in such case.
text.scan(/^\s*outline:\s*(\d+)\s+(\d+)\n(.*?)(?:\n\n|\z)/m)
.map{|a, b, corners| [a, b, corners.scan(/^\s+corner:\s*(\d+)\s+(-?\d+)\s+(-?\d+)\s+(\d+)/)]}

will give you:
[["4", "0",
  [["1", "347980000", "-2540000", "0"],
   ["2", "347980000", "-20320000", "0"],
   ["3", "482600000", "-20320000", "0"],
   ["4", "482600000", "-2540000", "0"]]],
 ["4", "1",
  [["1", "0", "-2540000", "0"],
   ["2", "345440000", "-2540000", "0"],
   ["3", "345440000", "-20320000", "0"],
   ["4", "0", "-20320000", "0"]]],
 ["8", "2",
  [["1", "0", "0", "0"],
   ["2", "0", "35560000", "0"],
   ["3", "53340000", "35560000", "0"],
   ["4", "53340000", "76200000", "0"],
   ["5", "449580000", "76200000", "0"],
   ["6", "449580000", "30226000", "0"],
   ["7", "482600000", "30226000", "0"],
   ["8", "482600000", "0", "0"]]],
 ["4", "3",
  [["1", "0", "38100000", "0"],
   ["2", "50800000", "38100000", "0"],
   ["3", "50800000", "76200000", "0"],
   ["4", "0", "76200000", "0"]]],
["4", "4",
  [["1", "482600000", "76200000", "0"],
   ["2", "482854000", "31750000", "0"],
   ["3", "450850000", "31750000", "0"],
   ["4", "450850000", "76200000", "0"]]]]

If you want numbers instead of strings,
text.scan(/^\s*outline:\s*(\d+)\s+(\d+)\n(.*?)(?:\n\n|\z)/m)
.map{|a, b, corners| [a.to_i, b.to_i, corners.scan(/^\s+corner:\s*(\d+)\s+(-?\d+)\s+(-?\d+)\s+(\d+)/).map{|a| a.map(&:to_i)}]}

will give you:
[[4, 0,
  [[1, 347980000, -2540000, 0],
   [2, 347980000, -20320000, 0],
   [3, 482600000, -20320000, 0],
   [4, 482600000, -2540000, 0]]],
 [4, 1,
  [[1, 0, -2540000, 0],
   [2, 345440000, -2540000, 0],
   [3, 345440000, -20320000, 0],
   [4, 0, -20320000, 0]]],
 [8, 2,
  [[1, 0, 0, 0],
   [2, 0, 35560000, 0],
   [3, 53340000, 35560000, 0],
   [4, 53340000, 76200000, 0],
   [5, 449580000, 76200000, 0],
   [6, 449580000, 30226000, 0],
   [7, 482600000, 30226000, 0],
   [8, 482600000, 0, 0]]],
 [4, 3,
  [[1, 0, 38100000, 0],
   [2, 50800000, 38100000, 0],
   [3, 50800000, 76200000, 0],
   [4, 0, 76200000, 0]]],
[4, 4,
  [[1, 482600000, 76200000, 0],
   [2, 482854000, 31750000, 0],
   [3, 450850000, 31750000, 0],
   [4, 450850000, 76200000, 0]]]]

Comment: There you go again, with the goods - dude, you rock! I'm using `string.scan(/regex/)` for everything in this project. I knew I had to break them up somehow, but I just wasn't getting it - strings or numbers will both work, but numbers would probably be better. Your assumption is correct, while most will only have 1 outline, with 4 corners, it still needs to be flexible - just in case someone (like me), decides to panelize the project, with multiple, odd shaped outlines. I'll post results, when I test the API for it. Thanks again ;-)
Comment: I had to add `class Symbol
def to_proc
proc { |*args| args[0].send(self, *args[1...args.size]) }
end
end` to get output from the second version - as I'm using Ruby 1.8.6
Comment: A map(&:symbol) call results in wrong argument type Symbol (expected Proc) (TypeError)
Comment: Update: Using the numbers example, it worked like a charm in my app - no errors. Thanks again ;-)
Answer: I'm not sure I even want to know what the purpose of scanning that file with a regex is.
But you know, it would be easy to parse using virtually any technique other than regular expressions.
And in fact, with just a slight change in syntax1 it's a good YAML file:
- outline: 4 0
  - corner: 1 347980000 -2540000 0
  - corner: 2 347980000 -20320000 0
  - corner: 3 482600000 -20320000 0
  - corner: 4 482600000 -2540000 0

- outline: 4 1
. . .
. . .

And there you go, a perfectly organized data structure with one line of Ruby:
 > pp YAML::load_file 'corners.yaml'
[{"outline"=>
   [{"corner"=>"1 347980000 -2540000 0"},
    {"corner"=>"2 347980000 -20320000 0"},
    {"corner"=>"3 482600000 -20320000 0"},
    {"corner"=>"4 482600000 -2540000 0"}]},
 {"outline"=>
   [{"corner"=>"1 0 -2540000 0"},
    {"corner"=>"2 345440000 -2540000 0"},
    {"corner"=>"3 345440000 -20320000 0"},
    {"corner"=>"4 0 -20320000 0"}]},
 {"outline"=>
   [{"corner"=>"1 0 0 0"},
    {"corner"=>"2 0 35560000 0"},
    {"corner"=>"3 53340000 35560000 0"},
    {"corner"=>"4 53340000 76200000 0"},
    {"corner"=>"5 449580000 76200000 0"},
    {"corner"=>"6 449580000 30226000 0"},
    {"corner"=>"7 482600000 30226000 0"},
    {"corner"=>"8 482600000 0 0"}]},
 {"outline"=>
   [{"corner"=>"1 0 38100000 0"},
    {"corner"=>"2 50800000 38100000 0"},
    {"corner"=>"3 50800000 76200000 0"},
    {"corner"=>"4 0 76200000 0"}]},
 {"outline"=>
   [{"corner"=>"1 482600000 76200000 0"},
    {"corner"=>"2 482854000 31750000 0"},
    {"corner"=>"3 450850000 31750000 0"},
    {"corner"=>"4 450850000 76200000 0"}]}]

1. Now I did use a vim(1) regex to convert the file :%s/^  */&- /
Comment: YAML does look good, but the syntax of the file is not under my control. The 2 attributes following outline are ` `. Each outline is a separate entity, and I need to handle them as such, in order to incorporate them in another project. The sample text is just part of a larger file, this section just happens to have similar child elements, where all the others had individual child elements, that made using a regex the simpleest solution. I'm not familiar with YAML, and I need to keep this in Ruby 1.8.6, as I'm using it with the SketchUp API.
Comment: Ran out of room - Thank You ;-)

Grouping Regex in Ruby


Run AWS SAM Local on another port

Question: I've been successful in running AWS SAM Local on my machine on port 3000 with this command:
sam local start-api

The documentation says there's a flag -d that runs the server in debug mode on a different port. I need to run this on port 8080. So I tried this:
sam local start-api -d 8080

And the server still starts up on 3000:
Mounting api.get_account (python3.6) at http://127.0.0.1:3000/account/{account_num} [GET]

Does anyone know what I'm doing wrong here? Thanks!
Answer: The -d (--debug-port) option refers to the port that you would connect a debugger to, not the port that the application listens on.
So sam local start-api -d 8080 translates to "Start the application on the default port, and allow me to connect a debugger to port 8080".
To have the application listen on a different port, use the -p (--port) option.
You can of course use both.  For example,
sam local start-api -p 8080 -d 5858

means "Start the application on port 8080, and allow me to connect a debugger on port 5858".

Run AWS SAM Local on another port


Defining font-size of custom font in CSS for the entire project

Question: What's the standard way to selectively define the font-size of one of the fonts among a gamut of font-families in CSS?
For instance, I'm trying to have my_font appear at 25px size via the following short-hand:
body{

font-family:helvetica,'my_font',arial,sans-serif;

font:helvetica,25px 'my_font',arial,sans-serif;

}

Needless to say, this doesn't work.
Comment: use `font-size:20px;` or if you prefer `em` use `font-size:1.4em;`
Comment: @Jorden1337: only looking to change `my_font`'s font size, not of any other font in the families declared.
Comment: Depending on your html you can select different content areas and give them a unique font style. For example if you have a header, .main-content, and footer, you can style the body fonts there as you wish in your css.
Answer: I believe the answer is no. The idea of a font-family is that it's a family of fonts not a single version or size.
Probably the best you can do is to just add font-size to each class or css selection that uses that font.
Comment: That's quite a bummer. The font's pretty ubiquitous and it's a large-ish project.
Comment: I hate to give you a bummer answer, buthere we are. Maybe you could do a find and replace to quickly add all the font sizes?
Answer: I think you should declare a class where you specify your font and your font-size and then use it specifically where you want. For example:

.myclass {
font-family: 'myFont',
font-size: your-size
}

Answer: That would be the @font-face property. It's a property where you can define multiple font families and even modify a specific type of font to your preferences. It goes something like this

body {
 @font-face {
    font-family: 'my-font';
    src: url(path-to-font);
    font-size: 24px;
 }
}

Read more about it here: http://www.font-face.com/#green_content
Comment: `font-face` was the first place I tried setting the font-size for `my_font`. It hasn't worked for me. It doesn't seem `font-face` accepts the `font-size` attr
Comment: `font-size` is not a attribute that can be used with `@font-face` as of right now
Comment: Yeah, I see it turns red. My bad then. I thought that that should help. I guess I gave the wrong answer.
Comment: Have you tried to delete the `font` property from the `body`, and leave the `font-family` with multiple fonts and then just add the `font-size` in the next line?


Reject non-existent users in Postfix with Maildrop

Question: I use Postfix with virtual mailbox and Maildrop for the transport agent. All my emails are delivered to the folder /home/vmail/domain.tld/user/. Today I noticed that emails sent to non-existent addresses are delivered to the file /home/vmail/domain.tld/user. I would rather have them rejected by the server with an error message to the sender.
I think it is responsible to the /etc/postfix/maildroprc file that contains the rules DEFAULT="/home/vmail/$1/$2"
The file /etc/postfix/main.cfg
virtual_mailbox_base = /home/vmail
virtual_mailbox_maps = hash:/etc/postfix/vmailbox
virtual_alias_maps = hash:/etc/postfix/virtual
virtual_transport = maildrop
maildrop_destination_recipient_limit = 1

The rule in /etc/postfix/master.cfg
maildrop  unix  -       n       n       -       -       pipe
   flags=ODRhu user=vmail argv=/usr/bin/maildrop /etc/postfix/maildroprc ${domain} ${user} ${extension} ${recipient} ${user} ${nexthop}

Any idea how I can specify a list of valid emails ? All the emails addresses (except redirections which are in virtual) are listed in the vmailbox database but it seems not use it.
Answer: http://www.postfix.org/LOCAL_RECIPIENT_README.html
You have to correctly set local_recipient_maps in main.cf. This depends on how you manage users (system users, mysql, etc).
It could be something like local_recipient_maps = mysql:/etc/postfix/sql-recipients.cf for mysql.
Comment: Thanks. It seems to work well. In my case, it was `local_transport = virtual` and `local_recipient_maps = $virtual_mailbox_maps` (I use virtual mailbox, not mysql)


Override the taxonomy pages

Question: In Drupal 7, you can use taxonomy-term.tpl.php to override taxonomy pages.
Inside the taxonomy-term.tpl.php page, you can use <?php print $term->field_NAME['und'][0]['value'];?>to print out the content of any fields attached to the taxonomy term. (*)
However, how do you get to the list of nodes that is displayed on the taxonomy page?
There doesn't seem to be anything in the taxonomy-term.tpl.php file to indicate how to theme the nodes that are displayed on the term page.
I know you can use Views to over ride the page. However, Views does not let you display nodes tagged with a term and fields that are attached to the term in a single View.
(*) I know you are not supposed to use UND. However, the correct method for access node based fields does not seem to work with taxonomy based fields.
Answer: The template file you want to use is not taxonomy-term.tpl.php; that's used for the taxonomy header at the top of the page. The template file used is node.tpl.php.
If you look at taxonomy_term_page() which is used to build the term page view, you will see the nodes are build separately by calling node_view_multiple(). node_view_multiple() is just a wrapper for node_view(), which uses the standard node.tpl.php file.
Also you should be able to use field_get_items() for taxonomy terms. I'll look for something like $field = field_get_items('taxonomy_term', $term, 'field_name');.
I haven't tried but it should work.
You should really never use 'und', but the constant LANGUAGE_NONE.
Comment: Thank you for your kindness in replying! If I use a custom node.tpl.php file it affects all nodes and not just those displayed on mysite.com/taxonomy/term/[tid]. Is there a way to specify a template just to hide the nodes on the taxonomy index page? I know I can hide all the fields for teaser display  on the manage display tab of the admin interface, but I would like to do it at theme layer.                          Also the $field code you posted on prints out the words "Array". How do I make it display the value in the array?

Override the taxonomy pages


Como adicionar um TextBox dinamicamente usando VB

Question: Como adicionar um TextBox dinamicamente, sempre que o Userform (Caixa de Combinação ou Validação de Dados Lista) seja igual a "Outro (Especificar)", usando VB ?

Estou perdida, sou novata em fazer macros e formulários, usando VB. ^^'
Estava fazendo com Validação de Dados, Lista.
Sub Outro()
'
' Outro Macro
coluna = 1
linha = 1
While Cells(linha, coluna).Value <> ""
    Application.Visible = False 'torna invisível a aplicação Excel
    valorCelula = Format(Cells(linha, coluna).Value, 2)
    'If valorCelula <> Cells(linha, coluna).Value Then
    '    Cells(linha, coluna).Value = valorCelula
    'End If
    linha = linha + 1
    With Selection.Font
            .Color = -16776961
            .TintAndShade = 0
        End With
        Selection.Font.Bold = True
        Range("G3").Select
        ActiveSheet.OLEObjects.Add(ClassType:="Forms.TextBox.1", Link:=False, _
           DisplayAsIcon:=False, Left:=497.25, Top:=36, Width:=66.75, Height:= _
           10.5).Select
Wend
End Sub

Comment: Seja muito bem vinda à comunidade SOpt Dani Guido, considere dar uma olhada em [Como Perguntar?](https://pt.stackoverflow.com/help/how-to-ask), irá ajudar bastante. Então, em relação ao seu problema, não consegui compreender o que exatamente você quer, tente **acrescentar alguns detalhes, partes do código que você utilizou e não está entendendo, qual linguagem de programação você quer usar?**
Comment: Estou com uma planilha de excel, que tenho de adicionar um campo lista, na mesma terá uma opção de "Outro", quando escolhida irar abrir um campo para ser preenchido. Programação em VB, usando macro e tal.  Ex: (Titulo)> Ponto:      (Opções) >   A; B; C; Outros(Especificar).
Comment: Tente seguir [esses passos!](http://www.macoratti.net/14/04/vba_forma1.htm)
Answer: Clica com o botão direito sobre o ComboBox e vai em:

Clica em Novo na tela que aparece:

Eu usei este código no sub Dropdown1_Alteração
Set oTB = ActiveSheet.OLEObjects.Add(ClassType:="Forms.TextBox.1")
Set cell = ActiveSheet.Range("C2")
With oTB
.Name = "MyTB"
.LinkedCell = "$C$2"
.Left = cell.Left
.Top = cell.Top
.Width = cell.Width
.Height = cell.Height
.Object.BackColor = RGB(204, 204, 255)
.Object.ForeColor = RGB(0, 0, 255)
.Object.Text = "Texto"
End With


Converting a 13 digit Unix timestamp to DateTime with Javascript

Question: I'm trying to convert this 13 digit Unix timestamp (1563398686957) to YYYYMMDD format using Javascript. How can I do this?
I have divided the 1563398686957/1000 and tried to get the first 10 digits but converting from Number to String and back gives me an error and is not there right way to do it if I am looping for many timestamps.
var newCreateDate = 1563398686957 / 1000;
var newTimestamp = Array();
for (let i = 0; i < newCreateDate.length; i++) {
    temp_timestamp = String(newCreateDate[i].slice(0, 9));
    newTimestamp.push(Number(temp_timestamp));
}

Comment: Have a look this `URL` I hope it's helpful https://www.toptal.com/software/definitive-guide-to-datetime-manipulation
Comment: [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) constructor may receive exactly 13 digit Unix timestamp as a parameter).
Answer: You can pass timestamp into Date:

var unixts = 1563398686957;
var date = new Date(unixts);

var fdate = date.getFullYear() + '/' + ("0" + (date.getMonth() + 1)).slice(-2) + '/' + ("0" + date.getDate()).slice(-2);
console.log(fdate);
Comment: @kshetline true
Answer: new Date(1563398686957).toISOString().substr(0, 10)
Will give you the date in this form: 2019-07-17
new Date(1563398686957).toISOString().substr(0, 10).replace(/-/g, '/')
Will change the dashes to slashes, if you prefer, and...
new Date(1563398686957).toISOString().substr(0, 10).replace(/-/g, '')
Would give you 20190717.
Comment: short and great


How well does mental practice work for you on different instruments?

Question: Multi-instrumentalists: this is about personal experience (instead of literature review) of mentally practicing your instruments away from them. Do you find it to be more or less effective for one (type of) instrument over another?
[Real experiences only, please. I beg you not to answer if you are merely imagining yourself imagining.]
Comment: This is relevant to my interests. Being an amateur guitar and keyboard player, I've tried "practicing" this way and I can say it did not help me a lot. At the very least it made it easier to internalize some hard passages from a song or some exercise.
Comment: It paid off for Prof. Harold Hill in "The Music Man". :-)
Answer: I'm a classically taught violinist and a self-taught drummer; "mentally practicing" drumming is much more effective than violin. I've made most (+50%) of my significant improvements in drumming first in just slapping my palms on my knees and tapping my foot. Of course, it might just be because you can actually practice drumming with your hands and feet. Violin is much more difficult to mentally practice since you don't have the same feedback about how well-placed your finger is, but it still helps. Also, one thing that I find very difficult to improve with from imagination alone is keeping tempo.
Regardless of the instrument, I tend to have the same habits and mental processes when imagining myself playing an instrument as when actually playing it. For instance, when playing difficult parts on the violin, I will subconsciously and immediately flare my nostrils - probably conditioned into me over the years. Imagining myself playing those same parts also makes me flare my nostrils.
Comment: But is it "mental practice" when you actually use your hands and feet?
Answer: In my freshman year of high school I was the backup drummer in our school's jazz/pep/orchestra bands, and quite frankly, I sucked. I couldn't use my limbs independently and I couldn't read music, but I was so into it. I memorized everything the lead drummer was doing, memorized the songs we played, mentally captured everything.
I was too poor to own my own drums, so over the summer I couldn't practice, but it was in my head, and I went over it over and over and over and over again.
First day of band practice my sophomore year, I discovered that the lead drummer had left and it was up to me. I sat at the drumset, and the entire band looked at me questioningly because they knew I wasn't up to the task.
And I rocked.
Probably the best moment of my life, actually.
Comment: Also, I actually learned how to read music by comparing what I was already playing to the written notes. (Ah! That's what a dotted eighth note looks like!)
Answer: This is a very difficult question to answer from a real experience point of view. For example if you measure your improvement by mentally practising how can you tell whether you would have had the same improvement by actually practising. I know you said you didn't want literature reviews and for that reason I wont go into naming sources, but there is sound evidence that mental practice creates the same neural pathways as actually doing the exercise.
Answer: For guitar, rhythm strumming can be practiced almost anywhere and it effectively translates to your strumming hand. Picking is a different story, but never tried it. I practice rhythms in my head and with my strumming hand all the time.
Fretting is not really something you can do without a guitar or some fretting device. It involves hand movement within specific ranges and is tied to muscle memory. That is why I am going to give the Halo Sport a try to see if it smooths my fretting by enhanced muscle memory (different post). Will update that by end of week.
Fretboard memorization/recollection, chord construction, scale recollection, etc are all things that I often sketch in my notebook at work while in meetings that drag on. And that is half of fretting and playing using the right brain. This does pay off when I am working out a progression that I heard, but applying it is still a matter of muscle memory... I just recollect it easier.


Why does the correlation coefficient between X and X-Y random variables tend to be 0.7

Question: Taken from Practical Statistics for Medical Research where Douglas Altman writes in page 285:

...for any two quantities X and Y, X will be correlated with X-Y.
  Indeed, even if X and Y are samples of random numbers we would expect
  the correlation of X and X-Y to be 0.7

I tried this in R and it seems to be the case:
x <- rnorm(1000000, 10, 2)
y <- rnorm(1000000, 10, 2)
cor(x, x-y)

xu <- sample(1:100, size = 1000000, replace = T)
yu <- sample(1:100, size = 1000000, replace = T)
cor(xu, xu-yu)

Why is that? What is the theory behind this?
Comment: What part do you want an explanation for?  Do you just want the simplified equation for the correlation that results because of the known correlation between x, and y, and covariance between x and x-y?  Or, do you just want to know why there's any covariance here at all?
Comment: Is this true for *any* $X$ and $Y$?  Suppose $X$ and $Z$ are uncorrelated and let $Y=X-Z$.  Then I suspect $X$ will not be correlated with $X-Y$.
Answer: If $X$ and $Y$ are uncorrelated random variables with equal variance $\sigma^2$, then we have that
$$\begin{align}
\operatorname{var}(X-Y) &= \operatorname{var}(X) + \operatorname{var}(-Y)\\
&= \operatorname{var}(X) + \operatorname{var}(Y)\\
&=2\sigma^2,\\
\operatorname{cov}(X, X-Y) &= \operatorname{cov}(X,X) - \operatorname{cov}(X,Y)
& \text{bilinearity of covariance operator}\\
&= \operatorname{var}(X) - 0 & 0 ~\text{because}~X ~\text{and}~ Y ~\text{are
uncorrelated}\\
&= \sigma^2.
\end{align}$$
Consequently, $$\rho_{X,X-Y} = \frac{\operatorname{cov}(X, X-Y)}{\sqrt{\operatorname{var}(X)\operatorname{var}(X-Y)}}= \frac{\sigma^2}{\sqrt{\sigma^2\cdot2\sigma^2}} = \frac{1}{\sqrt{2}}.$$
So, when you find
$$\frac{\sum_{i=1}^n\left(x_i - \bar{x}\right)
\left((x_i-y_i) - (\bar{x}-\bar{y})\right)}{
\sqrt{\sum_{i=1}^n\left(x_i - \bar{x}\right)^2
\sum_{i=1}^n\left((x_i-y_i) - (\bar{x}-\bar{y})\right)^2}} $$
the sample correlation of $x$ and $x-y$ for a large data set $\{(x_i,y_i)\colon 1 \leq i \leq n\}$ drawn from a population with these properties,
which includes "random numbers" as a special case, the result tends to
be close to the population correlation value $\frac{1}{\sqrt{2}} \approx 0.7071\ldots$
Comment: cov(X,X) is another name for var(X). cov(X,Y) = 0 since X and Y are assumed to be uncorrelated (hence covariance = 0).
Comment: Could you please explain a bit more how `cov(X,X)-cov(X,Y)=s^2`
Answer: A geometrical-statistical explanation.
Imagine you make an "inside-out" scatterplot where the $n$ subjects are the axes and the $2$ variables $X$ and $Y$ are the points. This is called a subject space plot (as opposed to usual variable space plot). Because there is only 2 points to plot, all dimensions in such a space except just any two arbitrary dimensions that are able to support the 2 points plus the origin, are redundant and can be safely dropped. And so we are left with a plane. We draw vector arrows from the origin to the points: these are our variables $X$ and $Y$ as vectors in the subject space of the data.
Now, if the variables were centered then, in a subject space, the cosine of the angle between their vectors is their correlation coefficient. On the pic below $X$ and $Y$ vectors are orthogonal: their $r=0$. Uncorrelatedness was a prerequisite outlined by @Dilip in their answer.
Also for variables centered, their vector lengths in a subject space are their standard deviations. On the pic, $X$ and $Y$ are of equal length, - equal variances was also a prerequisite made by @Dilip.
To draw the variable $X-Y$ or variable $X+Y$ we just use vector addition or subtraction that we've forgotten since school (move Y vector over to the end of X vector and invert direction in case of subtraction, - this is shown by grey arrows on the pic, - then draw a vector to where the grey arrow points).
It becomes very clear that the length of $X-Y$ or $X+Y$ vectors (the standard deviation of these variables) is, by Pythagorean theorem, $\sqrt{2\sigma^2}$, and the angle between $X$ and $X-Y$ or $X+Y$ is 45 degrees, which cosine - the correlation - is $0.707...$
Comment: A big +1 for sharing this approach.
Comment: Ahh...pictures! (+1) Well done. :-)
Comment: (+1) That is a very neat way of presenting this!
Answer: I believe that there's a simple intuition based on symmetry here, too. Since X and Y have the same distributions and have a covariance of 0, the relationship of X ± Y with X should "explain" half of the variation in X ± Y; the other half should be explained by Y. So R2 should be 1/2, which means R is 1/√2 ≈ 0.707.
Comment: This seems like a nice intuition, but note that if $r^2=\frac 1 2$, the standard way to write $r$ would be $\sqrt{1/2}$, not $1/\sqrt 2$ which might confuse some people even if they are algebraically equivalent.
Comment: No, that really is not more standard. (If you need evidence, look up at the top answer. The 38 people who have already voted for it didn't quibble with the same notation.)
Comment: I'm one of those 38 ;-). The question is, what will somebody whose algebra is fairly weak be most easily able to follow? If $r^2=1/2$, then it is easier to see that $r=\sqrt{1/2}$.
Answer: Here's a simple way to think about why there's a correlation here at all.
Imagine what goes on when you subtract two distributions.  If the value of x is low then, on average, x - y will be a lower value than if the value of x is high. As x increases then x - y increase, on average, and thus, a positive correlation.
Comment: @curious_cat: Or, perhaps to be even more evocative, drop the `y` altogether. :-)
Comment: I don't think your statement is always true _"There will always be a correlation between two random distributions when there's a mathematical relationship."_ e.g. `x <- rnorm(1e6, 0,1)  y <- rnorm(1e6, 0,1) $cor((x-y)^2,x-y)`
$


Formal definition of "unnesting" a nested list.

Question: This is very much related to my previous question on the iterated Kleene closure, here: The iterated Kleene closure of an alphabet. Someone in the comments called elements of my construction "nested lists". My current question is about the formal definition of "unnesting" a nested list. Let me give some examples so as to clarify what I intuitively mean. Let our alphabet be $\{a,b\}$. The unnesting of the nested list $(a,b,a,b,b)$ is itself, because it is just a regular list. The unnesting of $(a,(b,a))$ is $(a,b,a)$. The unnesting of $((()))$ is $()$, the empty list. The unnesting of $((),a,())$ is $(a)$. The unnesting of $(a,(b,(a,(b))))$ is $(a,b,a,b)$. The unnesting of $((),a,(),b)$ is $(a,b)$. I could give some more examples, but I hope these examples are sufficient to get the general idea of what I mean. So, what is the corresponding formal and rigorous definition of this notion?
Answer: The "unnest" operation only makes sense if we have a way to distinguish lists from non-lists, via types or some other criterion, so that you know when to "stop flattening". We can define it recursively as:
$$
u(x)=
\begin{cases}
\text{the concatenation of the list of lists $(u(y))_{y\in x}$}
&\text{if $x$ is a list}\\
\text{the singleton list $(x)$} &\text{otherwise.}
\end{cases}
$$


Criar código de barras com imagecreate e html

Question: Tenho uma página que monta um código de barras, quero saber como fazer para ao invés da página retornar um html, ela retornar uma imagem.
Exemplo de como esta minha página:
<?php

$fino = 1;
$largo = 3;
$altura = 50;
$text = null;

$barcodes[0] = '00110';
$barcodes[1] = '10001';
$barcodes[2] = '01001';
$barcodes[3] = '11000';
$barcodes[4] = '00101';
$barcodes[5] = '10100';
$barcodes[6] = '01100';
$barcodes[7] = '00011';
$barcodes[8] = '10010';
$barcodes[9] = '01010';

for ($f1 = 9; $f1 >= 0; $f1--) {
    for ($f2 = 9; $f2 >= 0; $f2--) {
        $f = ($f1 * 10) + $f2;
        $texto = '';
        for ($i = 1; $i < 6; $i++) {
            $texto .= substr($barcodes[$f1], ($i - 1), 1) . substr($barcodes[$f2], ($i - 1), 1);
        }
        $barcodes[$f] = $texto;
    }
}

$text .= '';
$text .= '';
$text .= '';
$text .= '';
$text .= '<img ';

// Recebe os dados
$texto = addslashes(filter_input(INPUT_GET, 'linha', FILTER_SANITIZE_NUMBER_INT));

if ((strlen($texto) % 2) <> 0) {
    $texto = '0' . $texto;
}

while (strlen($texto) > 0) {
    $i = round(substr($texto, 0, 2));
    $texto = substr($texto, strlen($texto) - (strlen($texto) - 2), (strlen($texto) - 2));

    if (isset($barcodes[$i])) {
        $f = $barcodes[$i];
    }

    for ($i = 1; $i < 11; $i += 2) {
        if (substr($f, ($i - 1), 1) == '0') {
            $f1 = $fino;
        } else {
            $f1 = $largo;
        }

        $text .= 'src="../Img/p.gif" style="width: ' . $f1 . 'px; height: ' . $altura . 'px; border: 0; padding: 0; margin: 0;">';
        $text .= '';
        $text .= '';
$text .= '';
$text .= '';

$img = imagecreate(410, 55);

// Transparent background
$black = imagecolorallocate($img, 0, 0, 0);
imagecolortransparent($img, $black);

// Red text
$red = imagecolorallocate($img, 255, 0, 0);
imagestring($img, 5, 0, 0, $text, $red);

header('Content-type: image/png');
imagepng($img);
imagedestroy($img);

Answer: Pode usar a biblioteca https://github.com/picqer/php-barcode-generator, se estiver usando composer basta instalar na pasta do teu projeto:
composer require picqer/php-barcode-generator

Gerando um .png:
$barcodes = '000101010100010';

$generator = new Picqer\Barcode\BarcodeGeneratorPNG();
$generated = $generator->getBarcode($barcodes, $generator::TYPE_CODE_128);

Outros formatos:

SVG: $generated = new Picqer\Barcode\BarcodeGeneratorSVG();
JPEG: $generated = new Picqer\Barcode\BarcodeGeneratorJPG();
HTML: $generated = new Picqer\Barcode\BarcodeGeneratorHTML();

Tipos de códigos aceitos: https://github.com/picqer/php-barcode-generator#accepted-types

Alternativamente você pode usar o TCPDF (o php-barcode é baseado nele) seguindo os exemplos de https://github.com/tecnickcom/TCPDF/tree/master/examples/barcodes, não é necessário composer, basta baixar o TCPDF pelo repositório e fazer o include, assim:
<?php
require_once 'tcpdf_barcodes_1d_include.php';

$barcodeobj = new TCPDFBarcode('http://www.tcpdf.org', 'C128');

// exibe no navegador a imagem
$barcodeobj->getBarcodePNG(2, 30, array(0,0,0));

Answer: Você poderia utilizar o html2ps é a solução que conheço para gerar uma imagem do seu html.
 html2ps index.html index.ps
 convert index.ps index.png

Vai precisar instalar em seu servidor e executar com exec em background mas é uma solução a se pensar.
Pode obter aqui html2ps
Existe essa classe aqui também, ela facilita muito para escrever o código de barras em formato de imagem Classe Código de barras
Comment: Outra solução é escrever tudo com GD do php.
Comment: Entendo, é uma solução mas quero uma coisa bem simples com o código que postei.
Comment: Mas como vou colocar outras imagens? Com se trata de um código de barras que é montado a padres de 2 imagens gif. Tem algum exemplo de como fazer isso?
Comment: @HugoBorges O mais fácil é desenhar as barras do código uma por uma com [imagerectangle](http://php.net/manual/en/function.imagerectangle.php), na mesma lógica que você usa pra montar o HTML.


Android Unlock like Swipe Gesture

Question: How can I have something like Emulator Swipe to unlock Gesture? What I want is Animation where user will drag a circle left or right and base action on Whether it was dragged left or right. How can this be achived? Something similar to Unlock shown in image below.
Thanks,
Umesh
Answer: Have found one sample solution. Suggestion for similar good libraries is welcomed.
https://github.com/nadavfima/GlowPadView
Answer: there is a open source solution for you- https://github.com/pellucide/Android-Switch-Demo-pre-4.0 , hope will help. Good luck.
Comment: Or directly to SO: http://stackoverflow.com/questions/9752760/slide-toggle-for-android
Comment: This is a good example when we need toggle kind of solution. In this case I'm looking for Three modes. No Action at center and Left swipe and right swipe to do some action. More lick Simple Phone unlock gesture or Pick the Phone gesture etc.

Android Unlock like Swipe Gesture


Stochastic domination of the cluster size

Question: I have troubles understanding the main idea used to prove the following theorem, which should be a coupling argument.
My question refers to the following notes, at page 125.
http://www.win.tue.nl/~rhofstad/NotesRGCN2011.pdf
Theorem
For all $k\geq 1$ $$\mathbb{P}_{np}[T^*\geq k]=\mathbb{P}_{np}[\mid C(1)\mid\geq k]\leq\mathbb{P}_{n,p}[T^{\geq}\geq k]$$
where $\mathbb{P}_{n,p}$ is a $\text{Binom}(n,p)$-Branching process, $T^{\geq}$  is the total progeny of a binomial branching process with parameters $n$ and $p$, $\mathbb{P}_\lambda$ denotes the law of $ER_n(\lambda /n) \ (\lambda=np)$, also note:
$$C(v)= \{x\in [n]:v\leftrightarrow x\}.$$
We denote the size of $C(v)$ by $\mid C(v)\mid$, i.e., $\mid C(v)\mid$ denotes the number of vertices connected to $v$. The largest connected component $C_\text{max}$ is equal to any cluster $C(v)$ for which $\mid C (v)\mid$ is maximal, so that
$$\mid C_\text{max}\mid = \max_{v\in[n]} \{\mid C (v)\mid\},$$ $[n]=$Set of vertices of $ER_n(p)$.

Hier is the proof. I don't understand basically the argument of bringing the new r.v. $Y_i$ and taking the sum $X^\geq$.
Answer: You want to know something about $\sum_iX_i$. However, $X_i$ has a different distribution for different values of $i$, so this is difficult. Estimating $\sum_i X_i+Y_i$ is easier, since $X_i+Y_i$ has a $Bin(n,p)$ distribution for all $i$. So $Y_i$ is just an auxiliary variable to show that $X_i$ is dominated by a $Bin(n,p)$ variable.
I would say that there is a mistake in the proof though, I think that it should say $X_i\leq X_i^{\geq}$.
Then $P(\sum_i X_i-(i-1)\geq 0)\leq P(\sum_i X_i^{\geq}-(i-1)\geq 0)$, since $X_i\leq X_i^{\geq}$.
Comment: Wow I think it should be fine now. Thank you so much :D


Find/Replace - Not working when called from batch file. OK if run independently

Question: I have a question based on a previus question asked here.
I need to change registry key entries on multiple computers where REG GUIDs of said registry keys are different on every machine. I have found that I can pull the regkey into a .reg or .txt file, find the "Device_State" values, and replace them with what I want using a .vbs script similar to the one in the link I referenced above.
I cannot use any 3rd party solutions for this. It must be organic to Windows, by nature (Windows 7 and windows 10 is currently my env).
Problem
My Test.vbs script appears to work when I just have the .reg file in a directory, and run (double-click) the .vbs script (from same directory).
The script finds and replaces the strings I want and writes it all back to the .reg file (in this case, "replace.reg"). However, when I call it from my batch file, the .vbs script returns an error:

Line: 15  Char: 1  Error:  Invalid procedure call or argument
  Code:  800A0005 Source:  Microsoft VBScrpt runtime error

line 15, 1 in my code is: objFile.Write strNewText.
When I check the .reg to see what has changed, the file is now blank. It seems like the script is reading the content of the file into the strText variable, finding my values, replacing values, then erroring out and not writing back to the .reg file.
Batch file
My batch file does the following:

creates a directory for backup and to work out of
md c:\windows\patches
reg export "hkey_name" C:\windows\patches\backup\backup.reg

exports the registry key to a .reg file (and a separate .txt for reference) for actual manipulation of file content:
reg export "hkey_name" c:\windows\patches\replace.reg
reg export "hkey_name" c:\windows\patches\replace.txt

calls the .vbs script
@call cscript "%~dp0Test.vbs"

I have also tried
runas /user:localadmin /savecred "wscript.exe c:\windows\Patches\Test.vbs"

imports the new .reg into the registry (this is the plan; have not gotten this far yet).
reg import c:\windows\patches\replace.reg

VBScript
The Test.vbs script is as follows:
Option Explicit
Dim objFSO, objFile, strText, strNewText
Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpentTextFile("C:\Windows\Patches\backup.reg", ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "HKEY", "BLAH-BLAH")      '<—– this is just for testing function!
strNewText = Replace(strText, "LOCAL", "EAT_SOME_FOOD") '<—-just for testing function!

Set objFile = objFSO.OpenTextFile("C:\Windows\Patches\backup.reg", ForWriting)
objFile.Write strNewText
objFile.Close

MsgBox "Done"

So, again, to reiterate, the VBScript does exactly what I want when I run it independently. But when I call it from a batch file, it "wipes out" (or fails to write to) the file I need changed.
I am running this as an administrator of the local system, with full rights to the files in question.
I am running this from an elevated CMD prompt/window.
Question
Does anyone know why this would work independently of the batch file, yet not work when called by the batch file?  I'm thinking it has to have something to do with permissions or authority to open/close the file for reading/writing while "inside" a batch routine. I just don't know enough to figure it out.
***************************** UPDATE ************************************
I have narrowed this down even further and here is what I'm finding:
 -
1) I run my batch file that creates a backup of the registry keys I need to edit. The batch file creates a .reg file and a .txt file of the same registry keys (this is just for my own security to have both).  I'm also granting full rights to everyone, users, administrators on this folder/files
2)  I then run the find/replace text vbScript. It errors out on the line "objFile.Write strNewText". When it errors out it appears to wipe out the contents of the .reg file.
3) I found that if I take everything in the .txt file (same exact text) and paste into the .reg file (AFTER the vbscript errors out) and THEN run my script, it works.
I have tried manually deleting the .reg contents and replacing it with the .txt content and trying to run the script, and it errors out the same way and again appears to wipe out the contents of the .reg file. It's ONLY AFTER THE VBSCRIPT errors out on writing to the file, appears to wipe out the contents, that I can paste the contents of the .txt file into the .reg file and run the VBScript ... and it works.  I'm so confused by this.   I can't imagine what's going on. Please, I'm hoping someone else can help me. Thanks.
Comment: Do you have the typographical quotation marks `""` also in your script or only here in your post? note that you must use normal ones `""` in the code!
Comment: not related to your problem. But are you aware that your line 12) overwrites the result fo line 11) ?
Comment: Yes. The idea is that it searches for a value (dword:00000001) and replaces it with (dword:00000000). The next line in my actual script finds yet another value (dword:10000004) and replaces it with (dword:00000000)
That last thing it will do is find all dword:00000000 and replace with dword 10000001
It's the only way I could think of to simply find all the different possible states of that 'dword' that we have, and replace with the state I wanted.
Comment: Line 16 as you had previously numbered it was `objFile.Close` not `objFile.Write strNewText`.
Comment: The script errors out on objFile.Write strNewText
Comment: I'm just informing you that you told us what line 16 contained and later in the post you clearly showed us that on line 15. Incidentally, because you are mixing languages and using an exported NT Registry file, you may be better advised to reveal the actual registry information your trying to manipulate. This may provide an opportunity for a complete solution using one of the languages only, possibly both languages done differently or even utilising a different method or language completely.
Comment: Check type and value of the variables after reading the file and after the replacement.
Comment: If I can run the script and it works, what difference does it make with the quotes?   I have the correct quotes.   It simply doesn't work when called from a batch file.
Comment: Did you try the troubleshooting steps I outlined below?  What is the error message you are getting?
Comment: Sorry, I thought I already replied on that Jen R3 -  there are no error messages when I do what you specified. Batch file messages repeat what's on the screen (operation completed successfully) and the & StrNewText shows some funky symbols instead of the new text.
The script stops on "objFile.Write strNewText", char 1, "Invalid procedure call or argument, code 800A0005

I explained, after the script errors out and appears to empty the contents of the .reg file,I copy contents in from a backup .txt file, & run the script again successfully.
Comment: Seems like when the script first reads the content, it's in a different format or coding?  It looks like plain text to me, but the the return on the WScript.Echo & streNewText is something funky like...symbols.
Comment: OK. I am using Note++, and when I open the .reg file and look at "Encoding", it shows the contents to be "Encode in UCS-2 Little Endian".

After the file gets wiped out, and I copy the txt file contents in, the Encode shows, "Encode in UTF-8 without BOM"   whatever that means

I feel like this is the problem, and I'm not sure how to fix it.
Comment: YUP, that's it. If I run my reg export to the .reg file, open it with Note++ and convert the text to "UTF-8 without BOM", save it, and then run my VBScript, it works.  SO, I have to figure out how to automate this process.  there must be a way to convert the encoding on the fly ??? Anyone?
Answer: There is likely an error being thrown that you can't see. In your batch file, at the end of each line, add > output.txt, like so:
md c:\windows\patches
reg export "hkey_name" C:\windows\patches\backup\backup.reg > outputExport1.txt
reg export "hkey_name" c:\windows\patches\replace.reg > outputExport2.txt
reg export "hkey_name" c:\windows\patches\replace.txt > outputExport3.txt
cscript "%~dp0Test.vbs" > outputVBS.txt

This will dump any error information you would have seen in the command prompt to the output file.  Alternatively, you can manually run each line of your batch file in a command prompt and see what it says there.
Inside your script, you can add additional debugging outputs (and they will also either be dumped into your output file or display in the command prompt if you run it manually):
Option Explicit
Dim objFSO, objFile, strText, strNewText
Const ForReading = 1
Const ForWriting = 2

WScript.Echo "Reading the file"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpentTextFile("C:\Windows\Patches\backup.reg", ForReading)

strText = objFile.ReadAll
WScript.Echo "File Contents: " & strText
objFile.Close
strNewText = Replace(strText, "HKEY", "BLAH-BLAH")      '<—– this is just for testing function!
WScript.Echo "Did first replace: " & strNewText
strNewText = Replace(strNewText, "LOCAL", "EAT_SOME_FOOD") '<—-just for testing function!
WScript.Echo "Did second replace: " & strNewText

Set objFile = objFSO.OpenTextFile("C:\Windows\Patches\backup.reg", ForWriting)
WScript.Echo "Opened the File for Writing"
objFile.Write strNewText
WScript.Echo "Wrote the File"
objFile.Close
WScript.Echo "Closed the File"
WScript.Echo "Done"

Note that in the code above I corrected a bug you have in the second Replace - in the original code you are reusing the strText variable, which means the changes done by the first Replace are overwritten.


How do I move files from an ESXi datastore onto a VM?

Question: I uploaded two 15GB .WIM images onto my ESXi 6.0.0 datastore. I have a VM that I would like to image using those .WIM files from within a WinPE environment but can't access the files from within the VM (which does seem logical -- it would be a a security risk to allow access to the root drive from a VM). In any case, it's what I want to do. So I'm looking for workarounds.
I found an open source VMFS driver but it uses Java and WinPE doesn't have Java (https://code.google.com/p/vmfs/).
I thought of maybe mounting the .WIM files as a "ISO" (which doesn't quite work). vSphere will mount the file just fine, but if you try to navigate to the CD drive it complains that there is no filesystem (which is correct). I thought of maybe using DD to try a raw copy from the "mounted" WIM? It just seems like there should be a better way (and I'm not sure if DD will work in this case).
I want to try to avoid having to upload a 30GB ISO image of the two WIMs because it will take a day or two.
Comment: This sounds kind of like an XY Problem. What are you trying to do, and why do you need to upload the WIM to a Datastore?
Comment: I'm trying to apply a WIM image to a VM running on an ESXi server. I've already uploaded the WIM files to the datastore on the ESXi host hoping for a faster image application speed. I just can't access the files on the datastore from within my VM. I don't think this is an XY problem -- I'm asking if it's possible to access files on a datastore from within a VM. I wanted to show my research effort -- not get answers for my "solutions".
Comment: I think there's others ways to do this without using the datastore, but they might be a little more complicated. If this is a one-off task then it's probably not the end of the world, though you will spend quite a while finding a way to do it. If it's something you'll be doing often, I'd find a better, more supported, way.
Comment: @GregL Agreed. I should find a better way as this is not something I'll be doing often. In that sense, I guess it is a bit XY. Thanks for your input.
Comment: As for attacking X instead of Y, I'd suggest, in this case, having a "maintenance" VMDK where you store your images. You can modify its contents to it by attaching it to a management VM or mount it in windows using vmware-mount, then attach it to the VM you wish to use the WIM to image and boot into WinPE there, or even put WinPE in a VMDK and keep the WIMs and WinPE all in one spot. Or do something else entirely.
Answer: If you enable ssh on the esxi server then you can scp the files off into an attached vmdk either using winpe or another suitable bootdisc.
Comment: As far as I'm concerned, enabling SSH on an ESXi node should really only be done for emergency management purposes, not for trying to solve problems like this.
Comment: The only file transfer app included with WinPE is FTP, which won't work for this case.
Comment: @GregL not really, it is fine if used temporarily and turned off again, plus it should be behind a firewall
Comment: Your router probably supports TFTP and/or SSH, but you wouldn't dream of using it like this. ESXi hosts should be treated the same way. They're single-purpose appliances which have tools and systems to manage them. Using those tools for things other than their intended purpose, while feasible, shouldn't be done if a better way exists.
Comment: @GregL the point is he already has the 30GB file on there, whether he should have or not is a different matter. The main reason vmware discourage SSH is so that people pay them for their tools, there is nothing at all wrong with using it from time to time to fix something that hasn't gone to plan with the proper tool. Eg. Winding back version10 VMs is far far easier using ssh and vi to change one number in a textfile than the hoops the webclient makes you jump through.
Comment: I can't entirely agree with your comparison of tasks; one is a direct use of the tool to manage the system in question, one isn't. Just because he's already copied the files to the system doesn't mean he should continue down that path. Instead, it might serve him well to revisit why he copied them there in the first place and take a new approach to his intended outcome.


Centre Align text on main image/header boostrap

Question: I know there are answers for this and I have tried troubleshooting with provided answers.
However even with the bootstrap class "text-center" my h1 tag is still not in the middle of my screen vertically, only horizontally. here is the html with targeting css. Thanks

    #hero-area {
      background: url(../img/hero-area.png) fixed no-repeat;
      background-size: cover;
      color: #fff;
      overflow: hidden;
      position: relative;
    }

    #hero-area .overlay {
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0px;
      left: 0px;
      background: #61D2B4;
      opacity: 0.9;

    }

    #hero-area .contents {
      padding: 600px 0 130px;
      }

    #hero-area .contents h1 {
      color: #fff;
      font-size: 60px;
      font-weight: 600;
      margin-bottom: 25px;
      letter-spacing: 5px;
    }

HART FERTILITY CLINIC

HOLISTIC ASSISTED REPRODUCTION TREATMENT

CAPE TOWN

Answer: If you are working with the newest Twitter-Bootstrap you can easily look into the documentation for the grid. There you find a class called:
align-items-center

that centers your content vertically.
For more information:
https://getbootstrap.com/docs/4.0/layout/grid/#vertical-alignment


can't access a variable in outer function

Question: var _URL = window.URL || window.webkitURL;

var $file = FS.gID('failImage');

var imgSize = FS.gID('failImage');

var file, img, imgWidth, imgHeight;

if(file = imgSize.files[0]) {

 img = new Image();

    img.onload = function() {

        imgWidth = this.width;
        imgHeight = this.height;

    }

    img.src = _URL.createObjectURL(file);

}

 alert(imgWidth); //Comes out undefined.

Why can't I get  this variable to alert the imgWidth? note that I didn't set the var inside the child function and yet in the parent function when I go to alert the imgWidth it comes back undefined?
Comment: because onload is asyncrhonous - https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call
Comment: since onload is asynchronous function, it is not executed in sequence. if you put the alert inside the onload, you will get the value.
Answer: Because img load after this line executed alert(imgWidth);
solution is to move alert(imgWidth); inside the onload function.
if (file = imgSize.files[0]) {

    img = new Image();

    img.onload = function () {

        imgWidth = this.width;
        imgHeight = this.height;

        alert(imgWidth); // This should work

    }

    img.src = _URL.createObjectURL(file);

}

Or use a callback function
function afterLoad(width, height) {
    alert(width);
    alert(height);
}

if (file = imgSize.files[0]) {

    img = new Image();

    img.onload = function () {

        imgWidth = this.width;
        imgHeight = this.height;

        afterLoad(imgWidth, imgHeight);

    }

    img.src = _URL.createObjectURL(file);

}

Comment: There is no other way I can make it so I can alert that variable in the parent function. I ask this because I want to put the width and height along with my other check that I go through down toward the bottom of the script. So it would be way easier if I could write if(imgWidth < blablahblah) rather then doing it in another fucntion. The greater purpose is not to just alert it but use it for a check to make sure the image passes my requirements.
Comment: @JonW i know that you put `alert` as example for explain. Anyway you can but your compare code in the `afterLoad` function. Ex: `function afterLoad(width, height) {
    if(imgWidth < blablahblah) { ... }
}
`
Comment: Yeah problem with that is though if I put it inside the afterLoad() then the afterLoad child is the only one that has access to the width and the height. I just want to be able to set the imgWidth and imgHeight inside the parent function. But having to use onload forced me to put inside a child function. Just trying to figure out how I can then transfer back the results to the parent function.
Comment: @JonW " I just want to be able to set the imgWidth and imgHeight inside the parent function" you can not do that.
Comment: @JonW all your code that depend on the `onload` function contents should be inside it. (it = `onload` function)


Cook's distance vs. hat values

Question: What exactly does Cook's distance measure? And how is this different from what hat values measure?
I know hat values measure how distant a point it form its corresponding fitted point. I also know Cook's distance measures the influence of a point (whether it changes the fitted line) but what exactly does it measure?
I other words, what exactly is the difference between hat values and Cook's distance?
Comment: Does the Wikipedia entry https://en.wikipedia.org/wiki/Cook%27s_distance help you? perhaps come back and edit your question with a more specific query as it is a bit hard to see what level of explanation you are looking for.
Answer: The cook's distance is given by the formula:
$D_{i} = \frac{\sum_{j = 1}^{n} (\hat Y_j - \hat Y_{j(i)})^2}{pMSE}$
Where:

$\hat Y_j$ is the fitted value for the j observation;
$ \hat Y_{j(i)}$ is the fitted value for the j observation without including the i-th observation in the data that will generate the model;
p is the number of parameters in the model;
MSE ie the mean squared error of the model.

This means that the cook's distance measures the influence of each observation in the model,or "what would happen if each observation wasn't in the model", and it's important because it's one way of detecting outliers that affects specially the regression line. When we don't look for and treat potential outliers in our data, it is possible that the adjusted coefficients for the model might not be the most representative, or appropriate, leading to incorrect inference.
The hat values are the fitted values, or the predictions made by the model for each observation. It is quite different from the Cook's distance.
Answer: Cooks distance shows how much the whole regression model would change if $(x_i, y_i)$ is removed. I am not quite clear what you mean by "hat value". Do you mean $e_i = y_i - \hat{y}_i$, or $h_{ii}$ in the hat matrix $H$ (i.e. leverage)? Either way they are different from cooks distance.
Note that cooks distance takes the form
$$D_i = \frac{e_{i}^{2}}{s^{2} p}\left[\frac{h_{ii}}{(1-h_{ii})^2}\right]$$,
so it's related to both residual $e_i$ and leverage $h_{ii}$. Large $D_i$ could be due to large $e_i$ or $h_{ii}$, or both.
Possible reasons for
large residual $e_i$: $y_i$ far from fitted value (possibly outlier)
large leverage $h_{ii}$: $x_i$ far from other $x_{j}$'s (influential point due to the value of $x$)

Cook's distance vs. hat values