AWS EC2 - Instance works as T2, but not M4 or C4

Question: I'm having a very strange problem with server instance, which I'm trying to upgrade from PV to HVM.
I've got through the migration process, and created an AMI.
If I launch an instance from this AMI as a T2 type, of any size, it works fine.
However, if I try to launch as M4 or C4, it fails.
I'm seeing very odd errors in the system log...
Apr 24 08:49:19 cloud-init[1619]: util.py[WARNING]: Route info failed: Unexpected error while running command.
Command: ['netstat', '-rn']
Exit code: 1
Reason: -
Stdout: 'Kernel IP routing table\nDestination     Gateway         Genmask         Flags   MSS Window  irtt Iface\n'
Stderr: ''
ci-info: ++++++++++++++++Net device info+++++++++++++++++
ci-info:  Device   Up    Address      Mask    Hw-Address
ci-info:    lo    True  127.0.0.1  255.0.0.0      .
ci-info: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Route info failed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Apr 24 08:49:19 cloud-init[1619]: url_helper.py[WARNING]: Calling 'http://169.254.169.254/latest/meta-data/instance-id' failed [0/120s]: request error [HTTPConnectionPool(host='169.254.169.254', port=80): Max retries exceeded with url: /latest/meta-data/instance-id (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7ffa7da7e310>: Failed to establish a new connection: [Errno 101] Network is unreachable',))]

Can anyone suggest a reason why this would consistently fail with the M4 and C4 types, but consistently work with T2?
I've never encountered an issue like this previously, even though I've migrated many other instances using the same process.
Comment: That smells like a network driver issue; the kernel isn't setting up the network port, so the check against the AWS metadata service doesn't have anywhere to go. You might try running this against an m3 type, as that can have different network configs.
Comment: Thanks @sysadmin1138. I've confirmed it also works with the M3 type. Any idea what I might need to do to upgrade an Amazon Linux instance to work with the M4 and C4 types? One of the main reasons for the PV to HVM migration was to be able to use the newer/faster instance types.
Answer: The most likely reason that your instance would be failing to fetch metadata is that its kernel lacks drivers for the network interface.
Most newer EC2 instance types use the Elastic Network Adapter, with the driver name ena. This driver is present in a vanilla kernel; the relevant configuration flags are:
PCI_MSI=y
NET_VENDOR_AMAZON=y
CONFIG_ENA_ETHERNET=y


Integral domain without unity has prime characteristic?

Question: By an integral domain, we mean here, a ring (not necessarily with unity) in which $ab=0$ implies $a=0$ or $b=0$.
Question: If an integral domain without unity has positive characteristic, is it necessarily prime?

An integral domain $D$ is said to be of finite characteristic if there exists a positive integer $m$ such that $ma=0$ for all $a\in D$. [cf. Topics in Algebra- I. N. Herstein, 2nd Ed., p. 129]
My question is a slight modification of Problem 6 in [Topics in Algebra- I. N. Herstein, 2nd Ed., p. 130]
Topics in Algebra- Herstein, 2nd Ed.
Comment: [Related, maybe duplicate](http://math.stackexchange.com/questions/111425/characteristic-of-a-non-unital-integral-ring)
Comment: I think to be safe you should add a definition of characteristic of a non-unital ring. The one used in the link suspiciously does not coincide with the characteristic of a unital ring.
Comment: @Daniel: My definition of characteristic is according to Herstein, which do not match with that in the Duplicate's Link.
Comment: In part, because the definition of characteristic used there is unusual, I said "maybe duplicate" and not "duplicate". The argument of the answers there also applies with the more common definition, however. But $D = \{0\}$ is a special case, its characteristic is not prime (it's $1$).
Answer: I will assume the characteristic of a non-unital ring is simply the exponent of the additive group, i.e. the smallest $n$ such that $na=0$ for every $a \in A$.
Then the argument that the characteristic is prime for integral domains follows the usual way:
So assume that $n=kl,  \;\;\; 0<k , l <n$ is a composite number. Choose $a \in A$ such that $ra \neq 0$ for every $r = 1, 2, \dots, n-1$ (if there is no such element, the characteristic is ncessarily smaller than $n$). Thus, $ka \neq 0, \; la \neq 0$ but $(ka) \cdot (la)=kl a^2=na^2=0,$ contradicting the fact that $A$ was an integral domain. Thus, if the characteristic is positive, it is necessarily prime.
Comment: Thanks for the nice argument.


Wildcards in dynamically generated menu

Question: I'm working on a custom module, and I'm building menu items using entries in a database. These are being cached, and the database is only really updated about once a month.
I'm having an issue getting wildcards to work with this menu.
Here's my menu structure that WORKS:
$dbconn = dbConnect();
$query = "SELECT TOP 3 id, title FROM table";
$q = mssql_query($query, $dbconn);
while($r = mssql_fetch_assoc($q)) {
    $title = $r['title'];
    $items[$title] = array(
        'title' => $r['title'],
        'description' => 'Page for ' . $r['title'],
        'page callback' => 'programs_page',
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );
}
mssql_close($dbconn);

But the moment I add the % into the array key, the menu items just disappear, like so:
$items[$title . "/%"];

Any suggestions on why drupal is tripping up on this? Even if I tack the ."/%" onto the $title variable, it doesn't work.
Comment: May you provide the full code of the function?
Answer: There is no need to add wilcard placeholders after your last path element. Anything tacked onto the end of the URL will be passed to the callback as arguments automatically.
If the example you give above, if someone goes to $title/arbitrary/arguments, then 'arbitrary' and 'arguments' will be passed as arguments to your page callback:
programs_page('arbitrary', 'arguments');
If you want arguments in the middle of your path, you can specify them with a % sign, or if you would like to automatically load and pass an object to your page callback, you can use wildcard loaders.
Comment: @oraanges13, yes that's right. They will be passed regardless, so you can use func_get_args() to check for arguments too. That's how functions like `db_query` work.
Comment: The User module uses a path like `user/reset/%/%/%`; using a wildcard at the end of a path is not forbidden.
Comment: Alright, so when I declare the programs_page function, I just have to do: `function programs_page($arg1, $arg2, $arg3, ...)` so I can reference them inside my function, correct?

Wildcards in dynamically generated menu


What's the difference between bronze-wound and silver-wound bass strings?

Question: The most common materials to wound bass strings are bronze and silver. Most string makers offer options with either. Seems that bronze strings last shorter or can go bad easier, so there must be a tone difference among them to justify the less modern bronze-wound strings?
What's the difference in tone? Is one brighter than the other? Why would one choose bronze-wound strings over silver-wound strings?
Answer: Most listeners can't tell the difference between bronze-wound strings and silver-wound.
It is often said that the silver-wound strings (actually silver-plated copper) sound warmer, and that the bronze-wound strings are punchier.
I say 'silver-plated copper wound' because pure silver winding would be prohibitively expensive.
It all comes down to that which feels right in your hands and which sounds good to you.
I have become a fan of flat-wound bass strings.
Much smoother surface they have, and boy oh boy do they feel good under your fingers.
The ones I am drawn to are the Rotosound 77's.
They are made of a stainless steel core and a Monel 400 top tape. (Monel is around 65% pure nickel.)


$\sigma$-algebra of $\mathbb{R}$ generated by $\mathcal{P}(\mathbb{N})$

Question: What is the $\sigma$-algebra of $\mathbb{R}$ generated by $\mathcal{P}(\mathbb{N})$?
I thought it is $$\Sigma = \{\emptyset, \mathbb{N}, \mathcal{P}(\mathbb{N}), \mathbb{R}, \mathbb{R}-\mathbb{N}, \mathbb{R}-\mathcal{P}(\mathbb{N}),(\mathbb{R}-\mathcal{P}(\mathbb{N})) \cup \mathbb{N}, (\mathbb{R}-\mathbb{N}) \cup (\mathbb{R}-\mathcal{P}(\mathbb{N})) \}$$
Is that correct?
Comment: Things like $\mathbb{R} \setminus \mathcal{P}(\mathbb{N})$ don't really make sense.  One of these is a set of numbers, and the other is a set of sets of numbers.
Comment: Since the members of $\mathcal P(\mathbb N)$ are never real numbers, what does $\mathbb R-\mathcal P(\mathbb N)$ mean?
Comment: You're right. Let me re-think it.
Comment: I think $\mathcal{P}(\mathbb{N})$ itself is a $\sigma$-algebra, am I correct?
Comment: No, because $\Bbb R \not\in \wp(\Bbb N)$.
Comment: It's not a sigma-algebra with respect to the real numbers, as it's not closed under complementing.
Answer: So the sigma algebra generated by $\mathcal{P}(\mathbb{N})$ is the smallest $\sigma$-algebra containing $\mathcal{P}(\mathbb{N})$.  So what's going to have to be in it?  Well, we'll need $\mathbb{R}$ and $\emptyset$, and we'll certainly need all of $\mathcal{P}(\mathbb{N})$.  Notice that $\mathcal{P}(\mathbb{N})$ is already closed under countable unions, so we won't need to worry so much about that.  But it's not closed under complements.  So we'll need to include every set of the form $\mathbb{R} \setminus A$ for $A \subset \mathbb{N}$.
Anything else?  Well, we just included new sets, so we need to check if the new sets is compatible with our old ones, or if we're going to need to add more. We can of course take complements of sets of the form $\mathbb{R} \setminus A$ and just get $A$, which is in $\mathcal{P}(\mathbb{N})$ so we're fine there.  If we take unions, $\bigcup_{\alpha} (\mathbb{R} \setminus A_{\alpha}) = \mathbb{R} \setminus (\bigcup_{\alpha} A_{\alpha})$, so we're also fine there.
So I believe the answer to your question ought to be $\sigma(\mathcal{P}(\mathbb{N})) = \{ \mathbb{R}, \emptyset \} \cup \mathcal{P}(\mathbb{N}) \cup \{\mathbb{R} \setminus A: A \subset \mathbb{N} \}$
Comment: Oh, I get it now. In another case, if I have to look for the $\sigma$-algebra generated by $\mathcal{P}(\mathbb{Q})$, we'll need $\mathbb{R}$ and $\emptyset$, and $\mathcal{P}(\mathbb{Q})$. $\mathcal{P}(\mathbb{Q})$ is also closed under countable union. But it's not closed under complements too.
Then, it's similar to the first case:
$\sigma(\mathcal{P}(\mathbb{Q})) = \{ \mathbb{R}, \emptyset \} \cup \mathcal{P}(\mathbb{Q}) \cup \{\mathbb{R} \setminus A: A \subset \mathbb{Q} \}$, right?
Answer: This indeed can be more general. Let $X$ be any nonempty set and $Y\subset X$ be any nonempty subset. Let $\sigma_Y(Y)$ be any $\sigma$-algebra on $Y$.
Then $$\sigma_X(\sigma_Y(Y))=\sigma_Y(Y)\bigcup\{A^c|A\in\sigma_Y(Y)\}.$$ Because any $\sigma$-algebra that contains $\mathcal{P}(Y)$ must contain the right hand side, it is enough to show the right hand side is a $\sigma$-algebra.
For any sequence $\{B_n\}$ from the right hand side, let $I_1=\{n|B_n \in\sigma_Y(Y)\}$ and $I_2=\{n|B_n^c\in\sigma_Y(Y)\}$. Then
$$\bigcup_n B_n=\bigcup_{n\in I_1} B_n\cup \bigcup_{n\in I_2} B_n=C\cup D^c=(D\backslash C)^c$$ where $C=\bigcup_{n\in I_1} B_n$ and $D=\bigcap_{n\in I_2} B_n^c$. The claim follows by observing that $C,D, D\backslash C\in\sigma_Y(Y)$.
In your example, $X=\mathbb{R}$, $Y=\mathbb{N}$ and $\sigma_Y(Y)=\mathcal{P}(\mathbb{N})$.


Is is possible to use other files as a map instead of the Google Apis Map?

Question: Instead of using the Google Apis Map from the MapView android tutorial, can I use other files such as a photo or a picture to substitute as a map?
Answer: Yes you can.
http://code.google.com/apis/maps/documentation/javascript/maptypes.html#CustomMapTypes


Integral of a product of a ${L^1}_{loc}$ function and a compact support function

Question: I'd like to prove that, if $f\in {L^1}_{loc}(\mathbb{R}^n)$ and $g$ is a bounded, measurable function with compact support and if $\int_{\mathbb{R}^n} fgdx = 0$ $\forall g$, then $f$ is almost everywhere equal to $0$.
Surely $fg\in L^1(\mathbb{R}^n)$: by hypothesis, $|g|\leq c\in\mathbb{R}$, so we have
$||fg||_1=\int_{\mathbb{R}^n} |fg| dx\leq c\int_{K}|f|dx\leq +\infty$, where $K$ is the support of the function $g$. So I applied Lebesgue differentiation theorem to $fg$, in order to have
$lim_{r\to 0^{+}} \frac{1}{|B(x,r)|} \int_{B(x,r)} f(y)g(y)dy = f(x)g(x)$ almost everywhere, but now I don't know how to use the hypothesis about the integral of this product over $\mathbb{R}^{n}$. How can I proceed?
Answer: Let $g$ be bounded, measurable and have compact support. Define $A := f^{-1} ([0,\infty)) \in \mathcal B (\Bbb R^n)$. Then $g\cdot 1_{A}$ is a measurable, bounded function with compact support. Hence
$$0=\int_{\Bbb R^n} f g 1_{A} = \int_{\Bbb R^n} f ^+ g ,$$
where $f^+$ is the positive part of $f$. Thus, without loss of generality we can assume that $f\geq 0$. Now let $g = 1_{B(0,r)}$ with $r>0$. The function $g$ is bounded, measurable and has compact support. Therefore,
$$\int_{B(0,r)} f =0.$$
Since $f\geq 0$, this yields $f = 0$ almost everywhere on $B(0,r)$. This means there exists a null set $N_r \subseteq B(0,r)$ with
$$f(x) = 0 \quad \forall x\in B(0,r) \setminus N_r .$$
This provides
$$f(x) = 0 \quad \forall x \in \bigcup\limits_{m=1}^\infty ( B(0,m) \setminus N_m) \supseteq \Bbb R^n \setminus \bigcup_{m=1}^\infty N_m. $$
Since $\lambda (\bigcup_{m=1}^\infty N_m) \leq \sum_{m=1}^\infty \lambda (N_m) = 0$ we have that $f=0$ almost everywhere.
Comment: Great, you didn't even use Lebesgue theorem! Thanks!
Answer: Since $g = 1_{B(x,r)}$ is measurable and bounded with compact support you could also proceed with your idea as follows:
$$\int_{B(x,r)} f =  \int_{\Bbb R^n} fg = 0$$
Thus for almost every $x\in\Bbb R^n$ $$0 = \lim_{r\searrow 0} \frac{1}{\vert B(x,r)\vert} \int_{B(x,r)} f  = f(x)$$
Comment: It was pretty easy indeed... thank you so much!


stereographic projections find the function

Question:
The problem is in the image.  I need help.  I have no idea how to do this.
Answer: Since the triangle depicted is isosceles, the angle of the triangle at the North Pole is $\frac{1}{2}(\pi - \varphi)$. Then, the triangle with corners at the North Pole and along the line at the points indicated by $0$ and $x$ has a right angle at $0$, and the shorter legs opposite and adjacent to the North Pole have length $x$ and $2R$ respectively, so using the definition of $\tan$ gives:
$$x = 2R \tan\left[\tfrac{1}{2}(\pi - \varphi)\right],$$
which we might also like to write as
$$x = 2R \cot\left(\tfrac{1}{2}\varphi\right).$$
There's a half-angle identity for cotangent, but I don't think it makes the formula any nicer or more usable.
Answer: If the Cartesian co-ordinate of the point P is (y,z),then under stereographic projection  x will be z/(1-y).


JSON Array para objeto swift 3

Question: Tem como alguém me ajudar e me orientar, estou estudando desenvolvimento iOS ai coloquei uma biblioteca "Alamofire" com o cocoapods pra consumir JSON
até ai tudo certo, só que meu JSON retorna assim:
{
  "results":[
     {
        "id":7,
        "descricao":"Acupuntura",
        "campoOrderBy":"descricao"
     }
]
}

Tem alguma biblioteca que consigo colocar esses caras em entidades, atributos, variável de forma simples, tem algum artigo, site que possa ver isso ?
Alguma dica por onde começar a estudar ?
Answer: Você pode usar o OCMapper:
Exemplo de JSON:
{
   "firstName"   : "FirstName",
   "lastName"    : "LastName",
   "age"         : 26,
   "dateOfBirth" : "01/01/2013",
   "address"     : {
                        "city" : "San Diego",
                        "country" : "US"
                   },
   "posts"       : [
                         {
                             "title" : "Post 1 title",
                             "datePosted : "04/15/2013",
                         },
                         {
                             "title" : "Post 2 title",
                             "datePosted : "04/12/2013",
                         }
                   ]
}

Um objeto com os dados do JSON:
@objc public class User: NSObject {

    var firstName: String?
    var lastName: String?
    var age: NSNumber?
    var dateOfBirth: NSDate?
    var address: Address?
    var posts: [Post]? // Repare que como é um array no JSON, será necessário criar outro Objeto chamado Post para receber os dados de dentro do array
}

Utilização Swift:
let user = ObjectMapper.sharedInstance().objectFromSource(dict, toInstanceOfClass:User.self) as User

Utilização Objective-C:
User *user = [[ObjectMapper sharedInstance] objectFromSource:dictionary toInstanceOfClass:User.class];

É possível inclusive fazer a integração no Alamofire para que ele já seja o parser da requisição, tem um exemplo no link acima.
Answer: Olá, você pode usar o protocolo Codable do swift. Atualmente o swift, na versão 5, possui o Encodable e o Decodable. O Encodable serve para codificar um objeto para json e o Decodable faz o trabalho reverso. Ao extender Codable você está dizendo que a estrutura ou classe pode tanto ser codificada quanto decodificada.
Na maioria dos casos fazemos ambos os processos, mas é possível que exista um caso no qual queremos apenas codificar ou apenas decodificar. Nesses casos é possível extender apenas Encodable ou apenas Decodable.
Para o seu caso basta criar as estruturas extendendo de Codable da seguinte forma:
struct ObjetoInterno: Codable {
  var id: String
  var descricao: String
  var campoOrderBy: String
}

struct ResultadoDaChamada: Codable {
  var results: [ObjetoInterno]
}

E para converter o json para a estrutura ResultadoDaChamada, usar da seguinte forma após obter o resultado da sua chamada:
let stringJson = """
{
    "results":
        [
            {
            "id":7,
            "descricao": "Acupuntura",
            "campoOrderBy":"descricao"
            }
        ]
}
"""

if let dadosJson = stringJson.data(using: .utf8){
    do {
        let resultado = try JSONDecoder().decode(ResultadoDaChamada.self, from: dadosJson)
        print(resultado)
    } catch let error {
        print(error)
    }
}

Uma boa fonte de informação sobre isso é a documentação da Apple: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

JSON Array para objeto swift 3


C++ Subclass Constructor

Question: I am having trouble understanding how to construct a subclass. My parent class is called "package" and the children are called "overnight" and "twoDay". The package class handles the recipient's name and address as well as the packages weight and the shipping cost per oz. twoDay also adds an additional shipping fee and overnight adds more to the shipping cost per oz.
The package class files run fine but I can't figure out how to use it in the children constructors. Below I will show the files for package and overnight and the header area of the main program file.
program.cpp
#include <iostream>
#include <string>
#include "package.h"
#include "twoDay.h"
#include "overnight.h"

int main() {

}

package.h
#include <string>
#include "name.h"
#include "address.h"

class package {
 public:
  package();
  package(std::string initFirst, std::string initLast, std::string initLineOne,
          std::string initLineTwo, std::string initCity, std::string initState,
          std::string initZip, double initWeight, double initPrice);
  double getWeight() const;
  double getPrice() const;
  double getCost() const;
 private:
  name recipientName;
  address recipientAddress;
  double weight;
  double price;
};

package.cpp
#include "package.h"

package::package(){
  recipientName = name();
  recipientAddress = address();
  weight = 0.0;
  price = 0.0;
}

package::package(std::string initFirst, std::string initLast, std::string initLineOne,
                 std::string initLineTwo, std::string initCity, std::string initState,
                 std::string initZip, double initWeight, double initPrice)
  : recipientName(initFirst,initLast), recipientAddress(initLineOne,initLineTwo,initCity,initState,initZip) {
  weight = initWeight;
  price = initPrice;
}

overnight.h
#include <string>

class overnight : public package {
 public:
  overnight();
  overnight(std::string initFirst, std::string initLast, std::string initLineOne,
            std::string initLineTwo, std::string initCity, std::string initState,
            std::string initZip, double initWeight, double initPrice, double initOunceFee);
  double getOvernightCost() const;
 private:
  package packageInfo;
  double ounceFee;
};

overnight.cpp
#include "overnight.h"

overnight::overnight() {
  packageInfo = package();
  ounceFee = 0.0;
}

overnight::overnight(std::string initFirst, std::string initLast, std::string initLineOne,
                     std::string initLineTwo, std::string initCity, std::string initState,
                     std::string initZip, double initWeight, double initPrice, double initOunceFee)
  : packageInfo(initFirst,initLast,initLineOne,initLineTwo,initCity,initState,initZip,initWeight,initPrice){
  ounceFee = initOunceFee;
}

So the part I'm having trouble with is the second constructor of overnight.cpp with the parameters.
Answer: The class overnight is a package, you don't need composition and embed a package object in the class.
As for the constructor, do e.g.
overnight::overnight(std::string initFirst, std::string initLast, std::string initLineOne,
    std::string initLineTwo, std::string initCity, std::string initState,
    std::string initZip, double initWeight, double initPrice, double initOunceFee)
: package(initFirst,initLast,initLineOne,initLineTwo,initCity,initState,initZip,initWeight,initPrice){
//^^^^^^^ Note the use of the base class here
    ounceFee = initOunceFee;
}

Comment: That is how I thought it worked but it gave me the following errors: http://imgur.com/L43qOWQ
Comment: @JohnLongsocks Where do you include the `"package.h"` header file?
Comment: @JoichimPilebord it is included in the "package.cpp" and the "program.cpp" file. Since it is include first in the "program.cpp" file doesn't that mean that the files after it will also have access to it?
Comment: @JohnLongsocks don't do that. Make sure your base class headers are included in your *derived* class headers. Don't build a compilation dependency on the ordering of an include-file list of a translation unit. If a header `derived.h` needs stuff from a different header `foo.h`, then `#include "foo.h"` inside the header guards of `derived.h`. This is true for *all* header dependencies. Your "overnight.h" should include "package.h", and  (as it uses `std::string` as well). And you should have proper include-guards.
Comment: @JohnLongsocks glad to help. It may seem a little odd at first, but you ideally also include user-defined headers *before* standard library headers. It may look a little odd at first, but the reason is sound: it prevents you from accidentally building an ordering dependency just as i described above. For example, `"package.h"` includes ``, then `"name.h"`, and `"address.h"` If `name.h` accidentally forgot to include `` and it uses `std::string` someone that include *just* `name.h` would fail to compile, but including `package.h` and they would succeed.....
Comment: @JohnLongsocks you can avoid that problem by always including user-headers *first*. That ensures any additional dependencies are fulfilled *prior* to pulling in additional library headers, thereby making your user-defined headers more stand-alone and self-dependency fulfilling. Hope that makes sense. Best of luck.
Comment: @WhozCraig What about when I have two derived classes? If I try adding "parent.h" to both "child1.h" and "child2.h" it gives me the error "redefinition of class name" and if I only include it in one it gives these errors (http://imgur.com/L43qOWQ)
Comment: @JohnLongsocks that would be the reason for *include guards*. Hunt around a bit and you'll find info about them.

C++ Subclass Constructor


how to test heteroskedasticity of a time series in R?

Question: How can I test heteroskedasticity of a time series in R? I have heard of two tests McLeod.Li.test and bptest (Breusch-Pagan test). Can I use these two tests? and what are the differences and assumptions of these tests if I can use them?
Thanks
Answer: Breusch-Pagan test is for hetroscedasticity in regression model. It is testing the relationship between squared residuals and the covariates. You get more information in wiki
McLeod.Li.test is a test for the presence of conditional heteroscedascity. This test is used to identify the presence of ARCH/GARCH modeling. It is very similar to Ljung-Box test on squared residuals.
For time series modeling Mcleoid Li test is more appropriate heteroscedascity test  than bptest.
As a suggestion, visual inspection is very important and this should be your first step before any test. Generate the residual graph and see the presence of heteroscedascity visually.


Probability of investment loss/gain problem

Question: I'm trying to determine the total expected gain or loss over a one year period given an investment that has the following probabilities (over the same one year period):
$P($2000 loss) = .25
$P($1000 profit) = .2
$P($5000 profit) = .15
$P($0 profit) = .4
My approach is as follows:
$P($loss) = .25(-2000) = - 500
$P($gain) = .2(1000)+.15(5000)+.4(0) = 950
Expected gain/loss = gain - loss
Expected gain/loss = 950 - 500 = $450
I feel like i'm missing something critical here, mostly pertaining to the 40% probability of breaking even.
Comment: What is the result of $0.2(1000)+.15(5000)+.4(0)$ ? Please calculate it again.
Comment: $-2000\cdot0.25+1000\cdot0.2+5000\cdot0.15+0\cdot0.4=450$
Answer: The best way to formulate this :
Let $X$ be a random variable with
$P(X = -2000) = 0.25$
$P(X=1000) = 0.2$
$P(X = 5000) = 0.15$
$P(X = 0) = 0.4$
Then, $E(X)=(-2000)\times 0.25+1000\times0.2 +5000\times 0.15+0\times 0.4=450$
Comment: Thanks Peter, this is a much more clear and concise way to look at the problem.


jQuery Keyup function works in Chrome and firefox, but not IE

Question: First off, apologies for the poor title, but I honestly don't know enough about jQuery to be specific about what isn't working and other similarly-titled questions don't provide a working solution. HTML code is below. My addition ,subtraction working in Chrome and Firefox. But not in Internet Explorer.

        Receiving Quarantine

        <input type="textbox" name="rcv_quantity" class="tqty" id="totalAmt"  value="<?php echo $row->rcv_quantity; ?>" style="background-color: #f0f0f0;" readonly />

        Lot Released

        <input type="text" name="lot_rel" id="lr1" class="lr" onblur="checkTextField(this);" />

        Total Lot Released

        <input type="text" name="total_lot_rel" id="tlrr" class="tlr" value="<?php echo $row->total_lot_rel; ?>" style="background-color: #f0f0f0;" readonly />

        <input type="hidden" name="sih" id="sih" class="sih" value="<?php echo $row->in_hand_nt_rel; ?>"  />

        Rejected

        <input type="textbox" name="rejected" id="re" class="lrr"  value="<?php echo $row->rejected; ?> " />

I use this jQuery for calculation. And write this jQuery at the bottom of my HTML page.

Comment: It's **well worth** your time to read through [the jQuery API](http://api.jquery.com) from beginning to end. It only takes an hour or two, and it pays you that time back immediately.
Answer: If you're using jQuery, you should consider using it.
The problem is that what you've passed into getElementsByClassName isn't a class name, it's a class selector. You don't want that . there if you use that function. e.g.:
var cells = document.getElementsByClassName('lr');
// No . here --------------------------------^

That makes it work if we fix various typos:

$(document).ready(function() {

  var cells = document.getElementsByClassName('lr');
  for (var i = 0; i < cells.length; i++) {
    if ($(cells[i]).val() > 0)
      cells[i].disabled = true;
  }
});

      Lot Released-1

        <input type="text" name="lot_rel1" id="lr1" class="lr" value="400" />

      Lot Released-2

        <input type="text" name="lot_rel2" id="lr2" class="lr" value="" />

      Lot Released-3

        <input type="text" name="lot_rel3" id="lr3" class="lr" value="" />

But again, if you're using jQuery, let's use jQuery:
$(document).ready(function() {
  $(".lr").each(function() {
    if (this.value > 0) {   // <=== Note! There's an implied type coercion here
      this.disabled = true
    }
  });
});

$(document).ready(function() {
  $(".lr").each(function() {
    if (this.value > 0) {   // <=== Note! There's an implied type coercion here
      this.disabled = true
    }
  });
});

      Lot Released-1

        <input type="text" name="lot_rel1" id="lr1" class="lr" value="400" />

      Lot Released-2

        <input type="text" name="lot_rel2" id="lr2" class="lr" value="" />

      Lot Released-3

        <input type="text" name="lot_rel3" id="lr3" class="lr" value="" />

Additionally, it's type="text", not type="textbox". I've also made that change above.
Comment: You are right . I used these three textbox value in addition and subtraction . When one textbox is disabled it  involved further  addition and subtraction. But I don't want these I want when textbox is disabled it  won't interrupt any addition and subtraction. Please help me.
Comment: @MasudSarker: I answered the question you asked. I have no idea what question you're asking with that comment. Good luck.
Comment: Here is any keyword which disable textbox as this textbox value can't perform any jquery  addition and subtraction. Thanks for good communication.
Answer: $(document).ready(function () {
    $(.lr).each(function(){
       if($(this).val() > 0)
           this.disabled = true;
    });
)};

Consider using this, because it seems like you are using jQuery, since you added $ in that if-statement.
Also, document.getElementByClassName('.lr') is not correct because of the . you added to it, since you already are looking for class names, you don't need to add ., or else you actually writing a selector and not a classname.
Comment: It works nice. Can you help me about this. Disabling a textbox if it has value and ignored this disabled value in addition and subtraction in jquery. There is any keyword like disable which will disable textbox also won't perform any jquery addition and subtraction?
Answer: I think you're looking for prop. Try typing this into your developer console.
$("#lr1").prop("disabled", true);

You'll see that this properly disables it. So here would be your proper jQuery, including type checking and all of that goodness.
$(document).ready(function () {
    $('.lr').each(function(){
        if (isNaN(parseFloat($(this).val()))) {
            return;
        }
        if (parseFloat($(this).val()) > 0) {
            $(this).prop("disabled", true);
        }
    });
});

Comment: I was still playing around with the code when I hit tab and space bar, accidentally posting the incomplete answer. Now it just looks derivative .__.
Comment: Hmm I got it. Can you help me about this. Disabling a textbox if it has value and ignored this disabled value in addition and subtraction in jquery. There is any keyword like disable which will disable textbox also value won't count any jquery addition and subtraction?
Comment: Uhm, what? I honestly do not understand what you are asking. If you want to use arithmetic on text inputs, set variables equal to `parseFloat($(selector).val())` and use `isNaN` to avoid NaN propagation. You can then set the new value with `$(selector).val(newvalue)`. If you want to exclude disabled inputs from selectors, you can use `$(".lr:not([disabled])")`.
Comment: Did that answer your second question?


Uncaught SyntaxError: Identifier 'total' has already been declared

Question: So I just got back with programming and I came across this, I don't understand why I keep getting this error "Uncaught SyntaxError: Identifier 'total' has already been declared". When I use a different variable name, the problem doesn't occur.
This is the code that emits the error:
let total = 0;
function sumArray(array) {
    for (let num in array) {
        total += array[num];
    }
    return total;
}

When I change the variable name, the error doesn't occur
let sum = 0;
function sumArray(array) {
    for (let num in array) {
        sum += array[num];
    }
    return sum;
}

and when I place the variable total inside the function, the error doesn't occur either.
function sumArray(array) {
    let total = 0;
    for (let num in array) {
        total += array[num];
    }
    return total;
}

Can someone explain this to me?
Comment: I don't get any error. The error may be for the lines above it. Did you define variable `total` twice in your code?
Comment: Share line # given in error  `Uncaught SyntaxError: Identifier 'total'` and code written `let total = 0;` ?
Comment: The questions is missing context such as the rest of the code and error as the error is likely to be somewhere else than in the shared code snippet.
Answer: alot of times when coding there could be invisible letters, i ran your code  on my end, see Below, i had no issues.this is only an identification that the variable total is already named in the file. unless you can provide us with more information of this error message,
In your terminal, does it tells you the where the variable "total"is named?
Can you perhaps do a quick find in your terminal by finding this hiding variable? if you are in a mac press "Command f" or windows:"ctrl f"
let total = 0;
function sumArray(array) {
    for (let num in array) {
        total += array[num];
    }
    return total;
}


How do I make this beat fit in the measures evenly, time signature-wise?

Question: In a program for tabbing (but I use with MIDI creation) called Tuxguitar, I've written out a drum beat on hihats, and I'm pretty sure the bpm is correct, and everything SOUNDS correct, but I can't get it to loop measures. To get it to sound like one continuous looping flow, I had to duplicate the measure, and then I found for every measure, it added a 64th note, so I had to pull it back a bit.
I don't think this is such a complex beat that it needs to be copy-pasted and adjusted for EVERY measure, but I do think maybe I've got the time signature wrong. You see, in my head, if you change the time signature to make the measure end where it should, then it'll loop easily. But nothing I've tried worked.
Here is how it should sound (well except that the engine sucks so it sounds nothing like a hihat on export to wav)
http://picosong.com/RZNt/
And here's a picture of what's going on.

Any ideas?
Again, it's looping perfectly, and it's the right BPM, but I need a way to fit it all into just one measure so it can loop, a time signature, maybe multiple?.
Answer: What seems to be causing the confusion here is a swing feel, used quite a lot in Jazz.  It has caused me confusion in the past too.
Put simply it's when you take the 2 even quavers in each beat, lengthen the first one and shorten the second to give a smoother feel. It has a very distinctive sound usually  (the wiki article can explain far better than I can)

It's an entire style by itself, with a ton of examples I'm sure you can find,  but my favourite has to be in a Leonard Cohen classic.
So as you might already have noticed, what you essentially have there is a compound time rhythm so the triplet feel could also be interpreted in 6/8.
So to answer your question there are 2 ways you can notate it depending on whether your intent is to have a 4/4 feel or a 6/8 feel (though duplet/triplet feel is a more technically accurate wording).
In 4/4 (with a swing feel) you would notate the pattern like this

And in 6/8 you would notate the pattern like this

I've uploaded the sound as it's notated in this way(here). If it's not what you meant let me know and I'll have a rethink :)
As for using it with Tuxguitar, I'm afraid I've never used it, but it should be able to handle both methods of notating.
edit: I also this nice video on swing rhythms, though it is on piano.
Comment: Unfortunately, this is what might be the actual idea but not what is given in the sound file..
Comment: Thanks @percusse, I'll upload a soundfile to SoundCloud and ask if that's what was intended.
Answer: It looks like your problem is coming in the notation of beat 3.  You have 16th rest, two 16th triplets and two 16th triplet rests.  Assuming the last two notes attacked are supposed to fall on beat 4 and its upbeat, this leaves beat 3 missing a tiny subdivision, a 32nd triplet.  To fix that you would just need the last 16th triplet rest of beat 3 to be a regular 16th rest (not a triplet).
I'm guessing that your software was making an approximation to fill space the space that you thought was empty at the end of your measure.  It should also not loop as well as you might think, as it is off from a normal pulse (by that 32nd triplet).  You could hear this if you tried to sync it with another MIDI device or if you just put a metronome on against the loop they would eventually fall out of sync.
Answer: Here is what I believe is the most accurate and idiomatic notation for the audio example you have given:

As others have mentioned, swing 8th notes can be notated in many different ways. I have decided to notate your swung notes as dotted 8th - 16th pairs because it is common to do this when the swung note is particularly late, and also in order to differentiate the rhythmic placement of the last 8th note of the first measure. In your audio example, that note comes earlier in the beat than the rest of the swung 8th notes.
Others have mentioned triplet notation. The nuance of the use of these notations is very contextual. When reading jazz music, you will only really see swung triplets written out when the style of music is not swing to begin with (i.e. playing a latin chart), because that is the most typical rhythmic interpretation of swing, and is the implied interpretation for 8th notes all in a row. When reading music in a non-jazz (or more "classical") context, you will see triplet notation when the composer wants a swing rhythm to be played by non-jazz-trained players.
Back in the jazz context, however, you -will- see dotted 8th - 16th notation written out when the swung note is particularly late, and especially at lower tempos. Where the swing is not as strongly laid-back, you would just see 8th notes.
Comment: I didn't realise there were times when swing rhythm was assumed rather than written out, crazy jazzers
Comment: Strangely enough, all my drum books about swing use triplet notation.
Comment: If the books are meant to teach you different grooves, that's understandable -- they just want you to play the rhythms exactly as written. But as someone who has been playing jazz for over a decade, I guarantee you that nearly all published charts and lead sheets use swing 8th note notation. [For](http://www.guitarcats.com/images/JazzStandardCharts/STRAIGHT,%20NO%20CHASER-412.jpg) [example](http://www.youtube.com/watch?v=pthTtLZINHQ).
Comment: I think we need to reset or sync our terminology ;) A syncopation chart is not drum notation for me as a drummer. Jim Chapin, Gary Chester books are all syncopation books for me, but say, any other modern drum book that teaches technique etc. is a drum notation with everything in place cymbals, kick drums etc.
Comment: I don't have a lot of experience with drumset pedagogy literature... I just know what I would expect to see on a big band drumset part (or "chart").
Answer: If I'm hearing correctly (because it's kind of too fast to hear for me to judge the spaces between 16ths) it can be written as below (with some random notation site I've found online  www.noteflight.com )

I don't know what software settings are available but you need to turn the swing option on. Otherwise the triplets are placed onto a 32nd note grid with those crazy alignment artifacts. Moreover I don't know if you did it deliberately but the two beats at the end of first bar and the first two in the second bar sound like not swung enough hence the difficulty of transcibing them.


Hide section if there is no featured image

Question: I made a custom template for the team I'm working on. I used this code for the template (along with the parts that get the header and footer ofc)

<?php
 the_post();

 $thumbnail = has_post_thumbnail();

?>

   <?php the_post_thumbnail('full', array('class' => 'background-image')); ?>

      <?php
       if(!( $thumbnail ))
        the_title('
','
');

       the_content();
       wp_link_pages();
      ?>

But if there's no featured image, a gray box will appear. I'd rather just have the whole section be hidden if there is no featured image, because it will look much better.
I'm a php rookie so I have no idea how to do this. What I think I need to do: Have an if/else statement check for the featured image. If there is no image, add a class to said section and define 'display none' in my css file for that class.
So this is the code I tried to pair with that, but it did not work:

<?php
// Must be inside a loop.

if ( has_post_thumbnail() ) {
 the_post_thumbnail();
}
else {
 $("section:first").addClass("noshow");
}
?>

Is this code incorrect? Where do I need to place this in my document for it to work?
Comment: Your code would not work because $("section:first").addClass("noshow"); is jquery.  However you are on the right path with the if statement.

Use an if statement to check if the image is there. If it is there output it...

I would guess it is something like this.
Answer: While PHP is executed on the server, jquery is executed on the user end. You could always echo that jquery statement and that way it would be sent to the user.
You could follow the path Martin E. said on his comment (which in my opinion is a much cleaner version) or you could pursue the way you were working on by adding jquery on your header if you haven't and trying something like this:
<?php
if ( has_post_thumbnail() ) {
    the_post_thumbnail();
}
else {
    echo '';
}
?>

Comment: Thanks for your help! I deleted the part where it gets the thumbnail in the script because otherwise I'll have two thumbnails. However it's not giving the class to the section. Can I also call on a section with a class? The section that needs to disappear is the 'section-header'.
Comment: You can add it wherever you need to $(".section-header").addClass("noshow");


I uploaded images in my cpanel but I'm getting a 404 error, and I can't find them in my devtools?

Question: So Im fixing the gallery page on this website https://gilbertmovingandstorage.com/gallery.html as you can see certain images aren't loading? I uploaded them in the img folder on the cpanel. I can see them right next to those images that are visible in the gallery? The img src has no typos and its not a caching issue because I can't see these images in incognito either? Please someone help me I'm sick of all these issues! This project is taking me too long
here's proof that the images are in the folder https://i.stack.imgur.com/cUqz9.jpg
and here's a pic of two images and there src url. One can be viewed on the site and the other one can't? Even though there's no typo https://i.stack.imgur.com/sjtvl.jpg
Also looking at the source in the devtools then opening the img folder then the gallery_img folder I don't see the images there? I only see the ones that are visible on the site? So does that mean iit is a caching issue, and if it is why then can't I see it in incognito or when I clear the cache??
Answer: check permissions ??? you cant access the img if it has wrong permission
like rwx (read write execute)


RoutingError uninitialized constant

Question: I want to use token_authenticatable in my application (using Devise).
Using this answer I added class Users::SessionsController in file app/controllers/users_sessions_controller.rb (is file location correct?).
To generate authentication_token in database I added line current_user.reset_authentication_token! as fourth line of create method.
Using "Configuring Controllers" section from devise docimentation I added line devise_for :users, :controllers => {:sessions => "users/sessions"} to my routes.
I also have file app/views/users/session/new.html.erb.
Now when I try to log in or log out in browser, I get Routing Error uninitialized constant Users.
I have no idea what happens. I think I named controller class wrong, or placed it incorrectly, but don't know for sure.
Answer: If you want your controller named Users::SessionsController then it need to be in app/controllers/users/sessions_controller.rb
If you don't want nested folders for your controllers you could also do
class UserSessionsController

located at app/controllers/user_sessions_controller.rb with the routes being: devise_for :users, :controllers => {:sessions => "user_sessions"}
Comment: Yeah, exactly! I figured it out yesterday, but your answer is correct and helpful. Thanks for explanation :)
Comment: Two years later, you just made my night a bit less scary! :)

RoutingError uninitialized constant


Custom node tpl being ignored

Question: I have created a content type called 'Home' and I also create a new file called, node-home.tpl.php.
What I understood from the drupal documentation, that when a Node has the content type it should use node-contenttypename.tpl.php as the node template file, if it exists.
But mine isen't working and its defaulting back to node.tp.php.
Any idea what I'm doing wrong?
Answer: The file has to be called node--home.tpl.php.
There always has to be 2 '-' between type and name.
Comment: Great thanks! I read it here: https://drupal.org/node/17565, which I can only assume is for an older version.
Comment: Yes this one is for d6 and lower ;)

Custom node tpl being ignored


How to run batch file using Runas command from a batch file

Question: This is our batch file which we have this code but its not running the run.bat file.
Giving Error :
is not recognized as internal or external command
<code>@echo off
SET Identity=%userdomain%\%username%
CALL :ICACLS "%Identity%"
SET mypath=%~dp0
echo %mypath:~0,-1%
runas /noprofile /user:%Identity% "cmd /K %mypath%\run.bat"
</code>
Comment: what is the exact error? does it state `run.bat is not recognised as internal....`
Comment: also, let's see if that script actually finds the run.bat. just `rem` out the runas part and then add `type %mypath%\run.bat` as a line and see if it prints the content of run.bat to the screen
Comment: You are stipulating `/noprofile` but without seeing the content of `run.bat` we have no idea whether that is causing something to malfunction, _(you are already using the default,`%username%`, which suggests that using the default profile would be a safer option)_. Additionally, we have no idea of the posted script content which runs between `CALL :ICACLS %Identity%` until it returns just before `SET mypath=%~dp0`, _(this shouldn't be an issue if the value of `%Identity%` cannot change within that code)_.
Comment: it works, is run.bat in the same directory as the original script?
Comment: also, you set mypath to the current dir, why? you could just call `.\run.bat` seeing as both are in the same dir.
Comment: yes its in the same directory
Comment: try the code in the answer I am about to post.
Comment: @GerhardBarnard it won't run if i remove the %mypath%
Comment: error : is not recognized as internal or external command
Comment: so where does that word `error` come from? If I run the exact code you added in the test it works, can you post `run.bat` batch content?
Comment: How do you know the error isn't coming from inside run.bat?
Comment: i have run the bat file using call statement, and given the administrator rights to run.bat so it worked.. please remove the down votes
Answer: <code>Echo Soft
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
 if '%errorlevel%' NEQ '0'
 (
 echo Requesting administrative privileges...
 goto UACPrompt
 ) else ( goto gotAdmin )

:UACPrompt
 echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
 echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"

"%temp%\getadmin.vbs"
 exit /B

:gotAdmin
 if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
 pushd "%CD%"
 CD /D "%~dp0"
 ::your code goes here which needs to be run with admin rights::
</code>


Is a function with $0 \le f(x) \le x^2$ continuous at $x=0$?

Question:
If $f: \mathbb{R} \rightarrow \mathbb{R}$ with $0 \le f(x) \le x^2$, is it continuous at $x=0$ ?

I guess it is, because if $(x_n)_{n\in \mathbb{N}}$ is a sequence with $\lim_{n \to \infty} x_n = 0$ then
$$
0 \le \lim_{n \to \infty} f(x_n) \le \lim_{n \to \infty} x_n^2 = 0.$$ So $\lim_{n \to \infty} f(x_n) = 0 = f(0)$ and so $f$ is continuous at $x=0$.
Is that correct?
Comment: you can't have $0 < f(0) < 0$.
Comment: You shall say that $0<f(x)<x^2$ for for all $x\neq -$
Comment: Do you know the squeeze lemma?
Comment: Sorry, just corrected it.
Answer: Yes, it is correct. But there's no need to introduce sequences here. You can just say that, since $\lim_{x\to0}0=\lim_{x\to0}x^2=0$ and since $(\forall x\in\mathbb{R}):0\leqslant f(x)\leqslant x^2$, then $\lim_{x\to0}f(x)=0=f(0)$.
Comment: Or to put it differently, "This is an application of the squeeze lemma, which is frequently useful and therefore worth knowing."
Comment: @JohnHughes The OP is obviously aware of the squeeze lemma, since he/she used for sequences. I just observed that it can be applied directly to functions.
Comment: I guess I was hoping that OP might look up "squeeze lemma" and discover that it's far more general than just the sequence form, or that some later reader might do so. It's a matter of pedagogical taste, I guess.
Answer: You have to note that:

If $a_n \to a$(or $\limsup a_n=a$) and $a_n <b,\forall n\in \mathbb{N}$ then $a \leq b$

So if you take sequences to examine continuity then it must be $0 \leq \limsup_{n \to \infty} f(x_n) \leq 0$
We use limsups because we don't know if the limit exists a priori.
So if you take $\leq$ in your above relation then you are correct.
But if your realtion was a strict inequality then you have to remember this property of sequences.
Of course if you have strict inequality then $f(0)$ must be defined a priori.


Redirect unauthorized user to login page

Question: I need to show only home page and some inner pages (which i will create using a common content type) to the anonymous user. I need to redirect all other access to home page where i added a login box. Is there a way to do it.
Comment: is your requirement to redirect anonymous user to login page or in home page only when anonymous user access some section you have to redirect as you mentioned as accessing "light box"  in home page
Answer: In the permissions, make sure anonymous users don't have access. Then go to Configuration -> System -> Site information (admin/config/system/site-information). At the bottom, put your home page in 'Default 403 (access denied) page'.
All traffic going to an unaccessible page, will be redirected here.
Answer: This is sample for administrator.
<code>global $user;

if($user->uid = 1){ //check user here

  drupal_goto('some_page'); //redirect to some page.

  }
</code>
it will redirect administrator to whatever page you want.
if you want anonymous user redirect.You can use user_is_anonymous().
Sample:
<code>   if(user_is_anonymous()){ //check user here

      drupal_goto('some_page'); //redirect to some page.

      }
</code>
it will redirect anonymous to whatever page you want.
Answer: Rather than redirect to the homepage, I would suggest using this:
https://www.drupal.org/project/r4032login
it will allow you to explain to users why they've been redirected here, and also gives the the login page.
if you MUST redirect to the homepage,  you can set the 403 page location to be:  website.com/node
Comment: Is there a way to add some URLs which don't need authentication to view it.
Comment: This solution might work best with something like the [Node View Permissions](https://www.drupal.org/project/node_view_permissions) module. Set your permissions so anonymous users can only view the content types you want them to see, the rest should return a 403 access denied response which is where this module could take over.
Comment: I need to hide all taxonomy term page also from anonymous user.
Answer: I strongly suggest the module "Anonymous Login"
https://www.drupal.org/project/anonymous_login

This is a very simple, lightweight module that will redirect anonymous users to the login page whenever they reach any admin-specified page paths, and will direct them back to the originally-requested page after successful login.

You can also specify which pages you do not want to be restricted. These pages can be viewed by anyone.
I believe it can do exactly what you're asking.
Hope this helps.


Cannot get interface speed with standard MIB, use highperf mib (-g)

Question: Every hour, my team is receiving an email with the following text :
Shinken Notification

Notification Type: PROBLEM

Service: NetworkUsage
Host: Monitor
Address: localhost
State: UNKNOWN

Date/Time: 27-09-2016 Additional Info : Cannot get interface speed with standard MIB, use highperf mib (-g) : UNKNOWN

I think I found the server that has the problem (it's the monitoring server, since the address is localhost), but I can't figure out what to do (I'm a developer and know almost nothing about shinken, nagios or SNMP).
I think I'm missing a MIB that should be able to provide some kind of highperf function that would be able.
This is a very old server I don't know where to find / how to install this MIB.
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.04
DISTRIB_CODENAME=precise
DISTRIB_DESCRIPTION="Ubuntu 12.04.5 LTS"

How can I provide this method? Alternatively, how can I disable this particular check for this particular host?
Answer: This has nothing to deal with MIB. The message you get means that your interface in question uses 64-bit counters, and those are not enabled by default in check_snmp_int.pl or check_netint.pl.
As the error message suggests, you should add '-g -2' to check_snmp_int.pl command line definition under commands.cfg.
Comment: In my case `-g -2` reports an error message. According to check_snmp_int.pl help, `-g` or `--64bits`
Comment: I found the file, I have this inside : `command_line  $PLUGINSDIR$/check_netint.pl -H $HOSTADDRESS$ -C $_HOSTSNMPCOMMUNITY$ -n "$_HOSTNET_IFACES$" -g -2c -f -e -w $_HOSTNET_WARN$ -c $_HOSTNET_CRIT$ -q -k -y -M -B -m -P "$SERVICEPERFDATA$" -T "$LASTSERVICECHECK$"  -o $_HOSTSNMP_MSG_MAX_SIZE$`. So `-g` is there, but not `-2` (or maybe -2c works also ?) I'm going to look for check_netint.pl to see if the options are explained somewhere
Comment: I tried changing `-2c` with `-2`, we'll see if it works in 40 minutes :) Thanks for your answer :)
Comment: Still doesn't work :( I'm banging my head on the wall on this one…
Comment: Are you sure you have only one command instance of `check_netint.pl` or `check_snmp_int.pl` in your configuration? There should be another one without -g, as the code implies this to be absent for the error message you mention: `       if (! defined($o_highperf) && (defined($o_prct) || defined ($o_perfs) || defined ($o_perfp))) {
          print "Cannot get interface speed with standard MIB, use highperf mib (-g) : UNKNOWN\n";
   exit $ERRORS{"UNKNOWN"}
  }`
Comment: I looked again, and I think I might have changed something on the wrong monitoring server… it works now! Thanks a lot!!!


Javafx button hover effect

Question: I have a button that changes color when I move the mouse in, but it looks stiff.
I want to have a CSS transition color transition effect.
Translated with translation tools. I don't know if you can understand it.
public void start(Stage primaryStage) throws Exception {
        // border布局器
        BorderPane borderPane = new BorderPane();
        // Hbox 顶部菜单开始
        HBox menuTop = new HBox();
        menuTop.setStyle("-fx-border-width: 1;");
        menuTop.setStyle("-fx-border-color: #cccc;");
        menuTop.setPadding(new Insets(5,5,5,5));
        menuTop.setSpacing(10);
        Button button1 = new Button("new");
        Button button2 = new Button("open");
        Button button3 = new Button("save");
        Button button4 = new Button("settings");
        Button button5 = new Button("help");
        Button button6 = new Button("about");
        menuTop.getChildren().addAll(button1, button2, button3, button4, button5, button6);
        for (Node Elemt: menuTop.getChildren()) {
            Elemt.setStyle("-fx-border-width: 2;");
            Elemt.setStyle("-fx-border-color: #FFE4C4;");
            Elemt.setStyle("-fx-background-color: #FFDAB9;");
            Elemt.setCursor(Cursor.HAND);
            // I want MouseMoved button background-color effect
            // 鼠标移入
            Elemt.onMouseMovedProperty().set(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    Elemt.setStyle("-fx-background-color: #FFC125;");
                }
            });
            // 鼠标移出
            Elemt.onMouseExitedProperty().set(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    Elemt.setStyle("-fx-background-color: #FFDAB9;");
                }
            });
        }
        // Hbox 顶部菜单结束
        borderPane.setTop(menuTop);
        // 场景
        Scene scene = new Scene(borderPane);
        primaryStage.setWidth(440);
        primaryStage.setHeight(300);
        primaryStage.setResizable(false);
        primaryStage.setScene(scene);

        primaryStage.show();
    }

Comment: Welcome and thanks for the translation-warning: We can understand, what you want. Please also post your JavaFx code as [example]. So we can search there for the issue.
Comment: How should I send my code?
Comment: @陈慢慢 [edit] your question and include it there. But *please* make it minimal, complete and reproducible as asked.
Comment: I know,but thank you
Answer: Did you try specifying a CSS stylesheet as explained in:

Button Hover and pressed effect CSS Javafx

CSS Stylesheet file (using IDs)
File name: ButtonStyles.css
#my-button {
    -fx-border-width: 2;
    -fx-border-color: #FFE4C4;
    -fx-background-color: #FFDAB9; /* 鼠标移出 */
    cursor: pointer; // seems like Cursor.HAND
}

