Prove that $f_A (x) = d({\{x}\}, A)$, is continuous.

Question: Prove that:

Let $(X, d)$ be a metric space, and let $A$ be a subset of $X$. The function $f_A\colon X\rightarrow \mathbb{R}$, defined by $f_A (x) = d({\{x}\}, A)$, is continuous.

Honestly, I have NO idea where to start. I need to prove that inverse of an open set in $\mathbb{R}$ is open $X$. What it makes it hard to approach is the definition involved: $$d(A, B) = \operatorname{glb}\{d(a, b)\mid a \in A, b \in B\}.$$
Would someone please guide me how to solve this question?
Thank you.
Comment: See also http://math.stackexchange.com/questions/48850/continuity-of-the-function-x-mapsto-dx-a-on-a-metric-space and http://math.stackexchange.com/questions/400487/continuity-of-dx-a
Comment: @Martin Sleziak: Neither questions nor (esp.) answers are same as here. I couldn't find my answer from those, but I learnt a lot by answers of here.
Comment: And what exactly is the difference? You ask how to show that $x\mapsto d(x,A)$ is continuous. That is the same question as in the post I linked to. (The only minor difference is that in one of them the posts adds a superfluous requirement that $A$ is closed. And one of the questions mentions Lipschitz contidion.) BTW I don't think that slightly different wording of answers should mean that the questions are not duplicates. And Ivo Terek's answer (which is accepted at the moment) is almost the same as [Zarrax' answer](http://math.stackexchange.com/a/48879/8297) at one of the posts I linked.
Comment: [Pedro Tamaroff's answer](http://math.stackexchange.com/questions/418042/show-that-the-function-f-x-to-bbb-r-given-by-fx-dx-a-is-a-continuo/418052#418052) in another post about the same question is very similar to the accepted answer, too. And I am pretty sure that you could find a few minor variations of this answer in [other linked questions](http://math.stackexchange.com/questions/linked/48850).
Answer: The idea is to use the reverse triangle inequality: $$d(x,a) - d(y,a) \leq d(x,y), $$given $x,y \in X$, $a \in A$. But notice that $d(x,A) \leq d(x,a)$, so we get: $$d(x,A) - d(y,a) \leq d(x,y).$$Reorganize: $$d(x,A)-d(x,y) \leq d(y,a).$$Now take the infimum on $a$: $$d(x,A) - d(x,y) \leq d(y,A).$$Reorganize: $$d(x,A) - d(y,A) \leq d(x,y).$$Since $x$ and $y$ were arbitrary, we can swap the above inequality to obtain: $$d(y,A)-d(x,A) \leq d(y,x) = d(x,y).$$This gives: $$|d(x,A)-d(y,A)| \leq d(x,y).$$Now let $\epsilon > 0$, and check that $\delta = \epsilon > 0$ will work in the definition of continuity. Since $\delta$ does not depend on $x$ and $y$, the function is actually uniformly continuous (which is even better).
Answer: Since $f_{A}$ is a map between metric spaces (each with the topology induced by its metric), we can use the $\epsilon$–$\delta$ definition of continuity: $f_{A}$ is continuous at a point $x\in X$ if for all $\epsilon>0$ there exists $\delta>0$ such that $|f_{A}(y)-f_{A}(x)|<\epsilon$ if $|x-y|<\delta$.
So, take any $x\in X$ and any $\epsilon>0$. Consider $y$ near $x$. Intuitively we expect $f_{A}(y)$ to be close to $f_{A}(x)$. We can show this formally using the triangle inequality, which tells us that $d(y,a)\leq d(y,x)+d(x,a)$ for all $a\in A$. Rearranging, $d(y,a)-d(x,a)\leq d(y,x)$. By the same argument, $d(x,a)-d(y,a)\leq d(y,x)$, so that $|d(y,a)-d(x,a)|\leq d(y,x)$. Because this holds for all $a\in A$, we can say that $|f_{A}(x)-f_{A}(y)|\leq d(x,y)$. In particular, $|f_{A}(x)-f_{A}(y)|$ will be less than $\epsilon$ whenever $d(x,y)<\epsilon$. Thus, $f_{A}$ is continuous at $x$. This holds for all $x\in X$, so $f_{A}$ is continuous.


What instrument is Stevie Wonder playing in this video?

Question: In this CBS This Morning video Stevie Wonder is talking about Aretha Franklin who has just recently passed, after a long and profound life.
What instrument is in front of him? I've never seen anything like it.
It appears to have strings, is long an flat on a table in front of him, with strings starting in front of him and extending forward directly away from him.
Video: Stevie Wonder reveals his last words to Aretha Franklin before she died
Answer: I think this instrument is a harpejji. SW had an endorsement deal with the makers.
Comment: Oh, the "strings" and "frets" are electrical contacts?
Comment: It looked like an overgrown steel guitar to me - though playing steel guitar entirely by hammering-on the strings was a novelty!
Comment: They're strings,  the playing technique is mainly 'tapping'. But check on the maker's website.  SW  endorses the instrument.

https://www.youtube.com/watch?v=3D89RpfwcEA&feature=youtu.be&list=UUV3VKY6Zh-rV6E7AXFcf_Tg


Is JavaScript pass-by-reference or pass-by-value?

Question: Is JavaScript language a pass-by-reference or pass-by-value language?
Also is it different for primitive types Vs for objects ?
Answer: It uses an evaluation strategy named call by sharing actually.
All types are passed by value. There's no pass-by-reference, otherwise you'd be able to modify contents of variables declared at the call site of a function. Usually people say that objects are passed by reference in JS. They're actually passed by sharing, which means you can modify an object's properties, and these changes will be visible to those that hold a reference to that object, but the reference in itself is not modifiable.
Comment: Which is akin to saying that you're given a pointer to an object, and you can then modify that object's properties, from the current scope, but if you try to reassign the value of the object, internally, you're merely resetting your pointer.
Answer: Objects are passed by reference while primitives are passed by value.
Note, that primitive values include the following:

number
String
boolean
undefined
null

You can find some more details at MDN on Functions.
Comment: Everything in JavaScript is passed by Value. It's just that when  you pass an Object, you are passing the reference to the Object, not the Object itself, so a copy of the reference is passed. Even the MDN link you shared states this.
Answer: Everything but primitives are passed by reference.
Just about everything in JavaScript is an object.
As Sirko said, Objects are passed by reference.
So functions/arrays/objects are all passed by reference, whether you're talking about the root object attached to a var, or you're talking about an object's property/method, chained 3 dots deep, or you're talking about an object in an array, as a property of an object, in an array of objects...
Comment: Everything in JavaScript is passed by Value. It's just that when  you pass an Object, you are passing a COPY (which is pass by value) of the reference to the Object, not the Object itself, so a copy of the reference is passed.
Comment: @ScottMarcus That's ... really not helpful to someone who is learning JS. You're getting into particulars of how a C++ / Rust VM runtime is going to manage access to memory.

Generally, people asking this question want to know "If I pass in an array, and then I change an element of the array, outside of the function has the original array changed" and the answer is, of course, yes.

Whether a smart-pointer (or equivalent) is copied or passed in directly doesn't change the language behaviour, in terms of new-user expectations.
Comment: On the contrary. As someone who has been a professional IT trainer for over 30 years and worked with JavaScript since Netscape invented it, I can tell you with certainty that my comment is exactly what new learners need to hear as there is much confusion over this, not only in JavaScript, but also in .NET and other languages. **Your (and Sirko's) answer is wholly incorrect.** JavaScript has no pass-by-reference and that was exactly what the OP was asking about. My comment in no way gets into particulars of how C++/Rust handles memory. My comment is clear and to the point.
Comment: You are most likely having the same confusion that many do, which is that there **are** "value types" (primitives) and "reference types" (objects), but both types are **passed** by value, not by reference.
Comment: I'm not confused. At all. I am aware that there is no differentiation, _technically_. People asking these questions tend to be early in their journey and have picked up terms from people who teach everything as if everything was built up from C, or viewed through the lens of C. JS has no concept of pointers, so passing a copy of a pointer has no meaning to someone who is coming to JS from, say, Scratch, or Haskell (aside from C-interop modules). I'm not about to suggest they learn Rust's borrow-checker, or C++ Move semantics, even a decade later, pedantically accurate or not.
Comment: My assumption is that they picked up these questions after hearing them used by young Java developers who picked them up from some developer (or teacher) who has built their career around ASM (presumably MIPS) and C/C++ (presumably pre auto, constexpr, lambda, and device independent values), and thus feel like the question is actually relevant to writing good or idiomatic code in the language (which I find works better like an ML where the question is moot). Either they're really asking about mutability or about the ECMA-262 spec re: calling-semantics. Which would you suspect as a teacher?
Comment: Furthermore, is the job of a teacher to Intuit the meaning behind a student's inquiry, and help them understand at a level that meets them where they are at, and encourages further exploration in a direction that is safer/more productive for the individual's level, or is it to parrot technical rote, until they get it? I can tell you my kindergarten Quantum Physics studies did not go well.
Comment: You've added a bunch of (largely) irrelevant technical information that only serves to confuse the learner. The question is quite clear "Is JavaScript pass-by-reference or pass-by-value?".  It doesn't take an educator to read that and understand that the OP already knows what passing by vale or reference means. Probably the best advise I can give anyone who seeks to inform/educate others is to Keep It Simple, which my answer does quite concisely.
Comment: It's hard to believe that you aren't confused when your post quite clearly states *"Objects are passed by reference while primitives are passed by value."*, which is false. And then you say *"I am aware that there is no differentiation, technically. "*, which only serves to further confuse the reader.
Comment: Additionally, when you say that JavaScript doesn't have pointers, it again informs the reader that you are confused about how JavaScript works. Of course the language has pointers, that's what object variables store (reference/pointer to the memory location of the object). It's just that they are implemented differently than other languages, but they certainly do exist. JavaScript is probably one of the most misunderstood languages and it's extremely important to be clear and concise when communicating information to newbies.
Comment: The reader is you. If you are confused by me saying "technically", that is on you and your ability to operate within different contexts. JavaScript has no pointers in its syntax. There are no language structures for creating, nor manipulating pointers. Your assumption that implementation details are equal to language features is nonsense.
Comment: Your "keep it simple" introduces a concept (pointers) which DO NOT EXIST WITHIN THE GRAMMAR OF THE LANGUAGE, but rather the implementation details thereof, requiring foreknowledge of other languages and their workings. My "simple" gets at the root of the question "If I modify values in a function are they modified after the return", without said foreknowledge. "pass by sharing" is better than "reference", sure, but is the same thing, in the implementation. I do not assume"pass by value/reference" is a learned individual, because 0 people ask that question in most circles.
Comment: I am extremely comfortable with any reader reading the comments I have written. The fact that you are all over the place with what you believe JavaScript does and does not have and does and does not do tells me that you really don't understand the language. Good luck to you.
Comment: [javascript pointers](https://linuxhint.com/javascript-pointers/)
Comment: JavaScript does not have pointers. You do not have direct memory access to a particular portion of memory, short of doing something like provisioning a contiguous array, via an `ArrayBuffer`. You can not increment a reference with pointer arithmetic. You can not otherwise expect contiguous allocation, nor contiguous access. WeakRef is as close as you get to direct pointer access. You pulling up a blog post saying "call 'ref' 'pointer'" changes none of that.
Comment: Moreover, I have no problem with other people reading these comments. Note how your comment had "you" in it, as in, addressed to me, and given that there are only 500 characters per comment, your recent comments contain the context of prior comments... That's how communication works, as I am sure you know. Tailoring the amount of detail provided to the recipient of the information is also how conversation works. It's why front-end devs aren't expecting to harvest silica and copper and have blast furnaces...
Comment: Wow, you really like to add complexity where none is needed as well as to change your position just enough to be able to defend an incorrect statement. It boils down to this (for the reader's benefit), you clearly stated that objects are passed by reference, **they are not**. You stated that JavaScript has no pointers, **it does**. As I said, the implementation is different, but pointers do exist as object references. That's all I want readers to know - - what's correct about the language, not misinformation.
Comment: That is not _remotely_ correct.
Comment: JS does not have pointers. You can not access a pointer. Moreover, when you get passed x, where x is a number, it must be a pointer by your statement, as it is passed as a pointer, right? Because JS has pointers? So why is it that when I increment `x` the outer scope does not change? "It's a copy of a reference " yeah, well, you said that "reference === pointer", didn't you. So a copy of a thing pointing to the same address in RAM continues to point to the same address in RAM. The pointer itself is new, but the address it points to is not. So why are you incorrect? It's a ref, after all.
Comment: You claim to want to avoid complexity, and yet, you treat the specification of the language, and the implementing VMs of the language as the syntax and grammar of said language, and your "simplicity" only applies to people coming to the language from one where pointers exist, and they understand interned constant values (from those other languages). "If I change x.y inside a function is it changed outside, too" is dirt simple. You are bringing the burden of extra languages with you.
Comment: Note that my explanation is not technically correct, and I admitted that it does not match calling semantics of the spec, nor does it match the particulars of V8, Spider Monkey, Chakra or Core. It matches the *behaviour* of the language. Yours carries not only baggage of other languages and prior knowledge, but also massive caveats and concessions. Like "it has pointers, but not pointers you can access or use or modify, and they only work on objects and not numbers but the blog says ref === pointer". You destroy intuition, like a teacher berating 5th graders for missing electron spin.
Comment: [Sigh] With every comment you make, you make it more clear that you don't really understand JavaScript. When `x` is a `Number` (note the capital "N"), it is a ["primitive wrapper object"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), which is an Object that wraps a primitive value and primitive values are immutable, so that's why the internally stored **value** of `x` doesn't change.
Comment: If you try [a valid example](https://jsfiddle.net/jg9r4v07/) with an object that doesn't store an immutable value, you can clearly see that what you have been saying doesn't work and can't be done, in fact works and is done all the time... BECAUSE JAVASCRIPT HAS POINTERS - just not implemented in the way they are in other languages. Finally, YOU are the one who has introduced other languages (and pointers) into this conversation. My simple, clear and concise comments remain unequivocally true: **JavaScript does not pass object by reference** and **there are pointers in JavaScript**.
Comment: `const add1 = x => x++; let y = 5; add1(y);` nowhere is there a capital. Nowhere is there a dot. Nowhere is there a new. Why doesn't this pointer work? It's a copy of a ref, right? And a ref is a pointer, right? It is surreal that you want to teach everyone, regardless of their prior history with programming, that this example, here, is pointer-based.
Comment: And nowhere is there an object! Your example is with primitives, which, when passed, pass a copy of the primitive value itself!
Comment: Ohhhhh. Say that again.
Comment: Why? I've been saying that all along?! We've been talking about OBJECTS BEING PASSED BY VALUE AND WHAT THAT ACTUALLY MEANS.
Comment: No. We have not. We have been talking about any value, at all, in the language, being passed in. Just because you presume OO does not mean that my answer precluded all of the things you were too pious to consider. So come on, tell me why 5 doesn't increment. Louder. For the cheap seats.
Comment: *JS does not have pointers. You can not access a pointer. *  <-- Do you understand what implementation details are? My car has a big old cover over the engine, making it impossible for me to get at the spark plugs without special tooling, while my other (older car) exposes the plugs. Does that mean that the car with the engine cover doesn't have an engine? Of course not! It's just not "implemented" the same way and I can't interact with it the same way in all cars.
Comment: Oh boy, now you're ability to read your own posts has declined. I'm actually getting concerned for you. You have been all over the place. I've simply been addressing the incorrect part of your ***"Objects are passed by reference while primitives are passed by value."*** post. To which I replied **"Everything in JavaScript is passed by Value. It's just that when you pass an Object, you are passing a COPY (which is pass by value) of the reference to the Object, not the Object itself, so a copy of the reference is passed."**
Comment: Yes, I understand what implementation details are. Does JS also have vtables, then? Does JS have bare pointers or smart pointers? Does JS use modern float32/float64, or is it more like old fashioned "long long" and "float" types that are architecture ambiguous?
Comment: Now you want to change the topic to the behavior of objects that wrap primitives and how primitives are passed? Really? Ok, well I've had enough of your trolling. Good luck in whatever endeavors you engage in (I really hope it isn't JavaScript).
Comment: If you had any idea how much all of your pedantry literally does not matter and how many times I have been contracted to fix the code written by people I am sure we're trained by you...
Comment: Let's try one last time.... What is the answer to this question:  "If I change x.y inside a function is it changed outside, too?" And, what about the following statement is incorrect: "Everything in JavaScript is passed by Value. It's just that when you pass an Object, you are passing a COPY (which is pass by value) of the reference to the Object, not the Object itself, so a copy of the reference is passed."
Comment: Funny enough that when I have taught this concept to literally thousands of complete newbies, engineers and architects relating to languages like C#, VB.NET and JavaScript, they all seemed to get it without more than the last sentence of my prior comment. You are literally the first person who wants to scream at the wind and protest what is demonstrably true.


hook_module_implements_alter() to put hook implementations into separate files - bad practice?

Question: In a number of modules I wrote, I use hook_module_implements_alter() to split up the *.module file, and to move hook implementations into separate files.
The main reason is that I passionately hate long files. (and yes, this does make me unhappy about a lot of the files in Drupal 7 and contrib)
Examples:

nestedbox_core_module_implements_alter()
xautoload_module_implements_alter()

I know there are a few things to consider:

It might not work for all hooks. E.g. boot or install, or hooks that are not called via module_implements().
It is important to include the respective file from within the hook_module_implements_alter() implementation, due to the way that module_implements() works.

Now I heard from a long-time and well-known Drupal developer that this practice is problematic. https://drupal.org/node/2230319 (topic starter, and comments #5 and #11).
Before I start moving functions around, I would like to hear from others whether and why this is bad, both technically and aesthetically.
EDIT:
I guess this could be split in two questions:

Is it good or bad to split up your *.module file, so that hook implementations live elsewhere?
Is hook_module_implements_alter() reliable enough, or should I rather use include_once __DIR__ . '/MYMODULE.filename.inc' directly in the *.module file? What could possibly go wrong by using hook_module_implements_alter() for this?
Comment: I want others to weigh in on the split, but I think it may be good.  I am really in the why of #2.
Comment: (btw, some of what is in the answer is stuff i already know, but that is nevertheless relevant and essential to make this useful for other people. And they confirm that splitting up is a common practice. So both get +1 from me.)
Answer: I just found the piece of information that was missing.
EDIT: And another one.
Problem with module_invoke()
module_invoke_all() always calls module_implements(), which checks the module include file by checking both hook_hook_info() and hook_module_implements_alter().
However, module_invoke() only checks hook_hook_info() and not hook_module_implements_alter().
module_invoke() is called e.g. in _block_render_blocks() for hook_block_view().
This means that hook_module_implements_alter() is not a good solution to split a hook_block_view() implementation into a separate file.
This has been a problem in Crumbs, see https://www.drupal.org/node/2328535.
For other hooks it generally works ok, but you never know if a specific module wants to use module_invoke() instead of module_invoke_all().
module_implements() cache polluted in bootstrap.
Another problem is caused by a core issue reported here:
module_implements_cache() can be polluted by hook_boot() implementations calling module_invoke_all() directly or indirectly
This applies only to non-boot modules, where it can happen that the implementation of hook_module_implements_alter() is never discovered.

An unexpected chain of events causes module_implements($hook) being called from hook_boot().
The $hook can be any random hook, it does not need to be related to the module we are working on.
This causes module_implements('module_implements_alter') to be called.
Drupal looks for all implementations of hook_module_implements_alter().
At this time, MODULENAME.module is not included yet.
Therefore, for the rest of the request, Drupal assumes that the implementation MODULENAME_module_implements_alter() does not exist.
Later in the request, implementations of other hooks are being discovered, but the implementations by MODULENAME are not being found, because MODULENAME_module_implements_alter() is not being executed.

Alternatives
require_once
Alternatives have already been mentioned. Instead of these tricks, one can include the file directly. There may be a tiny performance impact but this is probably overshadowed by a lot of other things in Drupal.
But, instead of using module_load_include(), I would suggest a more direct solution:
require_once __DIR__ . '/crumbs.block.inc';

Or to be PHP 5.2 compatible:
require_once dirname(__FILE__) . '/crumbs.block.inc';

Why not module_load_include()?
There is generally no need to call module_load_include(), it could even be detrimental, if the *.module file is included from you-dont-know-where (e.g. from settings.php), and you don't know if module_load_include() is available.
This function is mostly there to help you determine the location of other modules. But if you are including within the same module, it is generally safer and easier and faster to work with relative file paths and explicit require_once.
Call to helper function
As mentioned by Jimajamma, you can also implement the hook in the main *.module file, and then include another file and call a helper function from there. This is done e.g. in Display suite.
This solution is ok, although I think it still clutters the main file, and gives you even more places to look.
And here likewise you can use require_once instead of module_load_include(), if it is within the same module.
Comment: Thanks for the thoughtful breakdown. I needed a helpful shove to get me to consolidate a half dozen related but separate custom modules for a client into one. I think I'll stop trying to over think it, and simply `require` the extra files. A good naming convention for these files will help, too, and then the whole thing becomes much more parsible.
Comment: Why would you combine different modules into one? Separation is good! (depends, of course)
Comment: Oh separation of concerns is a must! And modules that can remain abstract (I.e be modules), should. On this particular project, I seem to have at one point thought that the same paradigm applied to the business logic that was unfolding and evolving within the app. It's not really the same case, and several of the modules aren't *really* modules but collections of PAC logic that make no sense without each other.
Comment: Why don't you use [`hook_hook_info_alter()`](https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_hook_info_alter/7) instead? Do the same considerations/problems apply if I use `hook_hook_info_alter()` to split the hook implementations in a separate file?
Comment: hook_hook_info_alter() applies to all implementations of this hook. Thus, it will have unintended side effects on other modules.
Answer: Any major project I have worked on has broken things up into manageable and easily assignable pieces; basically ending up like @tenken mentioned here, or to the point where foo.module ends up being only includes:
<?php

module_load_include('inc', 'foo', 'foo.defines');         // bring in our define()s
module_load_include('inc', 'foo', 'foo.HOOK1');           // bring in our HOOK1 functions
module_load_include('inc', 'foo', 'foo.HOOK2');           // bring in our HOOK2 functions

// ...etc

Of course, I have also seen, and used, situations where admin only or otherwise rarely used hooks are included like:
function foo_HOOK(/* $args */) {
  module_load_include('inc', 'foo', 'foo.HOOK');
  return _foo_HOOK(/* $args */);  // _foo_hook() is defined in foo.HOOK.inc
}

Comment: yes, seen that and done it myself. both of it. although I recently prefer just include_once \_\_DIR__ . '/filename.inc'. So.. i guess we are clear then about question 1, it is far from unorthodox to split stuff up. Remains question two, whether anything bad could happen if you use hook_module_implements_alter() for that. Or how big the performance benefit could be for not including the file on an average request, where e.g. hook_menu() is not called.
Comment: Btw I don't personally like the _foo_HOOK() trick all too much, it makes me look in two places instead of one..
Comment: Btw, you can simplify to module_load_include('defines.inc', 'foo'). But what's lrfm?
Comment: lol, lrfm was the module I cut and pasted that out of and forgot to change to foo :)
Comment: as for your simplification, yes, that would certainly work, but the first argument is supposed to be the type of file, and per the examples in https://api.drupal.org/api/drupal/includes%21module.inc/function/module_load_include/7, I imho doubt what the "drupal powers at be" intended, but certainly less typing.
Comment: I think the person who originally designed this function meant it to be used exactly like I suggest. But this is so weird and ass backwards that noone else actually picks up on that, including those writing the doc page.
Comment: https://drupal.org/node/697946
Comment: well, to each his own, the end result is that this is just a fancy wrapper for figuring out how to define `$file` in an eventual `require_once $file;` :)
Answer: If I try to breakup my .module file across multiple files I tend to do what Features for D7 does for its "included" files which it uses include_once() for:
include_once('MYMODULE.features.inc');

For D7 I still use my module's name "function namespacing" for these included files, and private module functions typically are prefixed as "_MYMODULE_foo()".
This answer kinda ignores your desired use of Autoloading classes and any OO related patterns you're trying to use within your code (code dependencies, etc).
In your linked issue it sounds like you want to use hook_module_implements_alter() to be a readable index of what files have what functions in your .module file. I think sane 'MYMODULE.PURPOSE.inc' filenaming is enough to clue a developer of the use of that include file within your module.
Comment: @donquixote if you are thinking about performance, then install APC or other opcode cache and don't bother with splitting so much.
Comment: The idea is to include the respective file only when it is needed. I am thinking about performance there, but I don't know the actual performance impact. I guess with APC or similar it does not make a big difference, but I never measured it.


Texto dentro de uma picturebox

Question:
Quero fazer isso nas PictureBoxes pra quando eu passar o mouse ela mostrar a mensagem que eu escrevi.
Como posso fazer?
Lembrando utilizo a versão Visual Basic 2010
Comment: Bruno, você não precisa usar a tag `visual-studio` nesse tipo de pergunta. Veja bem, o Visual Studio é apenas a ferramenta (IDE) que você usa para programar (C#, VB.NET, F#, etc.), seu problema é em `VB.NET`, logo é esta tag que deverias usar. Se tiveres confuso quanto a isso, dê uma lida nas respostas [desta pergunta](http://pt.stackoverflow.com/q/101691/18246)
Comment: eu botei ,a tag ,visual-basic-2010,axo que bugou
Comment: Você deve ser se confundido, porque esta tag não existe. Mas enfim, já está corrigido, só quis lhe informar mesmo =D. A resposta serviu para você?
Answer: Você pode usar um ToolTip para isso.
Primeiramente arraste um ToolTip da ToolBox para o seu form - ele não será mostrado dentro do form, e sim num rodapé, veja a imagem

Agora todos os componentes do form têm uma propriedade chamada ToolTip on toolTip1 (ou qualquer que seja o nome do ToolTip que foi adicionado anteriormente.
Pronto.
Agora só é necessário definir essa propriedade com o texto que queres que apareça na ToolTip.

Texto dentro de uma picturebox


Does the name of an interval change if the notes are in different octaves?

Question: The interval between C and G is a perfect fifth (P5).
But if the G is in a different octave does the interval name stay the same?
Comment: No. The interval from a C to the G an octave and a half above is a twelfth. If the G is even higher you need to describe it by saying something like "...from the C to the G three and a half octaves higher."
Of course if the G is BELOW the C it becomes a perfect fourth if it's close, an eleventh if it's in the octave below, and needs to be described if it's even lower.
Comment: @OldBrixtonian Any particular reason why that's a comment? That could have been an answer right there. You pretty much answered all parts of OP's question, and then some.
Comment: @user45266 Just modesty! And if I convert it to an answer now it'll mess up the threading. But thanks for your kind words.
Comment: I've never thought about this, but the question is legitimate: we name the intervals up to 16 but then we add the numbers of octaves.
Answer: One concept that I might add is the distinction between simple and compound intervals.
Simple intervals are intervals of one octave and smaller; compound intervals exceed the span of an octave.
So this C up to G is a fifth. If we move the C down an octave (or the G up an octave), this becomes a twelfth, but we can also call it a "compound fifth," meaning that it's a fifth, but one larger than an octave.
To quickly translate between simple and compound versions of intervals, just remember the "Rule of 7": subtract or add by 7 to move octaves. Thus an 11th is actually just a compound fourth, because 11-7=4.
Comment: Now we're talking. Never heard of that.

Rule of Seven = Modulo 7.
"In computing, the modulo operation finds the remainder after division of one number by another (called the modulus of the operation)."

https://en.wikipedia.org/wiki/Modulo_operation
Comment: @RandyZeitman Exactly! What we call "diatonic space" is really a mod-7 space, which allows this Rule of 7 to take place. Good catch!
Comment: @Richard   Yep! That is exactly how I describe it in my upcoming video about learning music theory. Keys are a helix and each segment is found by 'inclusive counting, by 5's, in base-7'.

1-2-3-4-5(key! G)
             5-6-7-(8/1)-2 (key! D)
                               2-3-4-5-6 (key! A)
Answer: Any interval is the space between two notes. For naming, two facts are needed. Names of notes, and number of semitones between them.
So, it stands to reason that the interval name for C>E (M3) will not be the same for C>an E an octave higher.That is M10.
In every case, half the interval name stays the same! C> any E will always be M, but the number attached will vary.
Answer: If C stays in the same place and G goes an octave higher, then yes, names changes. But if bouth of them moves to one side, then they don't change
Comment: Yes, then they wouldn't be in different octaves.
Answer: The intervals are counted in the first 2 octaves like this:
1 - Prime
2 - Sekunde
3 - Terz
4 - Quarte
5 - Quinte
6 - Sexte
7 - Septime oder Septe
8 - Oktave
9 - None
10 - Dezime
11 - Undezime
12 - Duodezime
13 - Tredezime oder Terzdezime
14 - Quartdezime
15 - Quintdezime oder Quindezime oder Doppeloktave
Source: German wiki site
https://de.wikipedia.org/wiki/Intervall_(Musik)


MSSQL Incompatibility with Organic Group Views Filter Handlers

Question: I have a view which filters all the organic groups for a user. I wanted to add a Views Filter to filter by OG Role, however it is not possible.
I would very much appreciate any help. Basically any OG Role filter using a Views Filter Handler cannot be used if the database is an MSSQL database. When selecting one of the filters, it errors out and then the view has to be re-created since the view can no longer be shown within the UI. I opened a drupal issue a few months ago, but no response as of yet.
The error message is as follows:

PDOException: SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Column 'og_role.rid' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.: SELECT r.*, r.name AS _field_0 FROM {og_role} r GROUP BY r.name; Array ( ) in og_handler_filter_user_roles->get_value_options() (line 14 of C:\inetpub\wwwroot\sites\all\modules\og\includes\views\handlers\og_handler_filter_user_roles.inc).

I'm almost postive that I have to rewrite Line 13 to support SQLSRV database types.
Line 13: ->groupBy('r.name')
Here is the relevant code:
/**
 * Field handler to provide a list of OG roles of a user.
 */
class og_handler_filter_user_roles extends views_handler_filter_many_to_one {

  function get_value_options() {
    $this->value_options = array();
    // Get all role names.
    $results = db_select('og_role', 'r')
      ->fields('r')
      ->groupBy('r.name')
      ->execute();
    foreach ($results as $result) {
      $this->value_options[$result->name] = $result->name;
    }
  }

  function query() {
    // Get the og_membership table from relations.
    foreach ($this->query->relationships as $alias => $info) {
      if ($info['table'] == 'og_membership') {
        // If there is a og_membership table present. Add some conditions.
        $rel = $this->relationship;
        $this->query->add_where_expression(NULL, $alias . '.gid = ' . $rel . '.gid');
        $this->query->add_where_expression(NULL, $alias . '.group_type = ' . $rel . '.group_type');
        break;
      }
    }

    parent::query();
  }
}

Comment: This question appears to be off-topic because it is a bug report for a module, and should be reported in module's issue queue. Reporting bugs here is forbidden, see [help center](http://drupal.stackexchange.com/help/on-topic).
Comment: Ok then please close the help request. I only submitted it, because I felt it was a way to also learn how to patch issues such as this for the future, but if it doesn't belong, then it no longer needs to remain open. Thanks for the prompt response.
Comment: if you want to learn how to patch etc, it might be OK, but, also in help center, there is a requirement to provide relevant parts of code if you are asking how to fix code. If you identified the place that causes this error, you may edit relevant part into your question, then tell us what have you tried to make it work, and expect us to answer :) That you are welcome to do, all right.
Comment: Close vote retracted, and edited it a bit to improve formatting. Good luck. Have you tried adding `->groupBy('r.rid')` just after `->groupBy('r.name')`?
Comment: Amazing. Thank you very much. As soon as I added that, it shows that another one was missing, and then another, etc. etc. Line 13 is now:       ->groupBy('r.name')->groupBy('r.rid')->groupBy('r.gid')->groupBy('r.group_type')->groupBy('r.group_bundle'). Thank you very much. Would you like to add the answer, or should I?
Comment: As I have said long ago - if I guess in comments, it means it's just a guess, and whoever did the real work of trying and testing things should get all the rep ;) You did it, you post it :) And don't forget to post it in the issue queue as well.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/12027/discussion-between-nwom-and-molot)
Comment: Please do NOT edit answers into a question, and avoid "chameleon" ones. If you are convinced it is not answered yet, please edit it in a way that does not look like "answer in question" issue.
Answer: I fixed it by changing Line 13 to:
->groupBy('r.name')
->groupBy('r.rid')
->groupBy('r.gid')
->groupBy('r.group_type')
->groupBy('r.group_bundle')

Comment: Please try to use code syntax for code. And no need for a "thank you" in answers :) if you really feel you need, put it in comment (just don't get surprised when it's get deleted)


shortcut keys not working for PyCharm

Question: I have installed VirtualBox -> Centos6.8 -> PyCharm.
The shortcut keys like Ctrl+c or any other is not working for PyCharm. When i press Ctrl+s then Centos settings window in invoked.
How can i change the key mapping?
Comment: might help https://www.jetbrains.com/help/pycharm/keymap.html
Comment: @yklsga i tried it. still no result.
Comment: Are you facing this problem only for pycharm or everything?
Comment: just with PyCharm
Answer: All I would like to say is that the solution is simple:
Turn off Vim Emulation in the Tools menu
Comment: This answer is suitable as a comment rather than an answer.
Comment: thnks. will take care from next time.

shortcut keys not working for PyCharm


PostgresSQL - Can't Insert values into table - ERROR: INSERT has more target columns than expressions

Question: there were a lot of related questions to this topic, but none of the ones I found could solve my issue.
I'm just trying to run a file to create a table in my database "test_scheduler".
The table is created just fine; however, when I run the file to seed the table with boolean values... nothing happens and I receive an
ERROR:  INSERT has more target columns than expressions

Here is the file that creates the table:
DROP TABLE IF EXISTS operation;

CREATE TABLE operation (
  id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
  monday INTEGER NOT NULL DEFAULT FALSE,
  tuesday BOOLEAN NOT NULL DEFAULT FALSE,
  wednesday BOOLEAN NOT NULL DEFAULT FALSE,
  thursday BOOLEAN NOT NULL DEFAULT FALSE,
  friday BOOLEAN NOT NULL DEFAULT FALSE,
  saturday BOOLEAN NOT NULL DEFAULT FALSE,
  sunday BOOLEAN NOT NULL DEFAULT FALSE
);

Here is the Seed File:
TRUNCATE operation;

INSERT INTO operation
  (monday, tuesday, wednesday, thursday, friday, saturday, sunday)
  VALUES
    (FALSE),
    (FALSE),
    (TRUE),
    (FALSE),
    (FALSE),
    (FALSE),
    (FALSE);

I previously added created and seeded two tables in this same database as well. I've poured over this seed file and I just am not sure what to do.
Here is the full statement and error:
psql:C:/Users/Eli/Desktop/SQL/seed.operation-hours.sql:11: ERROR:  INSERT has more target columns than expressions
LINE 2:   (monday, tuesday, wednesday, thursday, friday, saturday, s...

I've tried different variations of the create and seed files, for instance, I've forgone "NOT NULL", "DEFAULT", I've set the default values to "false", false, '0',etc.
Nothing I do in the files makes a difference.
I appreciate any and all help!
Answer: Your code is inserting seven rows with one value each rather than seven columns into one row.  The syntax you want is:
INSERT INTO operation (monday, tuesday, wednesday, thursday, friday, saturday, sunday)
  VALUES (FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE);

Comment: @ezg if it helped you solve your problem, consider accepting the answer.
Comment: Thank you!! I'm new to SQL, as you can tell, I really appreciate your answer!
Comment: Sorry, forgot to do that! Thanks again!


how to get info about an rq worker working on a remote redis

Question: I'm trying to run the rq info command, but I want to get info on a remote redis machine. how do I specify the url of the redis machine?
Answer: turns out this is simple but undocumented:
rq info --url redis://my-server-stage.blah.0001.use1.cache.amazonaws.com:6379 -R

That '-R' there tells the command to list info about all existing queues.


Spark code giving wrong matrix multiplication result

Question: I have two matrices {1,2,3;4,5,6;7,8,9} and {1,4;2,5;3,6}.
The following code is a matrix multiplication in apache spark. But it is giving me wrong output as {15.0,29.0;36.0,71.0;57.0,113.0}. I want to know where I am done mistake?
    JavaRDD<String> lines = ctx
            .textFile(
                    "/home/hduser/Desktop/interpolation/Kriging/MatrixMultiplication/MatrixA.csv")
            .cache();

    JavaRDD<String> lines1 = ctx
            .textFile(
                    "/home/hduser/Desktop/interpolation/Kriging/MatrixMultiplication/MatrixB.csv")
            .cache();

    JavaRDD<Vector> rows = lines.map(new Function<String, Vector>() {

        @Override
        public Vector call(String line) throws Exception {

            String[] lineSplit = line.split(",");
            double[] arr = new double[lineSplit.length];
            for (int i = 0; i < lineSplit.length; i++) {
                arr[i] = Double.parseDouble(lineSplit[i]);
            }
            Vector dv = Vectors.dense(arr);
            return dv;
        }

    });

    //rows.saveAsTextFile("/home/hduser/Desktop/interpolation/Kriging/MatrixMultiplication/MatrixA_output");

    RowMatrix A = new RowMatrix(rows.rdd());

    JavaRDD<Vector> rows1 = lines1.map(new Function<String, Vector>() {

        @Override
        public Vector call(String line) throws Exception {

            String[] lineSplit = line.split(",");
            double[] arr = new double[lineSplit.length];
            for (int i = 0; i < lineSplit.length; i++) {
                arr[i] = Double.parseDouble(lineSplit[i]);
            }
            Vector dv = Vectors.dense(arr);
            return dv;
        }

    });

    List<Vector> arrList = new ArrayList<Vector>();
    arrList = rows1.toArray();

    double[] arr1 = new double[(int) rows1.count() * arrList.get(0).size()];
    int k=0;
    for (int i = 0; i < arrList.size(); i++) {
        for (int j = 0; j < arrList.get(i).size(); j++) {
            arr1[k] = arrList.get(i).apply(j);
            //System.out.println(arr1[k]);
            k++;
        }
    }
    Matrix B = Matrices.dense((int) rows1.count(), arrList.get(0)
            .size(), arr1);

    RowMatrix C = A.multiply(B);

    RDD<Vector> rows2 = C.rows();
    rows2.saveAsTextFile("/home/hduser/Desktop/interpolation/Kriging/MatrixMultiplication/Result");

Thanks in advance...
Comment: If you run your code in a debugger, how does `arr1` look like? Please give a more self-contained example. The order of elements in your array may just be wrong. You can use an array literal in our example.
Answer: Matrices.dense constructs a column-major matrix (API doc), and you are traversing the array of rows in the wrong order.
I cannot look into your CSV files, but I guess you have a typo there as well. Why?
B has to be [1 3; 4 5; 2 6] in order to produce the wrong output, therefore the array has to be {1,4,2,3,5,6}, so MatrixB.csv probably contains:
1,4
2,3
5,6

(3 and 5 are switched)


replace multiline string with regex using python

Question: My code doesn't work, its output 's still the same
from sys import argv
import re

script, filename = argv
f = open(filename, "r")
str = f.read()
f.close()
str2 = re.sub("<start>.*</start>","aa",str,re.DOTALL | re.M)
print str2

Test file
<start>
</start>

Comment: You say it doesn't work. But you have not said what your code is supposed to do? Or how it is not working, what else are you getting?
Answer: As per Python docs fourth argument in re.sub is not regex flag but a count.
This should work:
>>> print re.sub(r"<start>.*?</start>", "aa", str, 0, re.DOTALL)
aa

Or with compiling regex first:
>>> regex = re.compile(r"<start>.*?</start>", re.DOTALL)
>>> print re.sub(regex, "aa", str)
aa

Or even this should work:
>>> print re.sub(r"<start>[\s\S]*?</start>", "aa", str)
aa

btw avoid parsing HTML using regex as it can be error prone in some cases.
Answer: I'm not sure what your intended outcome is, but if you are trying to replace everything between <start> and </start> then the following would work:
text = """<start>
</start>"""

print re.sub(r'(\<start\>).*(\<\/start\>)', r"\1aa\2", text, flags=re.DOTALL | re.M)

This would give you:
<start>aa</start>

You should really escape the < and > characters in your regular expression. It is also better practice to use a with statement when dealing with files:
from sys import argv
import re

script, filename = argv

with open(filename, "r") as f:
    text = f.read()

text2 = re.sub(r'(\<start\>).*(\<\/start\>)', r"\1aa\2", text, flags=re.DOTALL | re.M)
print text2

This will take care of closing your file automatically. Lastly it is best not to use a variable name of str as it shadows Python's str() builtin function.


How can I make Elo ranking system more diversified?

Question: As far as I know, Elo ranking system generates points between 100-2800 generally.
However lets say we have 1,000,000 players. Now this range of points is too small. Many players would get the same score
I want to prevent this happening. How should I modify the algorithm?
What I want is having a higher range of values so players would not get equal scores but rather get different scores?
Comment: It seems from the Wikipedia article that you referenced that two players can have the same ELO ranking.  Why would you want to prevent two players with equal skill to have different ranks?  That doesn't make much sense to me.  Theoretically you could have dozens of equally skilled players.  In that case ranking them without duplicate ranks would simply be an exercise in randomization and wouldn't be of much value.  If you can clarify how you would want to treat equally skilled players, we might be able to provide a better answer.
Comment: Evidently you could just show decimal places for the ratings (or multiply all scores by e.g. 10) to have more granularity, but honestly it hardly matters when people are within a few Elo. Also, whether ratings are within a certain range (say, always >0 or >100 or >1000) is an extremely arbitrary decision that is made by the organisation running the rating system. If they did not impose the restriction (there's nothing in the basic system that really requires this) some people might have negative Elo. I suppose, they feel would be bad for the motivation of people, which is the reason for that.
Comment: To expand on showing decimal places or the like: One problem with doing so is that the precision with which you have estimated the rating (even if people were to stay at a constant skill, did not vary in form from day to day, etc.) with a lot of imprecision and you end up giving a number to a precision that is a lot higher than the uncertainty around it making the apparent extra precision pretty meaningless.
Comment: @Björn well i am planning to have score based ranking and if many players get same score, how can i rank them? :D
Comment: @StatsStudent you are right but i have to rank the people and if many people gets the same rank it causes some quite confusion
Answer: In Elo, the starting rating is arbitrary, it doesn't matter what number you pick. So, if you start from an higher value (e.g. $R_0 = 1500000$), use a big constant value (e.g. $K = 12000$) and a big denominator for expected score formula, e.g.
$$E_A = \frac 1 {1 + 10^{R_B - R_A \over 400000}},$$
you've got a more granulated custom Elo.
I think there's no problem if many players would get the same score, indeed. In our ranking system rankade (here's a comparison between our ree and most known rating systems), public displayed scores have 4-digits format (e.g. $2134$), but calculation features many decimals and ranking works with real values.
Comment: ty for answer so this seems the only way. i guess i can make everything 10 times bigger. like the k value 320 and starting value 4000 and the denominator 4000
Comment: If $K=320$ and $d=4000$, I suggest you a bigger starting value, to avoid negative values.


merge 2 seperate arrays matching keys

Question: I need to take the values in the fist array at the top and insert them into the bottom array and assign the key as url when they merge. How can I do this?
I tried array_merge_recursive(), but that didn't seem to do it.
Before
$batchedDomains = Array
(
    [0] => http://www.domain.com/1/
    [1] => http://www.domain.com/2/
)

$json_a = Array
(
    [0] => stdClass Object
        (
            [pda] => 91.1624138732
            [upa] => 1
        )

    [1] => stdClass Object
        (
            [pda] => 91.1624138732
            [upa] => 1
        )

)

After
Array
(
    [0] => stdClass Object
        (
            [pda] => 91.1624138732
            [upa] => 1
            [url] => http://www.domain.com/1/
        )

    [1] => stdClass Object
        (
            [pda] => 91.1624138732
            [upa] => 1
            [url] => http://www.domain.com/2/
        )

)

Comment: Did you try something? there are several ways to accomplish such!
Comment: You should try and post your code with as much information as possible. There are several ways to accomplish this and it is quite simple.
Comment: The hardest part is that since the second object is an stdClass object you can't access its properties using brackets, but you need to use arrows and curly brackets, that's the hardest part, the rest is just a foreach loop. Also, the PHP source can be slightly more helpful there to work on
Comment: so sorry I have not had my morning coffee yet. This is for php and I have tried from `array_merge` `array_merge_recursive` as well as `array_push`
Comment: @CesarBielich Why do you have 2 times the same url in your expected output?
Comment: typo sorry, I edited it
Answer: This should work for you:
Just loop through both arrays with array_map() and add the property url to the stdClass object $v1 with the value $v2.
<?php

    $json_a = array_map(function($v1, $v2) {
        $v1->url = $v2;
        return $v1;
    }, $json_a, $batchedDomains);

    print_r($json_a);

?>

output:
Array
(
    [0] => stdClass Object
        (
            [pda] => 91.1624138732
            [upa] => 1
            [url] => http://www.domain.com/1/
        )

    [1] => stdClass Object
        (
            [pda] => 91.1624138732
            [upa] => 1
            [url] => http://www.domain.com/2/
        )

)

merge 2 seperate arrays matching keys


Automate the creation of settings.php and files directory

Question: I am using Drush make files and Drupal Installation profiles to streamline the creation of new Drupal websites (which are created in the sites directory of my Mac).
Everything is working fine. The Drush make file automatically downloads Drupal and all the modules I normally use on each site.
However, for each new Drupal website, I have to create a files directory and a settings.php file and then set them to writeable.
Is there any way I can automate this process, so these files are created when Drush downloads the files for the Drupal website?
Answer: Try using the drush site-install command. Name your installation profile with the command argument.
Answer: I use Aegir (http://www.aegirproject.org) for managing my multisites, it not that hard to setup and provides various benefits, automated creating of settings.php and files/ directory being part of them. It also provides you web interface for managing your webistes, creating backups, restoring them, managing versions and migrations...
EDIT:
It also supports make files.


Etymology of crotchet

Question: A crotchet in British English is one beat - a quarter in American English.
In French, the very similar word croche means a quaver (eighth note), just half the value of a crotchet.
The two words are too similar for them not to have come from the same root word - which is French for crooked, bent, hooked; a crochet is a little hook, we use the same word for a kind of knitting. Now, a crotchet (English) looks less like a hook than a quaver, so pictorially, the French term is pretty accurate. (They call a one beat note la noire (the black), again a more descriptive term)
Question - why and how did we end up with crotchet as the English term for that note value?
Question number 20,000! Well, it would've been...
Comment: Does this answer your question? [Where did the British names for different note lengths come from?](https://music.stackexchange.com/questions/12437/where-did-the-british-names-for-different-note-lengths-come-from)
Comment: Are you sure this is the 20000th? It writes 19999 here…
Comment: Because Frenchies are more logical :P ? (What do you mean, you say that because you're french?! How dare you?)
Comment: The first sheet music was embroidered on cloth. In more sedate English music the most common note was the quarter note while in livelier French music it was the eighth note. QED :-)
Comment: Yes, why did you across the pond end up with *crotchet* when "quarter note" is clearly the better name? :-D
Comment: Adam Neely knows the answer: https://youtu.be/JEFi4SatXso
Comment: @Tom - it was at the time - one got deleted. Never mind!
Comment: @Tim If you delete this one you might still be able to make it! But that would be a shame…
Comment: Excellent question, but -1 due to the false claim of 20,000! Shameful! :-) (And, actually, isn't there an language/etymology SE? Seems like a good place to post.)
Comment: @Aaron - not really. I checked that a couple of days ago.
Comment: Note that [Michael Scott Cuthbert's answer](https://music.stackexchange.com/questions/12437/where-did-the-british-names-for-different-note-lengths-come-from/12457#12457) to the above-linked question explains why "crotchet" came to be used for a "non-hooked" note.
Comment: Also, those interested in this question might also enjoy [Where did the symbols ♭ and ♯ originate from, and why those?](https://music.stackexchange.com/questions/46391/where-did-the-symbols-and-%e2%99%af-originate-from-and-why-those) and [Where does the tradition of bowing after a performance come from?](https://music.stackexchange.com/questions/41530/where-does-the-tradition-of-bowing-after-a-performance-come-from).
Comment: @Aaron - putting all the snippets of information together gives me a pretty good answer. Not sure why the French and English decided to differ.
Comment: @Tim Because it's the French and the English. What more answer do you need. :-)
Comment: @Aaron - I guess at the time composers, conductors and other musicians travelled freely between U.K and Europe. And would have been keen to achieve some parity. Or not.
Answer: Etymology is rarely a precise science.  For instance, in my part of the world there are two places with 'Chadwell' in the name, and the consensus is that the 'Chad' part of each has an entirely different derivation!
But we know that in mensural notation, the note that was half the length of a minim could be written as an open note with a hook or a filled one without.  So one language may well have assigned 'hook' to the old notation, the other to the newer one.

https://www.britannica.com/art/musical-notation/Evolution-of-Western-staff-notation#ref530062
Comment: That is all fascinating stuff. And we think our system's difficut enough! Still trying to determine why the French croche is ony half the value of the English crotchet. Devaluation..? And entemology...close to something insectish, I guess!
Comment: Because, as I said, the British picked up on the old 'hooked' note, the French on the new one. (Must we confuse the issue with a rapidly-corrected mis-type?  :-)
Answer: In the copied image of Laurence we can see that the values and note lengths have been diminished about 50% from earlier notation.
The brevis was half as long as the lunga (imperfect)
The next division was the semi brevis that optically ressembles to the whole note.
Actually "la breve" in french  is the half note and resembles to the minima. Now the next division is the fusa and it had also a hook. This explains that this division - the half value of a breve is called the crotchet referring to the quarter note, division of the half note, while  la croche in french refers to the
black notation and the english term seems to be derived of the white  notation.

CROTCHET, a note which is half the value of a minim, and twice that of a quaver, and is represented thus (figure rythmique noire hampe bas.svg). The origin of the name is not known. It is apparently derived from the French croche; but croche is a quaver, (figure rythmique croche hampe bas.svg) and is so called on account of the hook at the end of its tail, whereas a crotchet has no hook. The French name for this note is noire, the Italian, semi-minima, and the German Viertel, 'a quarter'—i.e. of a semi-breve.

https://en.wikisource.org/wiki/A_Dictionary_of_Music_and_Musicians/Crotchet

Etymology of crotchet


secure communication between accounts

Question: if we create a transit gateway connection between between two VPCs (same or different regions and different accounts) without using VPN attachments, can this still be considered as secure because this is within AWS networks.
In all the diagrams that I could find, there's no VPN between VPC's.
Please provide the reference which says it is secure or not. I couldn't find any.
Answer: Transit Gateway does not encrypt data between accounts. However, it's over the AWS backbone which many people consider sufficiently secure. Whether it's secure enough for you depends on your risk appetite and compliance requirements.
Application level encryption (eg TLS) over Transit Gateway is usually one of the easier ways to achieve encryption in transit over TG.
If you want encryption in transit for all traffic between accounts you can set up VPN connections. There are different models, some with appliances on EC2 instances, some using the AWS built in services, but from memory I don't think you do it all with AWS services - at least not last time I looked. I do recall seeing that AWS can initiate a VPN connection recently, but not sure if that helps.

secure communication between accounts


How do I allow a device to only connect to certain wifi networks?

Question: I have been assigned to a task that a laptop should be connected to particular wifi Network, i.e Laptop should not connect with any other wifi network other than office wifi. is that possible??? any help could be appreciated...
Comment: What OS? Windows or Linux? AD joined or not? Does the user have admin rights?
Comment: In windows, joined AD, for admin user and standard user both..
Answer: https://www.maketecheasier.com/block-wifi-network-windows10/
<code>netsh wlan delete filter permission=allow ssid="WiFi Network Name" networktype=infrastructure

netsh wlan delete filter permission=denyall networktype=infrastructure
</code>


Find all $n$ for which a polyhedron with $n$ edges exists

Question: Accroding to https://plus.maths.org/content/eulers-polyhedron-formula-1 :
$2E \ge 3F$ and $2E \ge 3V$.
Using these facts and the Euler's formula $V+F-E=2$, we get that $n+2 \le \frac{4n}{3}$, but this gives $n \ge 6$, which is incorrect.
Comment: Where do you get $2F \geq 3V$? I only saw $2\color{red}{E} \geq 3V$ in the linked article.
Comment: @VTand , my mistake.
Comment: Could you elaborate on why $n \geq 6$ is incorrect? What you have found is that a polyhedron must have at least $6$ edges. No conclusion has been made on whether *all* $n \geq 6$ will work.
Comment: @VTand, in the same article it is proven that for n=7, there is no polyherdon.
Comment: Yes, but as I said, those two inequalities and Euler's formula are only able to conclude that $n \geq 6$. This $n \geq 6$ is a *necessary* condition, but not a *sufficient* condition.
Comment: I agree. This was my attempt.
Answer: Any $n \geq 6$, except $n = 7$, will work.

For even values of $n$, simply consider the pyramid with $(n/2)$-gon as its base.

For odd values of $n$ with $n \geq 9$, start with the pyramid with $n-3$ edges. Cut a small corner around one of the base's vertices. This will generate $3$ extra edges, bringing the total number of edges to $n$.
Comment: @JeanMarie What is a simplex? [What I found on Wikipedia is different from a pyramid](https://en.wikipedia.org/wiki/Simplex); we're dealing only with 3D objects here. Also, the link you provided for $n = 7$ is exactly the link on the question, so that's why I didn't mention it again in my answer.
Comment: Error(s) of mine. I Delete my remarks.


Choose a point $(X,Y)$ uniformly in the unit disk. What is $\rho(X,Y)?$

Question: Solution in the book:

The joint pdf is $f(x,y)=1/\pi.$ Denote the unit disk by $D$ to obtian
$$E[XY]=\frac{1}{\pi}\iint_Dxy \ dxdy.$$
which we realize must be $0$ by symmetry. Also, by symmetry,
  $E[X]=E[Y]=0,$ so we get $\text{Cov}[X,Y]=0$ and hence also $\rho(X,Y)=0.$

Questions:

How would one show that $f(x,y)=1/\pi?$
How did they get the dobule integral expression for $E(XY)?$ Is it the analouge for having a single random variable, for example:
$$E(X)=\int_{-\infty}^{\infty}x\cdot f(x) \ dx, \ \text{so} \ \  E(XY)=\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}xy \ dxdy \ ?$$
The reason that $E[X]=E[Y]=0$, is it the following:

The marginal pdfs are
$$f_X(x)=f_Y(x)=\int_{-1}^1\frac{1}{\pi} \ dx=\frac{2}{\pi}.$$
So $$E(X)=E(Y)= \frac{2}{\pi}\int_{-1}^{1}x \ dx = 0 \ ?$$
Comment: The area of the unit circle is $\pi$.
Answer: Let $(X,Y)$ denote the random point on the unit disk.
Convince yourself that dependent random points $(-X, Y)$ and $(X, -Y)$ have the same distribution as $(X,Y)$.
It now follows that $\rho(X, Y)$ and $\rho(X, -Y) = -\rho(X, Y)$ must be equal, which is only possible is $\rho(X,Y)$ assumes a particular value.
Comment: +1 for elegance.
Answer: When we are dealing with a uniform distribution over a given set (in this case the disk), the probability density is given by one over the (Lebesgue) measure (or volume / area) of that set.
In your example, the disk $D$ has total area of $\pi$, and hence the joint density of $X$ and $Y$ is
\begin{align}
f_{X,Y}(x,y) = \frac{1}{\pi} I_{D}(x,y),
\end{align}
where $I_D(x,y)$ is the indicator function of the set $D$, i.e., $I_D(x,y) = 1$ if $(x,y) \in D$ and zero otherwise.
Just as an aside, if you would deal with the unit ball $B$ in three dimensions you would have for example the density
\begin{align}
f_{X,Y,Z}(x,y,z) = \frac{3}{4\pi} I_{B}(x,y,z).
\end{align}
To compute the expectations you can indeed use the law of the unconscious statistician (https://en.wikipedia.org/wiki/Law_of_the_unconscious_statistician):
\begin{align}
\mathbb{E}[g(X,Y)] = \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} g(x,y) f_{X,Y}(x,y) dx dy,
\end{align}
where $g$ is a suitable (measurable) function, for example $g(X,Y) = XY$.
Together with the density this is then enough to derive the results.
To get the marginal density of $X$ you can check:
Uniform distribution on unit disk
Combining all of that should help you to derive the results.
Comment: No problem. I think you should double check your marginals, there might be something you can learn from the link. Good luck with the detailed calculations.
Answer: ${\bf Obvious\ Answer}$:
$$
{\left[x^{2} + y^{2} < 1\right] \over \pi}\quad
\mbox{where}\ \left[\cdots\right]\ \mbox{is an}\ Iverson\ Bracket.
$$


apache mod rewrite issue with document root

Question: I'm currently redirecting everything to app/index.html because I have a client-side single page app. However, I want to skip redirecting for actual files and directories. I've gotten this far. However, when I add in the RewriteCond for skipping files that are directories, it counts the document root as well. This causes a visit to a document root such as hitting http://localhost:8080 to just list my dir contents. How would I get this to not apply to the document root or any other better way? P.S. I'm also skipping the /api dir.
Here is what I have so far:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/api
RewriteRule ^(.*)$ /app/index.html/$1 [NC]

So essentially I guess what I'm asking is: How can I skip directories except for the document root directory?
Solution
With help from the answer that Krist van Besien gave I was able to come to a solution.
# not a directory
RewriteCond %{REQUEST_FILENAME} !-d [OR]
# or if it is the document root
RewriteCond %{REQUEST_URI} ^/$
# not a file
RewriteCond %{REQUEST_FILENAME} !-f
# not /api
RewriteCond %{REQUEST_URI} !^/api$
RewriteRule ^(.*)$ portal/index.html/$1 [NC]

Comment: Instead of updating your question to add the solution, you should better post an answer with the solution, remove it from your question and accept your own answer. It's better for the community :)
Answer: You could add a RewriteCond:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/api
RewriteCond %{REQUEST_URI} !^/$
RewriteRule ^(.*)$ /app/index.html/$1 [NC]

Answer: I would suggest changing this line:
RewriteRule ^(.*)$ /app/index.html/$1 [NC]

To this; note the ^ is removed:
RewriteRule (.*)$ /app/index.html/$1 [NC]

Comment: Out of curiosity, why does removing the beginning of line ^ matter? Is that to take account for whether there is a leading / or not based on if it is in a .htaccess file versus a vhost or similar?
Comment: Yes, exactly as you describe.


Book recommendation for linear optimisation

Question: I am currently in a linear optimisation class that uses a lot of the simplex algorithm and things relating to it. The book we are using is called Linear Optimisation The Simplex Workbook but it is beyond confusing and seems very poorly written to introduce someone to the area. I am looking for a book on linear optimisation that is better written and explains stuff well (i.e. talks about feasibility, dual-simplex, simplex, etc). I have asked my professor but he told me he likes this book and did not give me another recommendation, so I am stuck and frustrated trying to learn from the book and his notes (based off the book).
Comment: I highly recommend Bertsekas' Introduction to Linear Optimization. It has a the full theory of linear programming and simplex method (+ other methods) and written in a very clear and comfortable manner
Comment: For linear programming, you might check out Vandenberghe's UCLA course EE 236a notes. http://www.seas.ucla.edu/~vandenbe/ee236a/ee236a.html
Comment: What is your background? Which mathematics and/or computer science courses have you studied? Does the class you're in focus on using software, writing your own code, mathematical proofs, applications of linear optimisation, or other aspects?
Answer: Here are two excellent books
Linear and Nonlinear Programming 2nd Edition
by David G. Luenberger  (Author)
Convex Optimization – Boyd and Vandenberghe
https://web.stanford.edu/~boyd/cvxbook/
Answer: In addition to the good recommendations given by Daniel S., may I suggest Understanding and Using Linear Programming by Matousek & Gärtner. It is a relatively small book (222 pages including an appendix on linear algebra, glossary and index), which might be an advantage.
Answer: I would recommend Linear Programming 1: Introduction by Dantzig and Thapa. Dantzig created the simplex method, and the book serves as both an introduction to operations research and linear programming.
https://www.springer.com/gp/book/9780387948331


Stop redirect_to and link_to from controller method ruby

Question: May be my question would be awkward but i am new to ruby.
I am working on a project. My task is that when in table status has value "submitted" then the link "advance_status" shouldn't be clicked or redirected or render.
I know logic will be implemented in controller but what should i write in my advance_status method in the controller?
Answer: In your controller you can do something like:
<code>def advance_status
  if thing.status == 'submitted'
    # Redirect to previous page if status is 'submitted'
    session[:alert] << 'This is not allowed'
    redirect_to :back and return
  end

  # Other code...
end
</code>
Comment: Isn't there a way so that the link behind the Advance Status could be disabled. I mean if user still clicks on it so it may not render nor redirect nor page refresh, just like clicking on a simple text in a website
Comment: Well, you can disable or hide a link, but a user can still enter the URL manually and visit the page. Therefore, you have to have a check in the controller action.
Comment: thanks zwippie i just changed session[:alert] to flash[:alert] and it worked perfectly...thanks


How do I store data from a stream in Cassandra if I don't know the structure of the data?

Question: I want to know how to apply key-value store using cassandra.
If I have stream of data and I don't know the architecture and structure of it then how to save it using cassandra key-value store and with java code and how is actually work
Answer: To use cassandra as a naive key-value store, use a simple schema:
CREATE TABLE kvstore (
    key text,
    value text,
    PRIMARY KEY(key)
)

You can use type blob instead of type text if you know you'll have binary data.
Cassandra's strengths, though, are in clustering. If you consider this very similar schema:
CREATE TABLE kvstore (
    key text,
    version int,
    value text,
    PRIMARY KEY(key, version)
)

This gives you a very similar key/value store, except all of the value s for a given key will be sorted naturally by version - you can select just a single version (SELECT * FROM kvstore WHERE key=? AND value=?) or all of the values for a given key (SELECT * FROM kvstore WHERE key=?).


Centralizar uma div circular dentro de uma outra div

Question: Boa tarde !!
Gostaria de fazer com que uma div circular ficasse centralizada em uma outra div maior, ela está focada na esquerda
podem me ajudar??

 .conteudo-externo{
  width:200px;
  height:200px;
  z-index:3;
  background:#ff1;
  float:left;
 }
 .conteudo{
  width:100px;
  height:100px;
  border-radius:50%;
  border:3px solid #000;
  z-index:5;
  background:#000;
  position:left;
  background-image:'images\j2.png';
  }
  .img{
   z-index:1;
   width:130px;
                        height:130px
                        background-position:center;
   opacity:0.5;
  }
<!doctype html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Teste</title>

Comment: Não existe float: center amigo.
Comment: :'(, vou editar lá
Answer:

.conteudo-externo{
  width:200px;
  height:200px;
  z-index:3;
  background:#ff1;
  float:left;
 }
 .conteudo{
  width:100px;
  height:100px;
  border-radius:50%;
  border:3px solid #000;
  z-index:5;
  background:#000;
  position:left;
  background-image:'images\j2.png';
    margin: 50px auto;
  }
  .img{
   z-index:1;
   width:130px;
                        height:130px
                        background-position:center;
   opacity:0.5;
  }
<!doctype html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Teste</title>

Comment: Perfeito !!! muito obg !!!
Comment: apenas para conhecimento, a altura foi em hard code porque ele não consegue pegar automaticamente. A fórmula é a seguinte: Margintop = Altura_Contener - (Altura_objeto/2)
Answer: Você pode fazer assim...

.conteudo-externo{
  width:200px;
  height:200px;
  z-index:3;
  background:#ff1;
  float:left;
 }
 .conteudo{
  width:100px;
  height:100px;
  border-radius:50%;
  border:3px solid #000;
  z-index:5;
  background:#000;
  position:left;
  background-image:'images\j2.png';
      margin: 0 auto
  }
  .img{
   z-index:1;
   width:130px;
                        height:130px
                        background-position:center;
   opacity:0.5;
  }
<!doctype html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Teste</title>

Answer: A propriedade "position" não pode receber o valor "left";
Fiz pequenas mudanças na classe 'conteudo':
.conteudo {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    border: 3px solid #000;
    z-index: 5;
    background: #000;
    /*
    position: left;
    background-image:'images\j2.png';
    */
    background-image: url('images\j2.png');
    margin: 50px auto;
}

Na propriedade margin passei 2 parâmetros (50px e 'auto').

O 50px significa a margem do eixo Y, ou seja, 50px de margin-top;
O 'auto' centraliza o elemento, mas só funciona se o elemento pai estiver com 'width' definido;

Espero ter ajudado;
Comment: Aaaah, entendi, muito obrigado @Veber, não tinha conhecimento disso !! vou ajustar aqui o restante


Centralizar duas divs com texto

Question: Tenho a seguinte estrutura:
HTML

Nenhum resultado encontrado para:

"teste"

CSS
    .contatoTopo{
      background-image: url('../imagens/contatoBG.jpg');
      background-repeat: repeat;
      height: 176px;
      line-height: 176px;
      margin: auto;
      width: 100%;
  }
.buscaConteudoCent {
  width: 960px;
  height: 100px;
  margin: auto;
  position: absolute;
  left: 50%;
  margin-left: -480px;
}
.buscaFontEncontraTit {
  font-family: 'ubuntulight_italic';
  font-size: 30px;
  color: white;
  text-align: center;
  margin: auto;
  float: left;
}
.buscaFontEncontra {
  color: #FFFFFF;
  font-family: 'ubuntubold_italic';
  font-size: 30px;
  text-align: center;
  float: left;
}

O que está acontecendo, ele não está centralizando as duas divs com os textos:

A palavra 'teste' é um exemplo, virá do sistema e poderá ser maior, por isso não consigo centralizar.
Como proceder?
Answer: Entenda que se você não definir uma largura para o div e definir como float: left;, ele ficará do tamanho do seu conteudo, logo não tem como centralizar se não há espaço sobrando para isso...
Outro problema é que ao definir o float: left; este tem uma certa prioridade ao text-align: center;, um não se da muito bem com o outro...
coloque a palavra chave dentro do div, em um span (que é in-line por natureza) para definir a classe, e retire os floats.
CSS
 .contatoTopo{
      background-image: url('../imagens/contatoBG.jpg');
      background-repeat: repeat;
      height: 176px;
      line-height: 176px;
      margin: auto;
      width: 100%;
  }
.buscaConteudoCent {
  width: 960px;
  height: 100px;
  margin: auto;
  position: absolute;
  left: 50%;
  margin-left: -480px;
}
.buscaFontEncontraTit {
  font-family: 'ubuntulight_italic';
  font-size: 30px;
  color: white;
  text-align: center;
  margin: auto;
}
.buscaFontEncontra {
  color: #FFFFFF;
  font-family: 'ubuntubold_italic';
  font-size: 30px;
}

HTML

Nenhum resultado encontrado para: "teste"

Centralizar duas divs com texto


R-squared and F-stat in dummy variables regression vs panel FE model

Question: When estimating a Fixed Effects model on panel data and an equivalent dummy variables regression, the coefficient estimates and associated SEs are identical. However, the R-squared and F-statistic are noticeably different (e.g. R-sq from dummy regression is usually much higher than R-sq from FE specification).
Once we obtain the R-squared & F-stat from the dummy variables regression, how can one adjust them to retrieve the same results as from the FE specification?
Consider this example:
library(foreign);library(plm);library(stargazer)
wagepan<-read.dta("http://fmwww.bc.edu/ec-p/data/wooldridge/wagepan.dta")

# Generate pdata.frame:
wagepan.p <- pdata.frame(wagepan, index=c("nr","year") )

# Estimate FE parameter in 3 different ways:
wagepan.p$yr<-factor(wagepan.p$year)

# Estimate dummy vars and FE models
reg.fe <-(plm(lwage~married+union+yr*educ,data=wagepan.p, model="within"))
reg.dum<-( lm(lwage~married+union+yr*educ+factor(nr), data=wagepan.p))

stargazer(reg.fe,reg.dum,type="text",model.names=FALSE,
      keep=c("married","union"),omit.stat=c("ser"),
      column.labels=c("Within","Dummies"))

Which will yield:
=================================================================
                             Dependent variable:
             ----------------------------------------------------
                                    lwage
                      Within                    Dummies
                        (1)                       (2)
-----------------------------------------------------------------
married              0.055***                   0.055***
                      (0.018)                   (0.018)

union                0.083***                   0.083***
                      (0.019)                   (0.019)

-----------------------------------------------------------------
Observations           4,360                     4,360
R2                     0.171                     0.616
Adjusted R2            0.049                     0.560
F Statistic  48.907*** (df = 16; 3799) 10.900*** (df = 560; 3799)
=================================================================
Note:                                 *p<0.1; **p<0.05; ***p<0.01

How can I adjust the Model 2 R2 and F-stat (0.616 and 10.9, respectively) to retrieve the same figures as in Model 1 (0.171 and 48.9)?
Answer: To get the same results for the F-Test and the R^2 with the lm() function you have to run the regression on the demeaned variables and adjust the available degrees of freedom. I have not looked up what plm() is doing in detail so results are not exact equal but pretty close (I do not know for example what is plm doing with 'educ' which is time-invariant and for which demeaning does not make sense). It does not matter really wether 'year' is demeaned or not since it is a balance panel here.
# Deman all variables (except 'educ' which is time-invariant)
wagepan$lwage_de<-wagepan$lwage-ave(wagepan$lwage,factor(wagepan$nr),FUN=mean)
wagepan$married_de<-wagepan$married-ave(wagepan$married,factor(wagepan$nr),FUN=mean)
wagepan$union_de<-wagepan$union-ave(wagepan$union,factor(wagepan$nr),FUN=mean)
wagepan$year_de<-factor(wagepan$year-ave(wagepan$year,factor(wagepan$nr),FUN=mean))
wagepan$educ_de<-wagepan$educ-ave(wagepan$educ,factor(wagepan$nr),FUN=mean)

# Define dummy variables for the years or 'yr80:educ' is also included
wagepan$yr81<-as.numeric(wagepan$year==1981)
wagepan$yr82<-as.numeric(wagepan$year==1982)
wagepan$yr83<-as.numeric(wagepan$year==1983)
wagepan$yr84<-as.numeric(wagepan$year==1984)
wagepan$yr85<-as.numeric(wagepan$year==1985)
wagepan$yr86<-as.numeric(wagepan$year==1986)
wagepan$yr87<-as.numeric(wagepan$year==1987)

# Run Regression
reg.fe2<-( lm(lwage_de~married_de+union_de+year_de+yr81:educ+yr82:educ+yr83:educ+yr84:educ+yr85:educ+yr86:educ+yr87:educ, data=wagepan))

# F-stat from the lm is wrong because it does not adjust degrees of freedom so calculate here
ss_res<-sum(reg.fe2$residuals^2)
 ss_reg<-sum((reg.fe2$fitted.values-mean(wagepan$lwage_de))^2)
 ss_tot<-sum((wagepan$lwage_de-mean(wagepan$lwage_de))^2)
 p<-reg.fe2$qr$rank-1

# We have to adjust the degrees of freedom available
n<-length(wagepan$lwage_de)-(reg.fe2$qr$rank+length(unique(wagepan$nr))-1)

# R Squared
round(1 - (ss_res/ss_tot),2)

# F-Test
round((ss_reg/p)/(ss_res/n),2)

Here are the results:
> # R Squared
> round(1 - (ss_res/ss_tot),2)
[1] 0.17

> # F-Test
> round((ss_reg/p)/(ss_res/n),2)
[1] 48.59

For a nicer approach using matrix notation see for example
http://www.econ.uiuc.edu/~econ508/R/e-ta10_R.html
or
http://faculty.washington.edu/ezivot/econ582/fixedEffects.pdf
Comment: I'm curious though if it is possible to adjust `lm` estimates *without* having to re-estimate the model on demeaned data. I am running a number of regressions in a loop, and re-estimating each model would prove time-consuming. Which is why I want to see if there is a way to somehow *adjust* 0.616 and 10.9 to retrieve the expected estimates...
Comment: Of course, you can change the 'lm' function to account for this fact, but in this case it would probably make sense to also [adjust standard error](http://stats.stackexchange.com/questions/10017/standard-error-clustering-in-r-either-manually-or-in-plm) (to account for the clustering due to the panel structure of the data). Winthin estimation and Dummy variable approaches give the same results, so in the end why not use the plm function? You can even [estimate coefficients](http://www.stata.com/support/faqs/statistics/intercept-in-fixed-effects-model/) for dummies using the within approach!
Comment: I have issues with `plm` because it handles poorly cases of linear dependence in the model frame (see [detect_lin_dep](https://r-forge.r-project.org/scm/viewvc.php/pkg/man/detect_lin_dep.Rd?view=markup&revision=195&root=plm)) which can generate errors in `summary` and/or `vcovHC` methods. Since the coefficient estimates are the same, I've switched to `lm`. For `vcovHC.plm`-like SEs the exact same Arellano estimator is implemented in `multiwayvcov` (e.g. `cluster.vcov(mod.lm, ~ var1, df_correction=F)`). Plus `lm` objs are more widely supported than `plm` in packages like `car` or `lsmeans`..


Finding Initial Parameter Values for Gompertz Model with Intercept

Question: I have the following data:
<code>y x
1275 230
1350 235
1650 250
2000 277
3750 522
4222 545
5018 625
6125 713
6200 735
8150 820
9975 992
12200 1322
12750 1900
13014 2022
13275 2155
</code>
I would like to find reasonable initial values for the model
$$y=\alpha+\beta_1\text{exp}(-\beta_2 e^{-\beta_3 x})+\epsilon$$
What I know:
For the Gompertz model, the inflection point satisfies
$$x=\frac{\text{log}(\beta_2)}{\beta_3}$$
For the Gompertz model we have
$$\lim_{x\rightarrow\infty} \beta_1\text{exp}(-\beta_2 e^{-\beta_3 x})=\beta_1$$
so presumably with an intercept we have
$$\lim_{x\rightarrow\infty} \alpha+\beta_1\text{exp}(-\beta_2 e^{-\beta_3 x})=\alpha+\beta_1$$
so we can set $\alpha+\beta_1=13275$, the maximum value of $y$ in the dataset.
However, I can't seem to combine what I know to find initial values.
I would like to find reasonable initial values and not rely on specifying an exhaustive grid of values.
Any ideas or suggestions would be appreciated.
Update:
I read on wikipedia that the halfway point is found to be
$${\displaystyle x_{\text{hwp}}=-{\frac {\ln\left(\frac{ln(2)}{\beta_2}\right)}{\beta_3}}}$$
I let $x_{\text{hwp}}=713$, the median of the $x$'s.
As previously stated, I have $$x=\frac{\text{log}(\beta_2)}{\beta_3}$$
I let $x=1000$, since a plot of the data shows that a possible inflection point is around there.
By software, this system of equation results in $\beta_2=0.279$ and $\beta_3=-0.0013$.
I (randomly) decided to let $\alpha=13275$ and $\beta_1=-13275$, where $13275$ is the maximum value of $y$.
The model then converges after 15 iterations to
$$\hat{y}=12934.4-14349.2\cdot\text{exp}(-0.1214e^{0.00257x})$$
which are reasonably close to my initial estimates. I'm not sure why it would make sense to have $\hat{\alpha}=13275$ and $\hat{\beta_1}=-13275$ though.
Comment: Graphing the data, it appears that the pattern is logarithmic, rather than S-shaped. So, I don't think it's a problem if it doesn't fit the data well. I'm only looking to run this specific model though.
Comment: this certainly fits the data but thought that for a Gompertz curve $\beta_2$ and $\beta_3$ are $\gt 0$ I guess it depends on what you are trying to do.
Comment: Anyway there is a solution satisfying the usual positivity constraints. It is 1403.91  11799.4 9.83262  0.00340595 with a sum of squares of 854256. which is higher than the solution which violates the constraints. After doing all this work I would appreciate knowing whether the constraints should be satisfied or not.
Comment: My textbook doesn't show those constraints but I see online that you are correct. I would be interested in seeing your approach with those constraints in mind.
Comment: well you don't HAVE to impose the constraint, but  then you are using a completely different family of curves. the two families are separated by the singular solution where $\beta_3=0$. To solve your problem you use the fact that the model is linear in y(x(1)) and y(x(n)) and use those values as independent parameters instead of $\alpha$ and $\beta$.  I wrote all this up to discuss fitting a 4-5 parameter logistic but it seems to have disappeared
Comment: I found the post  if it is not clear I can say some more.   https://stats.stackexchange.com/questions/62995/how-to-choose-initial-values-for-nonlinear-least-squares-fit
Comment: I used the Differential Evolution genetic algorithm to determine initial parameter estimates and an equation search found several sigmoidal equations the fit the posted data well, but I could not find a good fit to the equation you posted. If it might be of use I can post the top few results of the equation search. If you can use Python I can post source code for a graphical fitter for these equations.
Comment: I think that the resulting values of $\hat{\alpha}$ and $\hat{\beta}$ don't look as expected is because many of us would initially expect that $\hat{\alpha}$ would be the value of the intercept.  But the intercept is $\alpha+\beta_1 \exp{(-\beta_2)}$.  The point is that you've found the correct maximum likelihood estimates.
Answer: A typical situation in nonlinear statistical modeling  is that the at least some of the parameters of interest to the modeler are not good parameters to use for parameterizing the model. I have found that is really difficult to convince a lot of people that they should
parameterize their model in terms of parameters in which they have no interest.  Well duh!  It often turns out to be a good idea, however, because these new parameters lead to an easier and more stable estimation scheme. Once these uninteresting parameters have been estimated the parameters of interest can be calculated from them.   This is how it goes.
step1:
rescale the problem so that $x(15)=1$ and $y(15)=1$  this is just standard good advice for any model when it is possible.
step2: replace the independent variables $\alpha$ and $\beta_1$ with new independent variables  $y_1$ and $y_n$. Note that these are parameters and not observations. They are the predicted observed $y$ values for $x(1)$ and $x(15)$. However we have very good initial estimates for them namely the observed values
$y(1)$ and $y(n)$ for the values $x(1)$ and $x(n)$.
 Now since you have rescaled the $y$'s a good initial value for $y_n$ is 1.0 for $y_1$ it is 0.096045.  You can use almost any reasonable starting values for $\beta_2$ and $\beta_3$, but they both should be $>0$, say $\beta_2=0.1$, $\beta_3=0.1$ It is not at all sensitive to these initial values. The initial values $\beta_2=10$, $\beta_3=10$ converge to the same solution.
step 3: Solve the linear system
\begin{align}
y_1&=\alpha+\beta_1\text{exp}(-\beta_2 e^{-\beta_3 x(1)}) \\
y_n&=\alpha+\beta_1\text{exp}(-\beta_2 e^{-\beta_3 }) \\
\end{align}
for $\alpha$ and $\beta_1$ in terms of $y_1,y_n,\beta_2,$ and $\beta_3$
This is just a little bit of matrix algebra.
In any system which supports matrix algebra. You form the matrix
$M$
$$
  M=    \begin{bmatrix}
          1&\exp(-\beta_2 e^{-\beta_3 x(1)})  \\
            1&\exp(-\beta_2 e^{-\beta_3})\ \ \\
       \end{bmatrix}
$$
Then
$$  \begin{bmatrix}
       \alpha  \\
       \beta_1  \\
    \end{bmatrix}   =  M^{-1}
      \begin{bmatrix}
       y_1  \\
       y_n  \\
    \end{bmatrix}
$$
Now the minimization is carried out in two phases. For the first phase
$\beta_2$ and $\beta_3$ are estimated for the fixed values of  $y_1$ and $y_n$. In the second phase all four parameters are estimated.
Hereis the fitted data plot.

The estimates for the original parameters are
1403.9062  11799.399 9.8326183  0.0034059501
Notice that at no time did one need to look at any aspect of the data. The only assumption involved is that a Gompertz curve should be used. Everything else is automatic.  This same procedure works for many kinds of growth curves.
I used AD Model Builder to fit the model, but it can easily be done in R
(so it must be simple).
Comment: @whuber  I wonder if I have posted solutions to enough  of these kinds of problems to convince you that the method is general?
Comment: Effectively you fix the parameters $\beta_2$ and $\beta_3$ turning it into a linear regression to make an initial guess of $\alpha$ and $\beta_1$ (where you choose to use the end points where the effect of $\beta_2$ and $\beta_3$ is smaller). The rescaling seems superfluous to me, and I wonder how much more useful this method is than just taking $\alpha =y(1)$ and $\beta_1 = y(15)-y(1)$.
Comment: Well don't just wonder about it.  If the data are really informative any parameterization will probably work. What you should do is to generate data with variable amounts of noise and fewer points near the tails so that there is less information about the asymptotes and compare the performance.
Comment: the question was rhetoric.
Comment: OK sorry we wasted my time.
Comment: On the other hand your question may be rhetoric (sic) but everything you said is also wrong. If I don't respond people might mistakenly think you have a point


Reading file in PERL using ActiveX

Question: I have been trying to read a file in PERL using ActiveX Control. I was successful in reading the file using ActiveX Controls in HTML. So I changed the HTML code to PERL cgi using "Print" Statement. After that I am not able to read the file the file using ActiveX, other JavaScript functions are working good.
print "";

Above line of code is used to invoke the external JavaScript.
print "<input type='button' name='btn1' value='Process' onClick='getData(document.getElementById('sampleFile').value)'>	";

Above line of code is an button in HTML, which onClick invokes the JavaScript method getdata()
var obj = new ActiveXObject('Scripting.FileSystemObject');

Above line of code is present in external JavaScript which creates an ActiveX Object to read the file.
    readFile = obj.OpenTextFile(path, 1, false);
                while(!readFile.AtEndOfStream)
                {
        readFile = obj.OpenTextFile(path, 1, false);
.................

Above line of code is the one which reads the file line be line.
The above code is working fine in HTML but in CGI after using print statement am not able to read the file. Please do suggest what should be changed in order to read the file.
Comment: Is the file available for the user that runs the webserver?
Comment: You are generating HTML using Perl/CGI. The browser still gets HTML. There is no difference at all from the browser's POV from loading a static HTML file from a server and loading one dynamically generated using Perl/CGI. Whatever the problem is, you've misdiagnosed the cause.
Comment: [There is no such thing as PERL](http://perldoc.perl.org/perlfaq1.html#What's-the-difference-between-%22perl%22-and-%22Perl%22%3f)
Comment: I believe not, I am trying to read the file from the client system. Would it be accessible using ActiveX Object?
Comment: You said it was before, so presumably - yes. (Unless you've changed other things about the page, such as putting it in a different security zone)
Answer: You have a simple HTML error.
onClick='getData(document.getElementById('sampleFile').value)'

Your attribute value is delimited by ' characters, but you try to use literal ' characters as raw data inside the attribute.
Consequently the value of the attribute becomes getData(document.getElementById( which isn't valid JavaScript.
This would have been picked up if you had used a validator.
If you want to use a ' as data in an attribute value delimited by ' then you have to represent it as '.
Comment: 'sampleFile' in the above case is the id

So in this case how should I pass the input to the javascript?
Comment: @Babu — Assuming you want to use the non-standard ActiveX approach you were taking before … you fix the syntax errors in your HTML as described in the last sentence of this answer.

Reading file in PERL using ActiveX


how to validate ipv4 ipv6 and dns name?

Question: In Java, there is InetAdress which can do the validation. The problem is that it requires accessing the network for the dns query. How can I do the validation? There are hostname and ipv4 regex, But I can't find a regex to match ipv6 address.
Comment: Look here:
https://stackoverflow.com/questions/9208814/validate-ipv4-ipv6-and-hostname and here
https://stackoverflow.com/questions/3114595/java-regex-for-accepting-a-valid-hostname-ipv4-or-ipv6-address
Comment: @Nurlan Nabiyev I'll checkout InetAdressValidator
Answer: The IPAddress Java library can parse host names, IPv4 and IPv6 addresses, without triggering DNS lookup. Disclaimer: I am the project manager of that library.
Sample code:
HostName host = new HostName(hostStr);
try {
    host.validate();
    if(host.isAddress()) {
        System.out.println("address: " + host.asAddress());
    } else {
        System.out.println("host name: " + host);
    }
} catch(HostNameException e) {
    System.out.println(e.getMessage());
}

This will not do DNS lookup.  More sample code at the wiki

how to validate ipv4 ipv6 and dns name?


Connecting to remote mysql server

Question: I use this to connect to my local mysql server:
<?
$host = "localhost";
$user = "root";
$pass = "";
$db1 = "mydb";
$db = mysql_connect($host,$user,$pass);
mysql_select_db($db1,$db);
?>

But, I want to connect to a remote mysql server instead.  I mean that site will be on the same server, but I'll connect to another mysql server.  How can I do this?
I'm on Ubuntu.
Answer: This is as simple as adjusting $host, $user and $pass appropriately.  Of course, firewalls between you and the remote server will have to allow the connection, and you'll need a valid username/password (which should not be "").
Comment: PHP Warning:  mysql_connect(): Lost connection to MySQL server at 'reading initial communication packet', system error: 113 in /home/dima/domjudge/domserver/www/my/test.php on line 7
PHP Warning:  mysql_select_db() expects parameter 2 to be resource, boolean given in /home/dima/domjudge/domserver/www/my/test.php on line 8
i already tried , but how can i get permissions to connect ?
Comment: Who runs the remote server?  Who controls the firewall where the webserver is?  These people will need to be involved.
Answer: On the remote MySQL server issue a GRANT statement like:
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON mydb.* TO remoteuser@'192.168.1.10' IDENTIFIED BY 'password';
Then change your $host to the remote MySQL server's IP address and $user to remoteuser and $pass to password (but hopefully not password). Also make sure that the remote MySQL server doesn't have bind-address=127.0.0.1 in the my.cnf and that there aren't any firewall rules blocking access.
In the above GRANT statement 192.168.1.10 is the IP address of the host that is running your PHP application.
Hope this helps.
Comment: Does it mean that i need to talk with hoster ?
Comment: I'd suggest using `bind-address=` rather than omitting the line.
Comment: @DimaSavva -- yes, we've been assuming you have control of the remote server. Someone needs to confiugre MySQL on that server to allow your app server to connect.

Connecting to remote mysql server