/* I want MouseMoved button background-color effect 鼠标移入 */
#my-button:hover {
    -fx-background-color: #FFC125;
}

#my-button:pressed {
    -fx-background-color: #FFDAB9; /* maybe some other color */
}

Then those styles are applied to elements with the id of my-button.
So add the styles to the button(s) and set their id.
Button button1 = new Button("new");
// set id and add stylesheet
Button button2 = new Button("open");
// set id and add stylesheet
Button button3 = new Button("save");
// set id and add stylesheet
Button button4 = new Button("settings");
// set id and add stylesheet
Button button5 = new Button("help");
// set id and add stylesheet

Button button6 = new Button("about");
// set id and add stylesheet
button6.setId("my-button");
button6.getStylesheets().add(getClass().getResource("ButtonStyles.css").toExternalForm());

The buttons 1..5 are left to you.
Explained
The cursor is set to a pointing finger, with css-property cursor.
The styles have been copied from your Java-code.
Another guide is: styling JavaFx buttons with CSS.
You may also improve and create a List of buttons, so you can add the style to all buttons in and a loop.
Simplify using a Scene
Like explained in:

JavaFX - CSS tutorial
JavaFX Button Hover

So you can overwrite the CSS-class .button (used in JavaFX to style buttons) instead of single IDs. So replace id-selector #my-button by .button in the CSS file.
new CSS Stylesheet file (using classes)
File name: button.css
.button {
    -fx-border-width: 2;
    -fx-border-color: #FFE4C4;
    -fx-background-color: #FFDAB9; /* 鼠标移出 */
    cursor: pointer; // seems like Cursor.HAND
}

/* I want MouseMoved button background-color effect 鼠标移入 */
.button:hover {
    -fx-background-color: #FFC125;
}

.button:pressed {
    -fx-background-color: #FFDAB9; /* maybe some other color */
}

Adding a style to the scene
Then define the scene (optionally restricted to appropriate dimension), add the stylesheet to it, set it to your container and it will apply to all buttons inside the container.
You had already defined and set your scene to the primaryStage, great  So you need only to add the CSS stylesheet.
        Scene scene = new Scene(borderPane);
        scene.getStylesheets().add(this.getClass().getResource("button.css").toExternalForm());  // add the CSS stylesheet

        primaryStage.setWidth(440);
        primaryStage.setHeight(300);
        primaryStage.setResizable(false);
        primaryStage.setScene(scene);

        primaryStage.show();

Transition of background-color
CSS Transitions (for testing)
They are explained in the tutorial CSS Fundamentals: CSS3 Transitions.
You can also test them first in regular HTML like the one below:

/* NOTE: removed the "-fx-" prefixes from properties, to make it work with HTML in browser

.button {
    border-width: 2;
    border-color: #FFE4C4; /* color-name Bisque */
    background-color: #FFDAB9; /* 鼠标移出 */
    cursor: pointer; // seems like Cursor.HAND
}

.button:hover {
    background-color: #FFC125; /* color-name Goldenrod */
    /* linear transition gradually fading to the color for 1 second */
    -webkit-transition: background-color 1s linear;
    -ms-transition: background-color 1000ms linear;
    transition: background-color 1s linear;
}
<button class="button">Button with Transition</button>

Transition must be implemented in JavaFX
Like the answer from jewelsea in 2018 explained:

There is no direct support in JavaFX css for animation. You need to perform the animation steps in Java code to modify the css style.

I researched again for "applying CSS transitions in JavaFx" but did only find alternatives that follow the official guide Creating Transitions and Timeline Animation in JavaFX:

JavaFX Transition - Darken button on hover
How to make an animation with CSS in JavaFX?

Sorry, for now I only can explain the background-color change and on hover to you. The linear color transition is already answered (see questions before).
Comment: sorry。When the mouse moves to the button, it will change color slowly and gradually
Comment: In fact, it's like fadetransition darkening effect, but what I want is color change
Comment: A change like a chameleon

Javafx button hover effect


Get menu item of a node

Question: I have a node (in D8) which is placed in the menu "Main navigation". How do I get the menu item (in code)? In Drupal 7 you could use $node->menu but in 8.x, the object is not populated with menu information. So, how do I retrieve it? I also want to support another type of menus in the future, so something which works with more than the menu_link_content module is appreciated.
Answer: You can try this code:
use Drupal\menu_link_content\Entity\MenuLinkContent;

$node_id = 1;
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));

dpm($result);

Comment: Which will give us an array of all menu items this node belongs to. We can then foreach for the menu name to get the one we need.
Comment: Thanks this worked great. Just a note that I added this to get to the actual MenuLinkContent object
 ```/* @var $menuLink Drupal\menu_link_content\Plugin\Menu\MenuLinkContent */
    $menuLink = array_pop($result);``` which gives you an instance of https://api.drupal.org/api/drupal/core%21modules%21menu_link_content%21src%21Entity%21MenuLinkContent.php/class/MenuLinkContent/8.8.x

Get menu item of a node


Show that $2^a|(x-1)$ iff $2^a|(y-1)$.

Question: Suppose that $2^n + 1 =xy$, where $x$ and $y$ are integers > $1$ and $n>0$.
Show that $2^a|(x-1)$ iff $2^a|(y-1)$.
Here $a|b$ implies $a$ divides $b$.
Answer: $$(x-1)(y-1) = 1 + xy - x - y = 2^n - (x - 1) - (y - 1)$$
Then if $2^a$ divides $(x-1)$ then it definetile divides $(y-1)$, because
$$(y - 1) = 2^n - (x - 1) - (x-1)(y-1).$$
Answer: WLOG let $x-1=p2^a,y-1=q2^b$ where $p,q$ are odd and $a\ge b>0$
$$1+2^n=xy=(p2^a+1)(q2^b+1)=pq2^{a+b}+p2^a+q2^b+1$$
$$q=2^{n-b}-pq2^a-p2^{a-b}$$
As $n-b>0$
$q$ will be even if $a>b$
and $q$ will remain odd if $a=b$

Show that $2^a|(x-1)$ iff $2^a|(y-1)$.


Is it possible to extend a class with a default private constructor in Dart?

Question: Suppose that we have a class a:
class A {
  A._();
}

Its default constructor is private: A._().
Is there any way to extends that class?
Problem
class B extends A {

}

This results in a compiler error:
The superclass 'A' doesn't have a zero argument constructor.

Trying to compose any constructor for B myself (B()) results in another error:
The superclass 'A' doesn't have an unnamed constructor.

Comment: If you write a constructor, the class does not get a default constructor (the implicit `A():super();` constructor that would be added otherwise). The `A._` constructor is not a "default constructor", nor is it an unnamed constructor. You can still add an unnamed constructor `A();` to the class as well.
Comment: @lrn *Default constructor* was the term I found for it. Usually it would be `A()`, but that gets removed once `A._()` is added. Thus `A` does neither have a *public* zero argument nor unnamed constructor. `A()` would be zero argument und unnamed.
Answer: No, there is no way. This is an effective way to prevent extending.
What you still can do is implementing the class.
class B implements A {}

If the class also has a public non-factory constructor, you can still extend it by forwarding the constructor call to such a named constructor of the super class.
class B extends A {
  B() : super.other();
}

Comment: That is awful. What reason would there be to prevent extending? I noticed that implementing was possible, but that is not what I am looking for. Also, I will just adjust my question with *PascalCase*. I wrote those error messages myself. I did not really name classes *`a`* and *`b`*.
Comment: Extending can either add features or broke it. :) Depends on the implementations.
Comment: "Ignoring it would be my own responsibility". If a developer doesn't want his classes to be used in ways that would prevent them from working correctly, he should have the power. If this prevents you from using a package, then raise an issue to make the author aware. Not everyone wants a JavaScript-like world where everyone can do what he wants and then swamp the internet with complaints and bug reports and buggy code ;-)
Comment: Most serious programming languages allow that https://stackoverflow.com/questions/10170633/c-sharp-sealed-vs-java-final. There are many things a class can't guarantee when it can be extended.
Comment: Extending would only add features, or am I wrong? If the class is not intended to be extended, there are no overrides necessary anyway and one could just add to the class what they want. I also do not understand why privacy is enforced by the compiler.  Ignoring it would be my own responsibility.


Simple WPF ComboBox ItemsSource Binding doesn't work

Question: I'm just getting started with WPF and Visual Studio 2010.
When I try the following simple ComboBox binding, I get error messages.
XAML:
...
<ComboBox Height="23" HorizontalAlignment="Left"
Margin="33,18,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120"
ItemsSource="{Binding Path=test}"/>
...

Code File:
public partial class SetupWindow2 : Window
{
    public List<string> test { get; set; }
    public SetupWindow2()
    {
        test = new List<string>() { "1", "2", "3" };
        InitializeComponent();
    }
}

Error Messages:
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=test; DataItem=null; target element is 'ComboBox' (Name='comboBox1'); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 40 : BindingExpression path error: 'test' property not found for 'object' because data item is null.  This could happen because the data provider has not produced any data yet. BindingExpression:Path=test; DataItem=null; target element is 'ComboBox' (Name='comboBox1'); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 19 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=test; DataItem=null; target element is 'ComboBox' (Name='comboBox1'); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 20 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=test; DataItem=null; target element is 'ComboBox' (Name='comboBox1'); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=test; DataItem=null; target element is 'ComboBox' (Name='comboBox1'); target property is 'ItemsSource' (type 'IEnumerable')

Where is the problem here?
Comment: Window constructor should contain InitializeComponent() call. You also need to specify a data context, i.e. DataContext = this;
Answer: Whenever binding fails you should check the DataContext first and then the Binding expression.
In your case I would say the right datacontext is missing, so if your combobox is in your setupwindow2 you should add:
public partial class SetupWindow2 : Window
{
   public List<string> test { get; set; }

   public SetupWindow2()
   {
      test = new List<string>() { "1", "2", "3" };
      this.Datacontext = this;
   }
}


How do you prove that a formally constructed total ordering is unique?

Question: Seth Warner's Modern Algebra Exercise $14.22$ gets us exploring the properties of semilattices, in particular join semilattices.
Context: self-education.
The specific question that has been given is:

(b) If $(E, \vee)$ is a commutative idempotent semigroup such that every subset of $E$ is stable for $\vee$, then there is a unique total ordering $\le$ on $E$ such that $$x \vee y = \max \{ x, y\}$$

Notes:

a commutative idempotent semigroup is better known as a semilattice, as I have learned from studies elsewhere;
stable in this context means "closed": that is, every subset of $E$ is a subsemigroup of $E$.

It is straightforward though mildly laborious to prove that $\vee$ induces such a total ordering: reflexivity follows from idempotence, antisymmetry follows from commutativity, and transitivity from associativity, and connectedness follows from the closedness property as shown above.
Now, I've proved the existence of that total ordering, and I have shown that it has the property
$x \vee y = \max \{ x, y\}$.
Basically, the ordering $\le$ is defined as:
$$x \le y \iff x \vee y = y$$
and the rest follows easily.
Now, what I don't understand how to do is that final bit:
prove that $\le$ is a unique total ordering.
The only way I can conceive of a total ordering being "unique" is by showing that: suppose $\le_1$ and $\le_2$ are total orderings.
Then $\le_1$ and $\le_2$ are the same total ordering iff for any arbitrary $x \in E$, we have:

$\{y \in E: y \le_1 x\} = \{y \in E: y \le_2 x\}$
$\{z \in E: x \le_1 z\} = \{z \in E: x \le_2 z\}$

which looks horribly daunting to prove for the general set $E$, and I really don't know where to start.
Answer: You are supposed to prove that there is a unique total ordering with the property that $\max(x,y)$ (defined in terms of the ordering) is always equal to $x\vee y$.  In other words, you want to show that if $\leq'$ is any other total ordering with this property, it must be equal to your $\leq$ defined by $x\leq y$ iff $x\vee y=y$.  But this is trivial, since by assumption $\max_{\leq'}(x,y)=x\vee y$ and $\max_{\leq'}(x,y)=y$ iff $x\leq'y$.
Comment: All the hint I needed. It was the concept of what I was trying to achieve that I had not quite grasped. My understanding is more solid now.


How express Hapi.js Restfy Koa app.listen() and app.get() work?

Question: With http node module (only native modules) how i can recreate app.listen() and app.get() use http module with a constructor
var app = function(opts) {
     this.token= opts.token
 }

 app.prototype.get = function(callback) {
     // use request and response of app.listen()
   }

  app.prototype.active = function(callback) {
  // use request and response of app.listen()
  // return on callback some manipulate
  //request params
}

app.prototype.listen = function() {
 // start http or https server
}

Import the modules and work with this
var app = require(...)

Var client = new app({
token: 0000
})

client.get(function(error, reply) {})
client.listen()

Comment: Not sure what you're asking. Are you asking how to implement some basic features of your own http framework on top of Node's core http module?
Comment: @MattHarrison create same express logic create app and routes and listen them. new app and app.get() app.listen()
Comment: Did you look at the express source code for those methods?
Comment: @MattHarrison o yes but is very very hard to underrated this part of code
Comment: Possible duplicate of [How app.listen() and app.get() work on express and hapi](http://stackoverflow.com/questions/36822554/how-app-listen-and-app-get-work-on-express-and-hapi)
Answer: It's pretty easy to build your own very simple HTTP framework on top of Node's http module. Here's a quick one I made which implements the app.get() and app.listen() methods, you can see how it could grow to become something more Express-like:
'use strict';

const Http = require('http');
const Url = require('url');

// Framework

const Framework = function (options) {

    this.options = options;
    this.routes = [];
    this.listener = Http.createServer(this._onRequest.bind(this));
};

Framework.prototype.get = function (path, handler) {

    this.routes.push({ path, method: 'GET', handler });
};

Framework.prototype.post = function (path, handler) {

    this.routes.push({ path, method: 'POST', handler });
};

Framework.prototype.listen = function (callback) {

    this.listener.listen(this.options.port, callback);
};

Framework.prototype._onRequest = function (req, res) {

    // Find the first matching route

    for (let i = 0; i < this.routes.length; ++i) {
        const route = this.routes[i];
        const url = Url.parse(req.url);
        if (route.method === req.method && url.path === route.path) {
            return route.handler(req, res);
        }
    }

    // No matching routes

    res.writeHead(404);
    res.end('Not found');
};

You can use this mini framework like so:
const app = new Framework({ port: 4000 });

app.get('/', (req, res) => {

    res.end('Home page');
});

app.get('/about', (req, res) => {

    res.end('About page');
});

app.listen(() => {

    console.log('Started server!');
});

You can test it with a few cURL requests:
$ curl -i http://localhost:4000/

HTTP/1.1 200 OK
Date: Sun, 24 Apr 2016 14:38:02 GMT
Connection: keep-alive
Content-Length: 9

Home page

$ curl -i http://localhost:4000/about

HTTP/1.1 200 OK
Date: Sun, 24 Apr 2016 14:38:08 GMT
Connection: keep-alive
Content-Length: 10

About page

$ curl -i http://localhost:4000/spaghetti

HTTP/1.1 404 Not Found
Date: Sun, 24 Apr 2016 14:38:14 GMT
Connection: keep-alive
Transfer-Encoding: chunked

Not found

Obviously this is a really basic framework and suffers from many problems that frameworks like hapi have solved:

There's no support for parameters in paths e.g. /users/{id}. The URL paths must match the route path exactly
The order that you add routes is important (this can lead to issues)
Conflicting paths are permitted
Missing a lot of nice features like serving files and rendering templates (although you could do this in the handlers manually)


DIV / Table Headers are on bottom, jSON data is on top?

Question: I cant seem to figure this one out. I have tried various of things with no luck. Any ideas on how to resolve this?
I have attached a link for a screenshot of what I am getting...
http://s23.postimg.org/4eu3mhmyj/Capture.png

Counts

                      <form method="POST" action="">
                     <button type="submit" class="btn btn-default btn-sm pull-right" name="reset"></button>
            </form>

                  Count
                  Item

Comment: Can't really see the image. And also, adding css will help us to trace your problem. I think your problem is with css. Did you also try inspecting the output html?
Answer: I was able to resolve it. Had to change the JSON output from a div to a Tbody. :)
Comment: Please use the edit link on your question to add additional information. The Post Answer button should be used only for complete answers to the question.
Comment: @leesei Why so? It looks like the OP has found the answer to his question.
Answer: Update your JSON output from a DIV to a TBody should help you out.

                  Count
                  Item


Add dynamic fields by pressing Enter

Question: my code add a new text field when I press the ENTER screen on the keyboard but it only works on the first text field on the next when I just typed the value and pressing Entrer it does not add a new field.
Already leaves a search in the questions of forum and not find the solution.

        <button class="add_field_button">Add More Fields</button>

<input type="text" name="mytext[]">

Comment: I tried your code, it works fine
Comment: @SujitAgarwal the problem starts when I click on the second text field type and press enter
Comment: Check @abderrahim's answer. That would fix your issue.
Comment: What you need is "event delegation" - you should read about it as it's a common issue when creating interactive elements dynamically.
Answer: Try this code :
 $('body').on('keypress','input[type=text]', function(e){
            if (e.keyCode == 13) {
                e.preventDefault();
                $(".add_field_button").click();

            }
        });

Comment: Yes it's a common error in Jquery with dynamically added element you have to bind them to an existing element like body in this case
Comment: Also if you don't want to bind it to the whole `body`, you could bind the event handle to your `` since that is there from the start. `$('.input_fields_wrap').on...` instead of `$('body').on...`
Comment: @AbderrahimSoubaiElidrissi Your answer worked perfectly and just takes me another question, I need it to go into the new text field type a TAB. It's possible?
Comment: @IncredibleHat sure
Comment: I was just mentioning it as an alternative for @IsrayaneNayara :) Your answer works, and `body` is fine.
Comment: @IsrayaneNayara move to next input it's default Tab button behavior but you can override it and set the focus into the next() input to this
Comment: @AbderrahimSoubaiElidrissi I'll give it a look. Thanks.
Comment: @AbderrahimSoubaiElidrissi I tried $ (this) .prev ('input'). focus (); and it did not work. And $(this).prevAll('input:first').focus()
Comment: please make a working exemple here jsfiddle.net and i will take a look after
Comment: @AbderrahimSoubaiElidrissi THANK YOU VERY MUCH FOR YOUR HELP AND YOUR TIME. SOLUTION: $ ("input").focus ();

Add dynamic fields by pressing Enter


Waiting for targets in a CMake build

Question: I think I do have a CMake order/parallelism problem.
In my build process, I need to build a tool which is then later used by some other target. This tool is a separate project with a CMakeLists.txt file like this:
project (package-tool LANGUAGES CXX)
set (SOURCES package_tool.cpp)
...

Later in the build, this top level target is referenced by some other target:
...
add_custom_command (OUTPUT "${DST_FILE}"
                            COMMAND ${PACKAGE_COMMAND} "${DST_FILE}"
                            COMMAND package-tool.exe -e "${DST_FILE}"
                            DEPENDS ${PACKAGE_DEPENDENCIES} package-tool)
...

I use ninja for building and the dependencies (ninja -t depends) are looking correctly. Also, the build commands (ninja -t commands) are making sense. But: From time to time, the build fails. The message does not make sense, it reads:

This version of package-tool.exe is not compatible with the version
of Windows you're running.

Because the build runs in parallel (32 processes) I suspect that the package-tool target is not completed when the generated exe is being used in the second target, which might lead to this confusing error message. Again, most of the time the build succeeds but every 10th or 20th run, it fails with that message.
So now my question is:

Is there a way to wait for a tool/target having been finished building in a parallel build in CMake/Ninja ?
Or how do I handle the task of building build tools in the same build process correctly ?

Thank you in advance !
Comment: "I suspect that the package-tool target is not completed when the generated exe is being used in the second target" - As you say, `ninja` outputs dependencies as you expect. So, do you suspecting ninja to not follow these dependencies? Then the question should be not about CMake and writing `CMakeLists.txt`, but about ninja and its wrong behavior. It could be that a reason of the error you got is **somewhere else**.  But we could only **guess** about that, and *guessing* is not how Stack Overflow works.
Comment: Hmm... I think you are right. It does not make sense that CMake handles the concurrency, ninja should do that. Rethinking that, I would assume that a ninja step simply waits until the files it depends on are all present, so another cause for that problem outside of the CMake/Ninja domain does probably exist. Thank you for the insight !
Answer: Actually depend on the executable file and run the executable file, not the target. Don't concern yourself with any .exe suffix. Also better don't assume add_custom_command will be run in CMAKE_RUNTIME_OUTPUT_DIRECTORY - if you depend on specific directory explicitly set it with WORKING_DIRECTORY.
add_custom_command (
    OUTPUT "${DST_FILE}"
    COMMAND ${PACKAGE_COMMAND} "${DST_FILE}"
    COMMAND $<TARGET_FILE:package-tool> -e "${DST_FILE}"
    DEPENDS ${PACKAGE_DEPENDENCIES} $<TARGET_FILE:package-tool>
)

Comment: Instead of `$` CMake allows to specify just a target name:  `COMMAND package-tool -e "${DST_FILE}"`. Also, with both ways - `TARGET_FILE` or simply target name - CMake automatically adds a **target**-level dependency from the `package-tool`. It is up to the project whether a  **file**-level dependency from `package-tool` is needed or not. Such *file*-level dependency would only force custom command (more precisely, a custom target which depends on the command) to be re-run whenever the executable is changed.

Waiting for targets in a CMake build


How do I incorporate an if-statement within my array to hide/display a link?

Question: Using the coding snippet below, how would I write the code to display the "Change" link only when the value in status is "A"?
I think i'm making this harder than it has to be, but the use of both drupal module structure and php are throwing me, since i am just learning module development.
The link showing in the array below appears at the end of each of my rows. I only want it to appear when the status equals "A".
Because this link is within this array, i can't figure out how and where to implement it. I just want an [if statement] like this:
if (drupal_render($form['status'][$key]['status']) == 'A',)
echo l(t('Change'), 'rooms/avail_room/' . $key . '/' . arg(1), array('attributes' => array('class' => 'room-stat-avail'))),
else{
echo "";
}

so when the html table is displayed, the 'Change' link will only appear in the last column when the value of status is "A"
Can't believe I got the module working, but can't turn this link on/off as i want. See code snippet below:
function team_room_available_form($form) {
    $output = "No space available.";

  if ($form['roomid']) {
    foreach (element_children($form['roomid']) as $key) {
      $rows[] = array(
        'data' => array(
          drupal_render($form[''][$key]),
          drupal_render($form['room_title'][$key]),
          drupal_render($form['username'][$key]),
          drupal_render($form['status'][$key]['status']),
          l(t('Change'), 'rooms/avail_room/' . $key . '/' . arg(1), array('attributes' => array('class' => 'room-stat-avail'))),
        ),
        'class' => $form['status'][$key]['#value'],
      );
    }

Answer: You can use below code snippets:
$field = $form['status'][$key]['status'];

if (strip_tags($field) == 'A')
echo l(t('Change'), 'rooms/avail_room/' . $key . '/' . arg(1), array('attributes' => array('class' => 'room-stat-avail'))),
else{
echo "";
}


What is minCases in C5.0Control using R

Question: from Package (C5.0 Decision tree Using R ) definition     "minCases : an integer for the smallest number of samples that must be put in at least two of the splits."
I very confuse about it . Please help me  to expand understand more.
Answer: you can find the following answer on https://www.euclidean.com/machine-learning-in-practice/2015/6/12/r-caret-and-parameter-tuning-c50. I hope it helps to solve your problem.

The minCases parameter specifies the minimum number of cases (training examples) that must be put in at least two of the splits. Essentially it controls the depth of the trees created by C5.0 (depth cannot be controlled directly) and hence it is intimately connected with the resulting tree complexity. The purpose of tuning meta parameters is to find the optimal trade-off between model complexity and the training set size and so minCases is an important parameter to tune. That said, tuning minCases is problematic under cross-validation because the number of cases in the training folds are different than the number of cases in the entire dataset so the optimal value of minCases found in cross validation will not be equal to the true optimum for the entire data set (which the final model will be trained on). To overcome this obstacle we can define minCases as a proportion of the data set size and tune the proportional parameter instead. If we define minCases as
  minCases <- length(y)/splits
  then as "splits" increases, so will the depth and complexity of the resulting trees.

What is minCases in C5.0Control using R


How can i take N(read from user) number of inputs in an array, in python 3?

Question: I want to do it like we do in java where we take the number of elements from the user and then declare the  array with the provided size.
ie;
int[] arr=new int[n];
Comment: What have you tried so far?
Comment: So are you just getting the size from the users, not the values?  And why do you need to 'declare an array'?  This is Python, not Java.  Usually it is better to create the array or list with the desired values right away, rather than initialize followed by a 'fill'.  But maybe more important - do you want a Python list, or a `numpy` array?
Answer: In Python, arrays are called lists and don't have a fixed length. But if you want to create a list with N elements that will all be zero, you could use this code:
<code>n = int(input())
lst = []
for x in range(n):
    lst.append(0)
</code>
Comment: Why not `[0]*n` ?
Comment: OP is clearly a beginner and `[0] * n` is somewhat error-prone. `int`s are primitives so this approach happens to work as expected, but if you were to initialize a list of objects this way (for instance a list of lists), you would see that all its elements are in fact the same object. So I would argue that Daniel Cohen's solution is more beginner-friendly as it keeps them away from shooting themselves in their feet.


How to access fields from node template without render

Question: within node template, i am trying to print a content type field value. usually I see the render function used to print the field value in the template e.g. render($content['field_name']). how do i just print the field value?
$content['field_name'][$lang][0]['value'] doesnt work
Answer: You can do it like this:
$lang = field_language('node', $node, 'field_name'); // gets field language

print $node->field_name[$lang][0]['value']; // prints field


Returning from decorator function to Member function in a class

Question: I have written a decorator function which is working fine when I decorate to a normal function but when I decorated to a member function in class its throwing TypeError: print_cmd() takes exactly 2 arguments (1 given)
The decorator function is working fine with normal function but same is not working for a member function of class
ss=[]
def deco(func):
   def new_func(*args, **kwargs):
       for i in new_arg:
            "Do some operation"
       return func(','.join(ss))
   return new_func
class aaa:
   @deco
   def print_cmd(self,cmd):
       print cmd

ii=aaa()
ii.print_cmd('hello,ff,are')

TypeError: print_cmd() takes exactly 2 arguments (1 given)
Comment: can you put also your @deco ?
Answer: In order to properly call the wrapped function with its original arguments, try this code instead:
return func(*args, **kwargs)

The original code calls the wrapped function with a single string argument, and not the original function's arguments:
return func(','.join(ss))

Comment: My intention is to refactor the cmd and if I'm passing back *args,**kwargs.I wont get the modified cmd which is ','.join(ss)
Comment: This decorator is working fine if im using with normal function,Im getting issue with member function in class
Comment: It's not working on member functions in a class because they accept more than 1 argument. Try your decorator on any function which accepts more than 1 argument and it won't work.
It will also prevent a decorated function from working as it should because it does not send the original argument, but the string (which consists of the element of the list ss) that you are creating.


What does a non-mathematician need to google to learn more about latin squares in which each number in each row always has a different successor?

Question: First off, my apologies for the long and convoluted title. I am no mathematician so I don't know the "proper" terms to use... which is exactly my problem:
I want to find a/any/one Latin square of order 8 in which each pair of numbers in each row only occurs once in the complete square, i.e. I am looking for a latin square $L\in\mathbb{N}^{n\times n}$ in which each pair $(l_{i,j},l_{i,j+1}), i\in[1,n],j\in[1,n)$ is unique.
Here is an example for an order-4 square:
A "regular" Latin square that does not  have the property I am looking for:
$$
A=
\begin{bmatrix}
1 & 2 & 3 & 4 \\
2 & 3 & 4 & 1 \\
3 & 4 & 1 & 2 \\
4 & 1 & 2 & 3 \\
\end{bmatrix}
$$
A Latin square that has the property I am looking for:
$$
B=
\begin{bmatrix}
1 & 2 & 3 & 4 \\
2 & 4 & 1 & 3 \\
3 & 1 & 4 & 2 \\
4 & 3 & 2 & 1 \\
\end{bmatrix}
$$
For example, in $A$ the pair $(a_{1,2},a_{1,3})=(2,3)$ is repeated in the the rows 2 and 3 as $(a_{2,1},a_{2,2})$ and $(a_{3,3},a_{3,4})$, respectively. In $B$, however, that same pair $(b_{1,2},b_{1,3})=(2,3)$ is not repeated. Is there a name for this property?
To be honest, I don't even know if such a Latin square exist for order 8, but so far I haven't been able to find some related information, mainly as I don't know what to google for :(.
Any answer that gives me some searchable terms would greatly help me. Of course, a direct example of a Latin square of order 8 with the property I am after would be even more appreciated.
Thanks in advance for spending your time responding.
PS:In case somebody is wondering why I am looking for this: I am trying to set up a full factorial experiment with 3 factors at 2 levels each, i.e. $2^3=8$ cases. I would like to use the Latin square I am after to find sequences of the individual experiments in which two experiments never follow each other more than once so that I can exclude any training or learning effects from one to the other.
Edit:
While further looking onto this I noticed that my given example square $B$ shows additional properties that I actually don't really care for: I neither need $B$ to be in reduced form (first row and first column are in natural order), nor do I need $B$ to be symmetric ($B=B^T$).
Comment: Dear @hcc23, you just require that the pairs do not repeat horizontally, am I right ?  You also don't need to exclude circular pairs (seeing the latin square as a cylinder or a torus) ?
Comment: @ogerard: Yes, you are correct: no "wrap around" and no comparison between rows (i.e. the pair $(a_{i,j},a_{i+1,j})$ can repeat). Order also matters, i.e. $(x,y)$ is different from $(y,x)$. My apologies if my notation isn't as concise as it should/could be.
Answer: Hi I believe that the name of the property you are describing is row complete. See here for more information http://personal.maths.surrey.ac.uk/st/H.Bruin/MMath/LatinSquares.html
Comment: Thanks for not only providing the name but also a very easy to read reference. A quick MATLAB script based on the method outlined in your reference (https://gist.github.com/hcc23/274b76edc3dd82d5de1a) instantly provided what I needed :) Thanks!
Comment: @hcc23 I'm glad that it was useful to you!
Comment: An archive version is at https://web.archive.org/web/20170708014237/http://personal.maths.surrey.ac.uk/st/H.Bruin/MMath/LatinSquares.html
Answer: Using the method for row-complete cyclic Latin Squares given in the H.Bruin page cited by the other answer for n=8, gives:
$$\left(
\begin{array}{cccccccc}
 1 & 2 & 8 & 3 & 7 & 4 & 6 & 5 \\
 2 & 3 & 1 & 4 & 8 & 5 & 7 & 6 \\
 3 & 4 & 2 & 5 & 1 & 6 & 8 & 7 \\
 4 & 5 & 3 & 6 & 2 & 7 & 1 & 8 \\
 5 & 6 & 4 & 7 & 3 & 8 & 2 & 1 \\
 6 & 7 & 5 & 8 & 4 & 1 & 3 & 2 \\
 7 & 8 & 6 & 1 & 5 & 2 & 4 & 3 \\
 8 & 1 & 7 & 2 & 6 & 3 & 5 & 4
\end{array}
\right)$$
Of course, any permutation of its rows will do.
But if what you really need is to run all the successive
couples in the most efficient way, here is another way to do
it. This sequence contains all the 56 different pairs and use
only 57 different terms (even 56 if you use the fact that it
starts and ends by the same symbol) instead of the 64 of the 8x8 latin square :
<code>(2, 3, 1, 4, 8, 5, 7,
 6, 7, 5, 8, 4, 1, 3,
 2, 1, 2, 8, 3, 7, 4,
 6, 5, 6, 4, 7, 3, 8,
 2, 5, 1, 6, 8, 7, 8,
 6, 1, 5, 2, 4, 3, 4,
 5, 3, 6, 2, 7, 1, 8,
 1, 7, 2, 6, 3, 5, 4, 2 )
</code>
and you can vary it by any translation or any of the 40320 permutations of the 8 symbols for your operations such as this one:
<code> (1, 2, 3, 4, 5, 6, 7, 8,
  7, 6, 5, 4, 3, 2, 1, 3,
  1, 5, 2, 7, 4, 8, 6, 8,
  4, 7, 2, 5, 1, 6, 3, 8,
  5, 7, 5, 8, 3, 6, 1, 4,
  2, 4, 6, 2, 8, 1, 7, 3,
  5, 3, 7, 1, 8, 2, 6, 4, 1}
</code>
You can think of such a sequence as a minimal string in base 8 containing all 2-digits combinations.
Comment: I don't understand enough of Latin squares to be sure, but if I understand "circular" as "wrapping around from the last column to the first" (i.e. the same way as your comment on my original question), than I don't think that the Bruin method provides circular row-complete Latin squares. Looking at the example, $(5,1)$ appears to occur twice: "regularly" as $(a_{3,4},a_{3,5})$ and "circular" as $(a_{1,8},a_{1,1})$. Is there something that I am missing?
Comment: No you don't miss anything. You spotted a mistake in my terminology. I should have said cyclic (I will edit it), because in the Williams construction described on the H. Bruin page, this is the same array of differences from one column to the next. In fact, this property might be considered a disadvantage if there is an interaction between the properties of your operations and this sequence of difference, making this series of experimental tests not "mixed" or "unbiased" enough.
Comment: @hcc23 : I am also interested by your opinion on my sequential solution to your experimental problem.


NSIS Integration with Windows Games Explorer

Question: I'm trying to get the NSIS installer for my game to register the game with the Games Explorer in Vista/Win7.  In all other respects, my installer is working fine - but I've had a difficult time identifying the 'right' way to integrate with the Games explorer.  In my searching, I've found the following resources:

Game Explorer with Helper
Games Plug-in
Game Explorer

I've got the game-side tasks complete (my .EXE has embedded GDF resources), but the installer work is frustrating me. It seems that by now there should be a fairly well-honed approach to this, but none of these feel like 'it.'  Has anybody had experience with this?
Answer: Have you considered using Windows Installer XML (WiX) toolset instead of NSIS?
Starting from version 3 it have pretty handy Gaming Extension. (schema)
Comment: WiX is a better overall solution for sure, but I was too far down the road with NSIS at the time to switch over.
Answer: There are solutions available for NSIS either using the System plug-in or with a dedicated plug-in.


Wordpress pagination: get current page ('paged' query_var) from single page URL/template

Question: I have an issue trying to get the current page from WP pagination. Here is my code:
 global $wp_query;

   $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

   var_dump(get_query_var( 'paged' )); // HERE RETURN 0 EVERYTIME

            $args = [
                'post_type' => 'post',
                'posts_per_page' => 30,
                'paged' => $paged
            ];

            $loop = new WP_Query($args);
             while ($loop->have_posts()) :
                $loop->the_post(); ?>

                    // code ....
            <?php endwhile; ?>

I use this code on a single-page template (and so from a single-page URL). Doing get_query_var( 'paged' ); returns 0.
How to get the current page from a single-page template?
Answer: As per documentation:

For getting the current pagination number on a static front page (Page
template) you have to use the 'page' query variable:

<?php $page = (int)get_query_var( 'page', 1 );  ?>

Currently Browsing Page <?php echo $page; ?> On a static front page