Easiest way to automatically check EC2 disk space and be alerted if it is running low?

Question: Running the Amazon Linux AMI. It seems that CloudWatch does not check for free disk space. I have a number of servers and ideally don't want to have to configure each one with a mail server, script to check disk space etc.
Is there a simpler way to do this?
Answer: Amazon provides scripts for this as of march 2012:
Amazon CloudWatch Monitoring Scripts for Linux:
http://aws.amazon.com/code/8720044071969977
Comment: The scripts look fairly straight forward. The thing that worries me is that it needs a known pair of AWS access key and secret. Does anyone know if it will also look in the EC2 instance role to get a temporary pair or if I'll have to code that myself?
Comment: To answer my own question. Yes! The scripts will use the IAM Role of the EC2 instance (if present.) The catch is that the role you chose must have the necessary CloudWatch permissions.
Answer: There is no way for the EC2 control and monitoring tools to give you this data because the file system of your instances is ONLY accessible by the instance itself. Both the basic architecture of the hardware and the security model demand this limitation. Think about how bad it would be if software outside your computer could poke around at the files on your hard drives!
Here is a low key way to make cron (installed on most systems anyway) check this data for your periodically. Your systems should have the minimum requirements to handle root mail notifications anyway. I recommend having at least a materialistic outgoing mail agent and configuring the root or administrator alias to forward to you on all systems you administer. Many programs including cron expect this configuration.
You could add this to your crontab:
0 0 * * * test $(df / | grep ^/ | awk '{print $4}') -lt 1048576 && echo "Warning: Free disk space is less than 1G on /"

To break that down, this

Creates a job that runes once a day at 00:00.
Cron automatically handles emailing the system administrator with the output of jobs. This job only produces output if there is an error or if the disk space is low
The test command sets up a simple shell comparison using the -lt less than operator and a fixed value equivolent to 1Gb free space.
The df command tests free space on the / file system
The grep gets you just the line of output you need instead of the headers df includes.
The awk get's just the fourth column in the output, the free space number.
The && says to run the next command only if the first one (the test x -lt y) returns true.
Answer: I wrote a script as I needed to check several servers within my EC2 group. It needs a file with a list of each server IP/domain name on a single line.
#! /bin/bash

ADMIN="email@example.com"
ALERT=85

for SERVER in `cat ~/scripts/servers.txt` do
ssh -i ~/.ssh/yourkey.pem $SERVER df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
echo $output
usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1  )
partition=$(echo $output | awk '{ print $2 }' )
if [ $usep -ge $ALERT ]; then
echo "Running out of space \"$partition ($usep%)\" on $SERVER as on $(date)" |
mail -s "Alert: Almost out of disk space $usep" $ADMIN
fi
done done

Comment: The "Amazon CloudWatch Monitoring Scripts for Linux" can push the disk usage into CloudWatch as custom metrics. http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/mon-scripts-perl.html
Comment: @LaurionBurchall please put that as an answer.  IMO that is the correct answer as it gives the ability to use CloudWatch alerts.
Answer: Step by step instructions for setting this up on an EC2 instance with CloudWatch:
http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/mon-scripts.html
Answer: I use this script: http://nixcraft.com/shell-scripting/3238-shell-script-check-disk-space-remote-systems.html
Answer: Cron is your friend.  Put this file into your /etc/cron.daily  directory and it will run once per day:
#!/bin/sh
# this script is /etc/cron.daily/diskAlert.cron
ADMIN="email@example.com"
ALERT=90
df -PkH | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $6 }' | while read output;
do
  usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
  partition=$(echo $output | awk '{print $2}' )
  if [ $usep -ge $ALERT ]; then
    echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" |
    mail -s "Alert: Almost out of disk space $usep%" $ADMIN
  fi
done

NOTE: This script will say that mounted CDROMs are full.
Answer: This is a quick PowerShell script that I wrote that runs on our DC in AWS and shoots out an e-mail to a group of recipients if a drive is full.  It takes a csv with 2 columns - one titled name with a computer name, and one titled drive with a drive letter.  We don't have a mail server in our AWS environment, so I configured it to send through SES.  You can also slightly modify the script to just send a report every so often of the drive utilization if you like.  Just thought that I'd post this here, since all of the solutions that I found were for Linux instances.
$CSVPath = "c:\Scripts\computerNames.csv"
$computerName = new-object System.Data.DataSet
$computerName = Import-CSV $CSVPath
$AwsUn = ""
$AwsPw = ConvertTo-SecureString "" -AsPlainText -Force

$cred = New-Object -typename System.Management.Automation.PSCredential -ArgumentList $AwsUn, $AwsPw

Foreach($name in $computerName)
{

    $dl = $name.drive

    $Utilization = Get-WmiObject win32_Volume -ComputerName $name.computerName -Filter "DriveLetter = '$($dl)'"|   Foreach{ "{0:N2}" -f ((1-$_.FreeSpace / $_.Capacity)*100) }

    if($Utilization -gt 90)
    {
        Send-MailMessage -From Sender to Recipients -subject (
    "$($name.computerName) Disk utilization" )-Body "The $dl drive on the AWS instance $($name.computerName) has $utilization% disk utilization.   Please log in and delete log files or contact the Network Operations team to increase the storage allocated to this instance"  -SmtpServer email-smtp.us-west-2.amazonaws.com -Credential $cred -useSSL -port 25
    }

}


How do I use subtraction and addition intermittently on a vector?

Question: I have to add and subtract every other element in a vector like so:
1 + 2 - 3 + 4 - 5 ...
can I do this within a vector? if so how? if not what is a very basic way I can accomplish this?
Thanks, I'm new to R :)
Honestly I am completely stumped by this.
Answer: You can try
2 * x[1] + sum(x*(-1)^seq_along(x))

Answer: 1) First note that the first two elements are both positive but after that they are alternating so treat 1 separately, extract the even and odd position elements after the first and sum each and then subtract the two sums adding x[1].  Note that this requires that x have length 3 or more.
x <- 1:5

x[1] + sum(x[-1][c(TRUE, FALSE)]) - sum(x[-1][c(FALSE, TRUE)])
## [1] -1

# check
1+2-3+4-5
## [1] -1

2) This can also be written as
sum(x[1], x[-1][c(TRUE, FALSE)], - x[-1][c(FALSE, TRUE)])
## [1] -1

3) This solution works even if the length of x is 0, 1 or 2 as well.  We create the vector c(1, 1, -1, 1, -1, ...) and multiply it by x and sum.
sum(replace(rep(c(-1, 1), length = length(x)), 1, 1) * x)
## [1] -1

Answer: Here is a way. It will recycle the vector c(1, -1) to the length of x. If the length of x is not even, it gives  warning that must be suppressed since that is epected.
x <- 1:5
sum(c(1, -1) * x) |> suppressWarnings()
#> [1] 3

Created on 2024-02-10 with reprex v2.0.2

Edit
ThomasIsCoding found a bug in the above code. Here is his correction.
x <- 1:5
(x[1] + sum(c(1,-1)*x[-1])) |> suppressWarnings()
#> [1] -1

Created on 2024-02-10 with reprex v2.0.2
Comment: maybe you could use `x[1] + sum(c(1,-1),x[-1])` to fix it
Comment: I think it should be `-1`, since the first minus `-` happens to number `3`.
Comment: @ThomasIsCoding You are right, I will edit.


How to use "summarise" from dplyr with dynamic column names?

Question: I am summarizing group means from a table using the summarize function from the dplyr package in R. I would like to do this dynamically, using a column name string stored in another variable.
The following is the "normal" way and it works, of course:
myTibble <- group_by( iris, Species)
summarise( myTibble, avg = mean( Sepal.Length))

# A tibble: 3 x 2
  Species     avg
  <fct>      <dbl>
1 setosa      5.01
2 versicolor  5.94
3 virginica   6.59

However, I would like to do something like this instead:
myTibble <- group_by( iris, Species)
colOfInterest <- "Sepal.Length"
summarise( myTibble, avg = mean( colOfInterest))

I've read the Programming with dplyr page, and I've tried a bunch of combinations of quo, enquo, !!, .dots=(...), etc., but I haven't figured out the right way to do it yet.
I'm also aware of this answer, but, 1) when I use the standard-evaluation function standardise_, R tells me that it's depreciated, and 2) that answer doesn't seem elegant at all. So, is there a good, easy way to do this?
Thank you!
Answer: 1) Use !!sym(...) like this:
colOfInterest <- "Sepal.Length"
iris %>%
  group_by(Species) %>%
  summarize(avg = mean(!!sym(colOfInterest))) %>%
  ungroup

giving:
# A tibble: 3 x 2
  Species      avg
  <fct>      <dbl>
1 setosa      5.01
2 versicolor  5.94
3 virginica   6.59

2) A second approach is:
colOfInterest <- "Sepal.Length"
iris %>%
  group_by(Species) %>%
  summarize(avg = mean(.data[[colOfInterest]])) %>%
  ungroup

Of course this is straight forward in base R:
aggregate(list(avg = iris[[colOfInterest]]), iris["Species"], mean)

Comment: You're a legend. I had no idea about _!!sym(...)_ but this did exactly what I wanted it to.
Answer: Another solution:
iris %>%
  group_by(Species) %>%
  summarise_at(vars("Sepal.Length"), mean) %>%
  ungroup()

# A tibble: 3 x 2
  Species    Sepal.Length
  <fct>             <dbl>
1 setosa             5.01
2 versicolor         5.94
3 virginica          6.59


Which number should I use for In-between group analysis by using Fisher's exact test?

Question: I have to find out if the baseline demographics have statistically significant difference between two groups. The project is about two groups of students, one intervention group and one control group. The goal is to find out if the students in the intervention group that pass the test will be significantly more than that in the control group. I need to perform an in-between group analysis to see if the gender is a factor affecting the result. I would like to know which number should I put in to the 2X2 table test? Which of the following should I use?
                  Intervention group      Control Group
Passing Male:           28                     23
Passing Female:         41                     30

           Intervention group    Control Group
Male     :           30               27
Female   :           42               33

I am wondering if sex is affecting the the passing rate between each group. I guess it is called "between group differences" at baseline? For examples, I want to know if male students are more likely to pass the test, if it is, then it may affect the results as the two groups do not have the same proportion of male to female students in each of the two groups? I want to know if sex is a covariate affecting the passing rate.
Comment: You also need to present either the total group sizes or the number not passing. (Or clarify that the numbers is the second table were the numbers tested. And say why you wouldn't use a chi-squared analysis which could handle the 2x2x2 structure better than a `fisher.test`)
Answer: The Fisher Exact Test is not set up to handle covariates. There are exact tests that do handle covariates, but they require additional packages in R. I would set the data up like this:
> res2
  Pass Tot    Sex Grp
1   28  30   Male Int
2   41  42 Female Int
3   23  27   Male Ctl
4   30  33 Female Ctl

Then run two models (admittedly not using exact tests): one with both Sex and Grp and another with Grp removed. Clearly these two groups are not matched, so McNemar's test is not used either, although it could be argued that the selection methods for grouping were not described very well, if at all. Clearly there is nothing approaching a significant difference using logistic regression:
glm( cbind(Pass, Tot-Pass) ~ Sex + Grp, data=res2, family="binomial")
#-----------
Call:  glm(formula = cbind(Pass, Tot - Pass) ~ Sex + Grp, family = "binomial",
    data = res2)

Coefficients:
(Intercept)      SexMale       GrpInt
     2.3946      -0.7147       1.0965

Degrees of Freedom: 3 Total (i.e. Null);  1 Residual
Null Deviance:      3.922
Residual Deviance: 0.1249   AIC: 16.65
#----------------

glm( cbind(Pass, Tot-Pass) ~ Sex , data=res2, family="binomial")
#------------
Call:  glm(formula = cbind(Pass, Tot - Pass) ~ Sex, family = "binomial",
    data = res2)

Coefficients:
(Intercept)      SexMale
     2.8764      -0.7363

Degrees of Freedom: 3 Total (i.e. Null);  2 Residual
Null Deviance:      3.922
Residual Deviance: 2.688    AIC: 17.21
#------

Looking at the actual numbers you can see why random variation could easily explain differences of just a few students one or two groups. Comparing the deviance of two models, which is what I am implicitly doing, is a likelihood ratio test. The difference between that approach and an exact test would be expected to be very slight when the cell sizes all exceed 5. Furthermore the calculation of an exact test with this set of values would be prohibitive. I seem to remember that the R fisher.test may allow a more relaxed accommodation of data than just 2x2, but when the cell counts are this large the function would default to approximate methods anyway.
Comment: Using the `cbind` function with `glm` logistic regression , the values should be successes and failures, not successes and total.
Comment: Thanks. I was reading the `?glm` material incorrectly. Better to look at `?esoph`. Code and output revised accordingly.


Create custom links for private message in OG group

Question: I am using the module private messages to let users send messages to groups and other users. I would like to create a link where the recipient info is automatically filled with the Group title on the new message page.
Did any one try to work with private messaging groups and create the autocomplete links  ?
Answer: There is a module for private message in group but it is sandbox module and for Drupal 6 only. You can customize it for Drupal 7
Just check this Sandbox
And refer this discussion also, it has nice roadmap regarding implementation of entire module. http://drupal.org/node/612664


Add mermaid syntax into monaco-editor in ReactJS

Question: I try to add mermaid syntax into monaco-editor via Monaco-mermaid, It it's return an error:
enter image description here
This is my code:
import React, { useEffect, useRef } from "react";

import * as monaco from 'monaco-editor';

import initEditor from 'monaco-mermaid';

import './style.css';

const Editor = (props) => {

    const { className, handleChangeCode, handleDownload } = props;
    // comment

    const editorRef = useRef(null);

    useEffect(() => {
        const editorContainer = document.getElementById('monaco-mermaid');
        const monacoEditor = monaco.editor.create(editorContainer, {
            language: 'mermaid',
            minimap: {
                enabled: false
            },
            fontWeight: '600',
            fontSize: '14px',
            overviewRulerLanes: 0,
            quickSuggestions: false,
        });
        initEditor(monacoEditor);
    },[])

    return (

Code

            <div className={`editor-bottom`}>

 handleDownload('svg')}>
                    Save as SVG

 handleDownload('png')}>
                    Save as PNG

 handleDownload('clipboard')}>
                    Copy to clipboard

    );
};

export default Editor;

My monaco-editor version is: 0.34.0, monaco-mermaid: 1.0.8. Please help me !!!
Answer: According to the type of the first parameter of the initEditor function in the Monaco-Mermaid package on GitHub at this link, you need to pass Monaco type to this function.
Your corrected code is as follows.
import * as monaco from 'monaco-editor';
initEditor(monaco);

Comment: It's work !!!! Thanks.


How do guitarists switch on/off multiple effects via pedalboards?

Question: An example would be a guitarists on stage with various sounds for his setlist, and he has around 10 pedals.
For solo, he needs to turn on boost, change the channel, a bit of reverb, turn off chorus that was intended the clean channel, and use the wah afterwards.
How is this done without fuss? Do people really have to stomp on their pedals that much?
So far I've only used a footswitch and an equalizer, so I never used any pedals before.
Answer: There are various solutions to this:
Just doing it
.. by which I mean, just tapping the switches and turning the knobs that get you to the setting you need. With practice, you can get quite speedy at this, but at the same time there are practical limitations on what can be achieved.
If this is the only route available to you, you need to plan your pieces so that you don't have unachievable effects changes in a song. Either have changes you can achieve in 1-3 taps, or find space in the arrangement where you can stop playing and attend to your pedals.
Multi-FX Units
Units with multiple effects integrated into one unit. These have programmable patches, selectable by footswitch, that will set all the parameters at once.
MIDI control
Some pedals and rack FX units, can be controlled by MIDI. There are also small businesses that modify non-MIDI pedals to be MIDI controllable. So you can have banks of settings configured in some software, and use a MIDI footswitch to move between them.
Switch between FX chains
Let's say you want to switch immediately from a dirty riffing sound, to a clean reverb-y solo sound.  Set up both of those sounds, each using a completely different set of pedals. They could even each go to separate amps, if you like. Connect the guitar to both of these chains through an A/B switch pedal.
Now, at the tap of a footswitch, you can switch from one set of pedals to another.
Obviously this can mean having to own more pedals.
Programmable FX loop systems
This is effectively the solution above, on steroids. Systems such as GigRig route signals through a number of pedals, programmably.
An assistant
Have someone off-stage (or even on-stage) assist with the FX changes, usually in conjunction with the other techniques. This is what big acts often do. When ZZ Top launch into a solo, Billy Gibbons doesn't step on a stomp-box. An assistant off-stage knows the cue, and switches the effects route at the right moment.
Comment: FX loop is my way to go.
Comment: Can also add that for MIDI/Programmable FX Loop systems, the changes can also be made automatically. I.e., somebody runs a MIDI track for the song (which might also have backing tracks or other things, like light cues etc) with preprogrammed MIDI control messages that switches effects, signal routing and amp settings automatically between songs/sections of songs.
Answer: Ivan Ivkovik' answer (a programmable patch) is certainly a way of doing this withouht fuss, but the programmable stuff is relatively modern (considering how long electric guitars have been around) and it wasn't always the case.
I use a row of 6 individual effects units - there's no patch list or programmable setup, they're all autonomous. The reason I use these is firstly I've settled on a few whcih I really like the sound of, and I like that you change the sound by twiddling a knob, rather than programming using data tap wheels etc.
I use .. in this order (guitar in at top) :

Phaser
Compression (light for clean sound)
Distortion (crunch for rhythm sound)
Delay
Chorus
Compression (used as boost for solos)

They all sit in a line.
Common sound changes I use are :
Clean to distorted & back = easy just hit the distortion box
Clean to distorted with delay = hit distortion at right time and then hit the delay.
Probably the trickiest one is a song where I have to switch after a hard rock chorus:
distortion off (to clean) , switch on mild compression, phaser and delay.
The way I've gone about this is to "prioritise" & work out which of the effects needs to change "on time" - ie which has the most impact, and do that first. Normally this is the distortion or boost (for solos).
Do that one first, and th sound has either quietened or raised as appropriate, in time with the song so the impact is heard. Other swooshy effects like chorus or phaser, or delay generally aren't missed for the quarter second it takes to get my foot to the right pedals.
Another trick is to hit two at once -  eg I often switch from distortion to mild compression. the two pedals are next to each other so if I just fat-foot them both, one goes off and the other goes on.
So the answer is yes. . there is a bit of "tap dancing" on the pedal board, but the reality is you rarely want to go from all-on to all-off, and if you prioritise them you can get the impact you want and add the finer stuff as quick as you can afterwards, without any detriment to the overall sound.
Comment: Just a thought. Some effects are more effective connected between the pre- and the post- of an amp (send/return). Rather than all in series. You may find your sound is even better with this extra wiring in place
Comment: I agree! except my amp is oooold (1968-1970 Marshall I think) and doesn't have a send/return loop
Answer: This is solved by using programmable effects loop devices - you can setup custom presets (amount of presets depend upon the product) that run the desired pedals through the effects loop.
An example: preset 1 runs the signal to and back from the chorus pedal (clean channel), preset 2 runs a chorus and a boost pedal (clean solo) and so on.
Comment: Don't confuse "looper" a device that allows you to record and overdub short segments of sound, with and effects loop switcher.
Comment: GigRig is one of the elaborate systems. (My pedals are few, but my amp offers 3 distinct channels plus fx loop, reverb, and more all built-in and foot switchable.)
Answer: A newer solution
BOSS - ES-8 | Effects Switching System
https://www.boss.info/global/products/es-8/ (or the smaller https://www.boss.info/global/products/es-5/)
This type of device connects each external pedal you have to an independent effects send loop. Effects chains can then be created virtually within the effects controller, allowing you to arrange pedals in any order and save that configuration as a preset.
Presets can also be setup to send MIDI commands to pedals that support that, to change the pedal's own preset when you change the main preset.


Line Integral of real linear function

Question: Let $L: \mathbb C \rightarrow \mathbb C $ be a real linear function and $\gamma $ a closed $C^1$ curve in $\mathbb C$.
Then $\int_\gamma L(z) dz = 0 \Leftrightarrow \quad $L is complex linear
Why is that so? I cant find to find a reasonable solution.
Answer: Viewing $L$ as a real operator, if we choose a basis for $\mathbb{C}$, say $\{1,i\}$, we may write it as a 2x2 matrix:
$$L(x+iy)=\begin{pmatrix}a & b\\c &d\end{pmatrix}\begin{pmatrix}x \\ y\end{pmatrix}=(ax+by)+i(cx+dy)$$
Then $L$ is $\mathbb{C}$-linear if $L(i)=iL(1)$ which amounts to $b+di=ia-c$ so $a=d$ and $b=-c.$
We may also view $L$ as a function of $z=x+iy$ and $\bar z=x-iy$. After this change of variables we have
$$L(z,\bar z)= \frac{z}{2}((a+d) + i(c-b))+\frac{\bar z}{2}((a-d)+i(b+c))$$
Thus the line integral becomes
$$\oint L(z,\bar z)\,dz = \frac{1}{2}((a+d) + i(c-b))\oint z\,dz+\frac{1}{2}((a-d)+i(b+c))\oint\bar z\,dz$$
But $\oint z\,dz=0$ by Cauchy residue. And $\oint \bar z\,dz=\int_0^{2\pi}e^{-i\theta}ie^{i\theta}\,d\theta=2\pi i$. So the integral vanishes only if $a=d$ and $b=-c$.
Or more succinctly if you know the relevant theorems, the contour integral vanishes iff the function is holomorphic iff the antiholomorphic part vanishes and for linear maps homolorphicity is equivalent to $\mathbb{C}$-linearity.

Line Integral of real linear function


Existence of Lebesgue measure on real line proof help

Question: I am reading a proof of the existence of Lebesgue measure and am struggling to understand one part. I will first get you up to where I am in the proof.
We define for a set written as a finite disjoint union $A=(a_1,b_1] \cup \cdots \cup (a_n,b_n]$ the set function $\mu(A)=\sum\limits_{k=1}^n (b_k-a_k)$.
Sets of the form of $A$ above form a ring $\mathcal{A}$ and generate the Borel sigma algebra. In order to apply Caratheodory extension theorem, we must show that $\mu$ is countably additive on $\mathcal{A}$. This is equivalent to showing (from an exercise done previously) that if $(A_n)$ is a decreasing sequence of sets in $\mathcal{A}$ with $\bigcap\limits_n A_n=\emptyset$, then $\mu(A_n)\rightarrow 0$ as $n\rightarrow \infty$.
Suppose for contradiction that this fails. Then there exists $\epsilon>0$ such that $\mu(A_n)\geq 2\epsilon$ for all $n=1,2,\ldots$.
THIS IS THE BIT I AM STUCK ON....
But then we can find, for each $n$, a set $B_n\in\mathcal{A}$ such that $\overline{B_n}\subset A_n$ and $\mu(A_n\setminus B_n)\leq \epsilon2^{-n}$.
If somebody could explain the last line or reword it, I will be extremely grateful.
(PS this isn't set work. I am doing it in my holidays as a bit of fun ;))
Thank you in advance!
B.
Answer: Each $A_n$ is a finite union of some number, say $q$, of half-open intervals of the form $(a,b]$.  Shrink each of these just a little from the left end; I'll decide later how much to shrink it but for now I'll just call the shrinkage amount $\delta$.  So you're now looking at shrunk intervals $(a+\delta,b]$ in place of $(a,b]$.  Do this for each of the $q$ intervals $(a,b]$ that constitute $A_n$, and call the union of the shrunk intervals $B_n$.  So $B_n\in\mathcal A$, and the closure of $B_n$ is the union of closed intervals $[a+\delta,b]$.  In particular, the closure of $B_n$ is included in $A_n$.
All that we still need, for the statement you asked about, is that $\mu(A_n-B_n)$ is really small, $<\epsilon2^{-n}$.  Well, how small is it? That is, how much of $A_n$ was lost in the shrinking process? Each of the $q$ intervals that formed $A_n$ lost $\delta$, so altogether, the loss was $q\delta$.  We need that to be $<\epsilon2^{-n}$. We have no control over $\epsilon$, $n$, and $q$; they're given to us.  But we can make $\delta$ as small as we need.  So take $\delta<\epsilon2^{-n}/q$.


"Col is undefined" quando uso table.rows.add

Question: Estou tentando pegar um json de uma requisição AJAX para inseri-lo na tabela porém sempre que executo o table.rows.add
Código da Tabela:

           Id
           Uniforme
           Modelo
           Tamanho
           Cor
           Fornecedor
           Contrato
           Quantidade
           Custo
           Localização
           Actions

           aaaa
           aaaa
           aaaa
           aaaa
           aaaa
           aaaa
           aaaa
           aaaa
           aaaa
           aaaa

               favorite
               dvr
               close

         Id
         Uniforme
         Modelo
         Tamanho
         Cor
         Fornecedor
         Contrato
         Quantidade
         Custo
         Localização
         Actions

Jquery:
 $('#datatables').DataTable({
        "pagingType": "full_numbers",
        "lengthMenu": [
            [10, 25, 50, -1],
            [10, 25, 50, "All"]
        ],
        responsive: true,
        language: {
            search: "_INPUT_",
            searchPlaceholder: "Search records",
        },
        columns: [
           { data: 'Id' },
           { data: 'Uniforme' },
           { data: 'Modelo' },
           { data: 'Tamanho' },
           { data: 'Cor' },
           { data: 'Fornecedor' },
           { data: 'Contrato' },
           { data: 'Quantidade' },
           { data: 'Custo' },
           { data: 'Localização' }
         ]

    });

    $.get("http://localhost/infinity/assets/php/list-uniforms.php", function(data){
        uniforms  = JSON.parse(data);
        console.log(uniforms);

        table.rows.add(uniforms).draw();

    });

Resultado:
Answer: Isso acontece quando você tenta passar quantidade diferente de colunas em columns: do que realmente existe na tabela.
Para corrigir este problema, simplesmente inclua a última coluna "Actions" em columns::
columns: [
  { data: 'Id' },
  { data: 'Uniforme' },
  { data: 'Modelo' },
  { data: 'Tamanho' },
  { data: 'Cor' },
  { data: 'Fornecedor' },
  { data: 'Contrato' },
  { data: 'Quantidade' },
  { data: 'Custo' },
  { data: 'Localização' }, // <-- não esqueça a vírgula aqui
  { data: 'Actions' } // <-- faltou esse aqui
]

Comment: Agora deu esse erro: "DataTables warning: table id=datatables - Requested unknown parameter 'Id' for row 1, column 0. For more information about this error, please see http://datatables.net/tn/4"
Comment: Eu não tinha adicionado o actions porque ele não faz parte do Json, usaria ele apenas para colocar os botões de ação
Comment: @LuhanSalimena Saquei. Vou ver aqui...
Comment: {add_date: "2018-01-24 17:12:48",
amount: "50",
cost: "20",
id: "1",
model: "Manga Comprida",
place: "NIT",
provider_id: "1",
size: "PP",
uniform_type: "Blusa Social",
userid: "fdsfsfs1f",
Comment: Coloquei porém continua o mesmo erro
Comment: @LuhanSalimena Tenta assim: `$('#datatables').DataTable().rows.add(uniforms).draw();`
Comment: @LuhanSalimena Se vc já definiu o "table" antes, não vai adiantar a dica acima ;/... deixa o "table" mesmo... Para arrumar isso, os itens do JSON devem ter o mesmo nome das colunas: "Id", "Uniforme"...
Comment: @LuhanSalimena Tipo: `{"Id": "1", "Uniforme": "Manga Comprida",...}`
Comment: Vou modificar aqui
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/72190/discussion-between-dvd-and-luhan-salimena).
Comment: As colunas estão entrando corretamente, porém sempre é alertado esse erro : DataTables warning: table id=datatables - Requested unknown parameter '10' for row 1, column 10. For more information about this error, please see http://datatables.net/tn/4


How can I disable "Delete the account and its content"?

Question: On the Cancel account page, is it possible to disable the option "Delete the account and its content"?
Some roles have the permission to cancel user accounts, but they should not have the option to delete the user's content.
Comment: use hook_form_alter to remove the option.
Comment: how to remove the link cancel account on the user form ?
Answer: You can implement hook_form_alter() in a custom module or theme to either remove the radio button entirely, or disable it which grays it out. You'd need to add additional logic to check the role of the user and disable it appropriately. I've shown both examples in the code example below, just uncomment the one you want to use.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'user-multiple-cancel-confirm') {
    // Set '#access' to FALSE to remove the radio button.
    // $form['user_cancel_method']['user_cancel_delete']['#access'] = FALSE;

    // Set '#disabled' to TRUE to disable the radio button.
    // $form['user_cancel_method']['user_cancel_delete']['#disabled'] = TRUE;
  }
}

Answer: There are two routes to deleting a user in the admin UI. Vincent's example handles deleting a user from the People list. The following code also handles clicking the 'Cancel account' button on the user's profile edit form:
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  /* Debug...
    file_put_contents(
      $_SERVER["DOCUMENT_ROOT"]."/sites/default/files/debug.log",
      "mymodule_form_alter()...form_id: ".$form_id."\nform: [\n".print_r($form, TRUE)."]\n\n-----------------------\n\n",
      FILE_APPEND
    );
  */

  switch ($form_id) {

    case 'user_cancel_confirm_form':
    case 'user_multiple_cancel_confirm':
    //
    // Only full Administrator accounts can delete user *and* their content...
    // Disable the cancel account options, apart from 'Delete the account and make its content belong to the Anonymous user.'
    //
    if (!user_access('administer modules'))  {
        //
        // Set '#disabled' to TRUE to disable the radio button.  (Still need to change the default value - see below)
        $form['user_cancel_method']['user_cancel_block']['#disabled'] = TRUE;
        $form['user_cancel_method']['user_cancel_block_unpublish']['#disabled'] = TRUE;
        $form['user_cancel_method']['user_cancel_delete']['#disabled'] = TRUE;

        // Set '#access' to FALSE to remove the radio button.  (Still need to change the default value - see below)
//        $form['user_cancel_method']['user_cancel_block']['#access'] = FALSE;
//        $form['user_cancel_method']['user_cancel_block_unpublish']['#access'] = FALSE;
//        $form['user_cancel_method']['user_cancel_delete']['#access'] = FALSE;
    }
    // For everyone, change the default radio button...
    $form['user_cancel_method']['user_cancel_block']['#default_value'] = 'user_cancel_reassign';
    $form['user_cancel_method']['user_cancel_block_unpublish']['#default_value'] = 'user_cancel_reassign';
    $form['user_cancel_method']['user_cancel_delete']['#default_value'] = 'user_cancel_reassign';
    $form['user_cancel_method']['user_cancel_reassign']['#default_value'] = 'user_cancel_reassign';
    break;

  }
}

Thanks again Vincent and hope this helps someone.


Dark-sounding 1986 Les Paul Custom - modern upgrade? or embrace yacht rock?

Question: I'm lefty, and good lefty guitars used to be very rare. I bought the first lefty Les Paul I ever laid eyes on: a used black 1986 les paul custom. I gigged/toured in three different bands with it. It's seen a lot of use. I realized it sounded quite dark some years back and had the soap bar covers removed from the stock pickups. Sadly, the bridge pickup subsequently became damaged when the small string got hooked under the edge of the pickup a few too many times and eventually broke through the coil. I replaced it with a dimarzio super distortion dp100, which I hoped would give it a brighter, crunchier sound.
I later acquired a used 91 Les Paul Standard, which sounds a LOT brighter. It has become my preferred guitar. When I say brighter I mean without even plugging it in. Just press your ear against it and play a few notes and the wood of the 91 Standard is much richer and brighter than the 86 Custom. I don't know what wood is used in either guitar and would appreciate it if someone could help me figure that out. I've seen conflicting posts all over the internet about which wood Gibson used when for which Les Pauls and would much prefer to take a look inside the guitar to know for sure, rather than relying on common wisdom or hearsay. I'd be willing to bet that my two LPs are constructed differently and that the 86 custom is all mahogany and the 91 standard has maple in it.
Plug them in and the difference is even more noticeable. The 86 Custom just sounds abysmally dark and dull compared to the 91 Standard (which has Seymour Duncan SH-1 pickups). The neck pickup on the 86 Custom sounds OK with suitable settings (sorta like the Peter Green), but the bridge pickup--the one I use almost exclusively in my playing--is very disappointing. The result is that I never play the 86 Custom.
So I'm wondering if I should try and modernize the 86 Custom to get a crunchier, more modern sound out of it or if that's a fool's errand. Perhaps I'd be better off staying as vintage as possible with it to try and preserve resale value? I still have the stock Gibson HBR/HBL pickups from 91 Standard and the 86 Custom still has the stock neck pickup, but the 86 Custom has seen a lot of use. The finish is dinged, it needs at least one replacement tuning head, I replaced the original strap buttons with Schaller S-Locks, and I removed the pickguard, which is long gone. It still has the original case -- the big square monstrosity, but one of the buckles is gone. It might not have a lot of resale value, and its value to me is largely sentimental.
I would mention that I'm really hoping for a bright, crunchy sound good for chugs and tasty prog metal chords, bristling with rich harmonics. I'd be more than happy with a sound like Matt Pike gets for Sleep/High On Fire. Can this guitar achieve a modern sound? I've seen folks recommending a rewire kit and this video seems to offer a pretty good idea of what I might expect. This adjustment seems significant to me, and I might go further by installing some bright, modern pickup like a Seymour Duncan Nazgul or Pegasus or something. Or maybe a Dimarzio X2N? Is this drastic and ill-advised? Or a good way to draw out more character from the dark wood of the guitar?
Comment: I wonder why everyone is focusing on pickups when the question says the acoustic tone is different. Anyway, I had the exact same problem with an Epiphone and replacing the bridge fixed it. If it doesn't work, you can drop in the original bridge and keep the thing original spec.
Comment: So many possible factors and subquestions here it's hard to get a grip on this. Almost anything could be contributing to the sound of an electric guitar. Definitely pickups are high on the list, with any or all of the capacitors and the tone pot values also being part of it. Of course the wood has an impact and it might be that no amount of electronics changes will get you the sound you want. It's hard for us to tell you what to expect when there's too many variables. Easiest route is to sell it and buy a guitar that sounds how you want.
Comment: @YourUncleBob Never! Although I must say, [this guy](https://www.youtube.com/watch?v=2t0gl_RuMvw) is making the best of his 86 LPC.
Comment: It's pretty certain your custom has a maple cap. Maple alone won't make a dark guitar bright and all the Gibson literature says 86 customs have maple caps.
Comment: Embrace yacht rock.
Comment: @ToddWilcox you've pretty much hit the nail on the head there, now that I've thought about it. It's hard to know if the guitar can achieve a gnarly, crunchy sound without actually trying something. Every guitar is its own beast. I was sort of hoping that some electric luthier extraordinaire might chime in with some anecdotal thoughts about les paul wood patterns or something.
Comment: @ToddWilcox Any official gibson literature you could point me to? Or perhaps there's some way to open up the guitar and find out first-hand? I'm extremely skeptical that there's maple in it.
Comment: @ToddWilcox Actually, scientific analysis points to the wood making no perceptible difference. There are lots of factors that have more impact. You won't be able to change the overall construction of the guitar (glued-in neck and the like), but different electronics are a good starting point. A different bridge might help as well.
Comment: I posted this below, but think its better here. Get some advice from a luthier. but you might find there is a different value of capacitor you can use in the tone circuit. This would cost pennies to try. start here guitar.com/guides/essential-guide/vintage-les-paul-tone-guide, but there is a lot of advice on Google
Comment: @ToddWilcox turns out you were correct about the maple cap, sir. I eat my words. I pulled out one of the pickups and you can see both the darker mahogany down inside and also the lighter-colored maple cap on top.
Answer: Your guitar can definitely get that modern sound. A lot of the tone is the pickups, with the other major parts being the amplifier and cabinet. The guitar design and woods, while having an influence on the tone, are probably the smallest part of the equation. I'd suggest trying out some passive pickups that players you like are using. It sounds like the Nazgul / Pegasus or Sentient combo would be a good choice for you.
Fortunately swapping pickups is fairly easy if you know the basics of soldering, and you can always resell them if you don't like them.
Comment: get some advice from a luthier. but you might find there is a different value of capacitor you can use in the tone circuit. This would cost pennies to try. start here https://guitar.com/guides/essential-guide/vintage-les-paul-tone-guide/, but there is a lot of advice on Google
Comment: Changing pickups is apparently not enough. As I noted in my original post, I did put in a [Dimarzio Super Distortion DP-100](https://www.dimarzio.com/pickups/high-power/super-distortion). This didn't really change anything. I think I'll need to change out the pots with some kind of [pre-wired kit](https://store.rsguitarworks.net/collections/pre-wired-modernupgrade-kits/products/pre-wired-modern-electronics-upgrade-kit-long-shaft), but am truly wondering which modern shred pickup might match the wood profile.
Comment: @bigbadmouse I really appreciate that link you sent. However, I'm not looking for a vintage sound at all. On the contrary, I have a 33-year-old guitar and want a more modern sound. Also, the issue is the pots more than the capacitors. Sadly, I opened it up and the pots are firmly attached (soldered?) to a metal plate. Seems like it'd be tricky to try and swap out one pot.
Comment: @S.Imp Pots don't make that much difference except in clarity. I wasnt trying to push you to a vintage sound, just trying to suggest that a simple change of capacitor  can give you a changed sound without the expense and hassle of pickup swapping. If you look on google there are a lot of pages where they indicate what kind of sound a given value of capacitor might give you.


Criar um nome para uma variável com o php

Question: Bom estou com uma questão onde o próprio php tem que criar o nome da variável, já usei esse recursos várias vezes. O problema que agora estou tentando usar isso em um array, da seguinte forma:
// Cria o nome da variável
$tabela = "tabela1";

// Cria o array
$$tabela[1] = array(
    "valor" => $valor
);

Bom o código tinha que criar uma variável com o nome $tabela1 e colocar o array nela, porém ele esta me retornando esse erro:
Notice: Uninitialized string offset: 3 in teste.php on line 3

Alguém sabe o que pode ser?
Comment: este é um array multi dimensional? Acredito que o que está errado é $$tabela[] = array..., deveria ser $$tabela = array...
Comment: Na verdade uso o `[]` para fazer a ligação dos dados. Editei a pergunta.
Comment: Queres que `$tabela` seja um array é isso? e na posição 1 que valor queres que tenha?
Comment: Não quero criar uma variável com o nome `tabela1` e depois colocar um array nela.
Comment: Porque não usar somente `$tabela1` assim: https://ideone.com/VIQsRv ?
Comment: Então tenho um `for` onde tenho que criar alguns arrays, e fica mais fácil o próprio código criar os nomes.
Answer: O problema estava ocorrendo no $$tabela[1], neste ponto, o PHP tenta definir o índice de um array que não existe ainda, você precisa colocar em volta da variável chaves para o PHP entender que primeiro ele precisa criar a variável e depois definir o índice dela. O correto ficaria da seguinte forma:
<?php

// Cria o nome da variável
$tabela = "tabela1";

$valor = "Qualquer coisa";

// Cria o array
${$tabela}[1] = array(
    "valor" => $valor
);

?>

Comment: Deu certo aqui, muito obrigado.
Answer: Primeiro você cria o array depois você atribui os valores.
// Cria o nome da variável
$tabela = "tabela1";

// Cria o array
$$tabela = array();

// Atribui os valores
$$tabela[1] = array(
    "valor" => $valor
);

Comment: Dessa forma não funcionou no meu código, mas a forma do @Bruno Rigolon deu certo.
Comment: Eu testei aqui com PHP 7 e funcionou de boa, mas a resposta do @Bruno Rigolon é mais correta de se fazer. ;)


How to use np.where to display the index position + N where a condidtion is met

Question: I have a data frame where I am trying to create a new column when only a specific condition is met.
For example I have this line of code that I want to change to display a different output.
data['new_filtered'] = np.where(((data.movie == data.genre) & (data.length > movie_average)),1,0)

Instead of the return to be 1 and 0 for True and False, I want it to display data.movie but + 5 index positions.
For Example, if this condition is met at row 5 I want the return to be the movie at row 10.
I have done this in the past with just a for loop and appending that return value to a list and added that to the dataframe. I am just curious to see if this is possible with np.where().
Comment: please, send us some reproducible dataset.
Answer: Try something like:
mask = ((data.movie == data.genre) & (data.length > movie_average))
data['new_filtered'] = np.where(mask, data.movie.shift(-5), 0)
#                                     ^^^^^^^^^^^^^^^^^^^^

Comment: Thank you so much.  I didn't know that you can create a mask. It makes it look much cleaner. I also didn't know about using a negative number in the shift but it makes sense!


how to apply multi threading to a method

Question: I have a program that get user int input "1" and increment it based on the amount of files in a directory then stamp that int on each file( first is 1 and so on 1++). The foreach loop go in each directory gets its files, increment the input and call the stamp method until all files are done. In this process the order is important. However multitasking ( Parallel.ForEach) does't always guarantee order, in my understanding it returns which ever thread done first and maybe also damage the i++ functionality ( correct me if I'm wrong).
The question is how to apply multi threading in this case? i am thinking save the values of the foreach at the end, pass it to the stamping method and have the method stamp x amount of files at a time. I don't know if its possible or how to apply.
Here is my watermark method:
//text comes from the foreach already set.
  public void waterMark(string text, string sourcePath, string destinationPathh)
        {
            using (Bitmap bitmap = new Bitmap(sourcePath))
            {
                //somecode
                using (Graphics graphics = Graphics.FromImage(tempBitmap))
                {
                   //somecode
                   tempBitmap.Save(destinationPathh, ImageFormat.Tiff);
                  //Erroe^: a generic error occurred in gdi+
                 //I think due to trying to save multiple files at once
                }
            }
        }

The foreach loop:
var files = folder.GetFiles();
 Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = 4 }, (file, state,indexer) =>
                {
//somecode that calls the waterMark method in multiple spots as of now
});

Thank you in advance.
Comment: See also: [Read and process files in parallel C#](https://stackoverflow.com/questions/20928705/read-and-process-files-in-parallel-c-sharp). There is [Parallel.For Method](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.parallel.for?view=netframework-4.8) method giving you an index.
Answer: There is an overload of Parallel.ForEach that also provides an index for the item being processed:
Parallel.ForEach(someEnumerable, (val, state, idx) => Console.WriteLine(idx))

You can use it to keep track of the index in a thread-safe fashion.
As for the GDI+ stuff (Bitmap), I think you're safe as long as you use a single thread for all interactions with the bitmap. Don't try to do anything clever with async between instantiation and disposal.
Comment: @CountLessQ No... I'm not going to provide support through your development process. You've encountered a clear error message. Time to write a more focused question concerning that error message. Chameleon questions are generally of little use to subsequent readers.
Comment: @CountLessQ Feel free to ping me when you've written the question... I don't know how useful I'll be though. I never had much luck using GDI+ for bulk image operations.
Comment: I think same issue/question still apply. It is the usage of multi threading while manipulating the files as mentioned, thank you for your help.


Month field on EXTJS 5.1: cannot select march, october or december if Ext.Date.monthNames is redefined

Question: After having found this site and this post I made this fiddle. If Ext.Date.monthNames is defined (for german translation) it is not possible to select march, october or december... The actual month is selected instead (may for example today). If it is not defined, it is possible to select those months... Amazing...
Does someone have any suggestion?
(tested on Chromium 50.0... 64bit)
Comment: It appears that the problem is solved with the latest version of ExtJS (6.0.2)... But I use version 5.1 GPL and 6.0.2 has no GPL release
Comment: I have tried to reproduce in your fiddle (ExtJS 5.1.0), and managed to select März 2016. I just had to doubleclick "Mär" and "März 2016" was written in the box. Not sure what the problem is.
Answer: I know the solution to this problem. You are not overriding the monthNumbers property of Ext.Date object. So in order to change the months name to German months names do this:
Ext.Date.monthNames = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];

Ext.Date.monthNumbers = {Januar: 0, Jan: 0, Februar: 1, Feb: 1, März: 2, Mär: 2, April: 3, Apr: 3, Mai: 4, Mai: 4 , Juni: 5, Jun: 5, Juli: 6, Jul: 6, August: 7, Aug: 7, September: 8, Sep: 8, Oktober: 9, Okt: 9, November: 10, Nov: 10, Dezember: 11, Dez: 11};

And that's it, your fiddle will be working as intended(I have tested it).
This sencha forum link could be useful.
Answer: There is nothing need to add month name the default name already here
sencha doc


How do you make nodes automatically publish one by one after specific time?

Question: I'm going to do a comic site. I saw the MemeCenter. It automatically publish comics after 10 minutes. Is there a module to do this on Drupal?
Answer: You can use Rules module with rules scheduler, check this tutorial for better understanding on how to configure.
and also take a look at Scheduler module


Android - "Method Call Expected" error when trying to build a singleton SQLiteOpenHelper

Question: New programmer here trying to self-learn, apologies for any stupid questions.
I'm trying to build a SQLite database with a singleton pattern in Android, so I can access the same DB through many different activities. I have the code below, but in the dbInstance = DatabaseHelper(context.getApplicationContext()); line, they have flagged an error "Method call expected".
I've searched google and this site, but it seems like this error can be triggered for a variety of reasons, and I wasn't able to figure out what's wrong in my case.
private static class DatabaseHelper extends SQLiteOpenHelper{

    private static DatabaseHelper dbInstance = null;

    private DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public static DatabaseHelper getInstance(Context context) {
        synchronized(DatabaseHelper.class) {
            if(dbInstance == null) {
                dbInstance = DatabaseHelper(context.getApplicationContext());
            }
        }

        return dbInstance;
    }

Appreciate all of your help in advance!
Comment: Thank you Mike M. Apologies for overlooking that one
Answer: Should be
dbInstance = new DatabaseHelper(context.getApplicationContext());

Comment: Thank you Michel_T. Super helpful


Send mails in an asynchronous process

Question: I'm using drupal_mail() to send mails from the HTML formatted content.
It takes more time to send mails. Actually, Mail is triggered while the form submission after the save logic.
To save the page loading time, how can I send emails in an asynchronous process?
Answer: As far as a pre-built solution goes, you can try the Background process module, which would theoretically allow you to do something like:
$handle = background_process_start('drupal_mail', $module, $key, $to, ...);

Beyond that Drupal has nothing to help, so If you don't use that module, just approach this as a general PHP task. The options and difficulties for async/background processing in PHP are very well documented around the web.

Send mails in an asynchronous process


Unable to locate main class

Question: Since my command prompt messages are in portuguese, I do not know the exact words, but when I try to execute java -cp . My file, it says that it was unable to locate or execute the main class. I´ve searched, but since I am new to programming at all, so far I know that it may be a problem with Classpath. This is what I have:
A ShooterGame.class file already compiled properly with javac -cp . FILE. But when I do java -cp . CLASS, it shows that message.
How can I fix this? Thanks.
Edit:
Yes, there is a ShooterGame.class in the directory. More specifically, there is a folder called game. Inside this folder you find the class I just mentioned. There are 4 entire classes I could post here. Comment if you need any of them(although I think the problem is in this class we are talking about).
ShooterGame.java (it has no package)
import java.awt.*;
import java.awt.event.*;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.*;
import java.net.URL;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.awt.event.MouseEvent;
import game.input.InputHandler;
import game.player.Player;
import game.scenario.Block;

public class ShooterGame extends JFrame{
static int playerX=500;
static int playerY=520;

InputHandler input = new InputHandler(this);
public static Player player = new Player(playerX,playerY,50,50);
Block meteor = new Block(100,100,30,30);

public static void main(String[] args){
    ShooterGame game = new ShooterGame();
    game.run();
    System.exit(0);
}

static int windowWidth = 1300;
static int windowHeight = 600;
static int fps = 30;
static BufferedImage backBuffer = new BufferedImage(windowWidth, windowHeight, BufferedImage.TYPE_INT_RGB);

public void run(){
    boolean running = true;

    initialize();

    while(running){
        long time = System.currentTimeMillis();

        update();
        draw();

        time = (1000 / fps) - (System.currentTimeMillis() - time);

        if (time > 0) {
            try{
                Thread.sleep(time);
            }
                catch(Exception e){};
        };
    }

}

public void initialize(){
    setTitle("--- Shooter Game ---");
    setSize(windowWidth, windowHeight);
    setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}

public void update(){
    player.update(input);
    meteor.update(0);
}

public void draw(){

    Graphics g = getGraphics();

    Graphics bbg = backBuffer.getGraphics();

    bbg.setColor(Color.BLACK);
    bbg.fillRect(0, 0, windowWidth, windowHeight);
    player.Draw(bbg);
    meteor.Draw(bbg);

    g.drawImage(backBuffer, 0, 0, this);
}
}

Comment: Is there a ShooterGame.class in the current directory? You should copy the full error message to question.
Comment: are  you trying "java -cp . ShooterGame" or "java -cp . ShooterGame.class"
Comment: The right way ("java -cp . ShooterGame")
Comment: Please check examples in http://stackoverflow.com/questions/6662665/could-not-find-the-main-class?rq=1
Comment: Please post the code to `ShooterGame`, and specify its' package.
Comment: I have posted ALL my code here already: http://stackoverflow.com/q/27808501/4415415.
Comment: Is "game" the current directory? "." means to look in the current directory. It doesn't mean to look in "game", unless "game" *is* the current directory.
Comment: So i do just "java -cp game.ShooterGame"?
Answer: Based on your code and comments, I believe you need
java -cp game ShooterGame

The game folder is where your ShooterGame.class is. So you could also
cd game
java -cp . ShooterGame

Now, if ShooterGame was in a game package; then it would be
java -cp . game.ShooterGame

And you would point to the folder that holds game.
Comment: Apparently the "cd game; java -cp . ShooterGame" worked, but it shows "Exception in thread 'main' java.lang.NoClassDefFoundError: game\player\Player". The player folder and Player.java are part of my game.
Comment: @gabzerbinato Move the `ShooterGame.class` up one folder, or add a `package game;` to `ShooterGame.java` and recompile. Or, create a new folder `game\game` and move `game\player` to `game\game\player`. Why did you put `ShooterGame.class` in `game` if you weren't going to put it in a `game` package?
Comment: I added a "package game;" to ShooterGame.java and recompiled it. My current directory is _game_. What command should I use now? "java -cp . ShootGame"?
Comment: Move up one folder, and then "java -cp . game.ShootGame"; the package is part of the class name (and you can take a look at what  a java class looks like compiled with `javap -v game\ShootGame.class`). Note that `import` is a convenience for you, internally classes are always fully qualified.

Unable to locate main class


Ctools content types- What do I need to do to get my content to render in the right place?

Question: I have some panels on my site.  Previously, I was using custom content panes with the PHP filter to call functions in a custom module.  The custom function had lots of print() statements and I simply dumped a bunch of HTML to the screen.
Now, I am trying to reform my bad programming practices by moving the custom content panes into Ctools content types.  I successfully created a content type, but when I call my function (in my custom module) full of print() statements, all of the HTML gets dumped to the top of the page, instead of where the content type has been placed within the panel.
Reading through articles online, it appears this is because the content pane expects me to return something it can render, not directly print() the HTML.  Is there another PHP function I can use to gather up all the HTML I was previously using print() for?  What is the correct way to output a bunch of HTML in a ctools content type?
(If this seems obvious, please bear with me.  I'm not a programmer by training and I'm probably in a bit over my head.)
Answer: From the top of my head you should simply be able to do:
$pane = new stdClass();
$pane->title = 'Check this out!'; // Optional
$pane->content = '
My content
';
return $pane;

It's also worthwhile to review What are Ctools plugin (content type, access, etc), and how does one create them? which contains an example content type.
The question
Correct way to render a modules output through a template? shows an example of rendering through a template, so you can strip the markup out from your pane and have it contain only the relevant content.
Comment: Thanks!  So I managed to get everything into `content` by changing every `print()` to dump it into a string (`$output .= ABC`) and then returning the string.


Conditional expectations $E\left(X^Y\mid X\right)$ and $E\left(X^Y\mid Y\right)$

Question:
Let $X,Y$ be independent random variables. $X$ has uniform distribution on $[0,1]$ and $Y$ has uniform distribution on $\{0,1\}$. Find $E\left(X^{Y}\mid X\right)$ and $E\left(X^{Y}\mid Y\right)$.

Both $E\left(X^{Y}\mid X\right)$ and $E\left(X^{Y}\mid Y\right)$ are random variables. My questions are:

is $X^{Y}$ measurable on $\sigma-$algebra generated by $X$ and
is $E\left(X^{Y}\mid Y\right)$ a discrete random variable?
Comment: "is $X^{Y}$ measurable on $\sigma-$algebra generated by $X$" No, why did you imagine it could be? "is $E(X^{Y}|Y)$ a discrete random variable?" Yes, since $Y$ is discrete.
Answer:
The smallest $σ$-algebra on which $X^Y$ is measurable is $σ\left(X^Y\right)$, defined as
$$σ\left(X^Y\right)=\left(X^Y\right)^{−1} \mathcal B(\mathbb R)=\left\{\{X^Y\in B\}\subset Ω:B\in \mathcal B(\mathbb R)\right\}$$ Now, take the set $B_1:=\{1\}\in \mathcal B(\mathbb R)$ with $$\left(X^Y\right)^{-1}B_1=\left\{ω\in Ω: X^Y(ω)=1\right\}=\{ω\inΩ: Y(ω)=0 \text{ or } X(ω)=1\}$$ A $σ$-algebra generated by $X$ does not contain the information $Y(ω)=0$ and hence $X^Y$ is not measurable with respect to it.
Observe that $$E\left(X^Y\mid Y=1\right)=E\left(X^1\right)=\frac12, \qquad E\left(X^Y\mid Y=0\right)=1$$ (ok, let $0^0=1$ or let $X\sim U(0,1)$ to avoid complications), and putting these two together with the help of indicator functions $$E\left(X^Y\mid Y\right)=1-\frac12\mathbf1_{\{Y=1\}}$$ and hence it is discrete (it takes the values $\frac12$ and $1$).
Answer: Since $X,Y$ are independent and $Y\sim\mathcal U\{0,1\}$ therefore:
$$\mathsf E(g(X,Y)\mid X) = \sum_{t=0}^1 \tfrac 12g(X,t)$$
Since $X,Y$ are independent and $X\sim\mathcal U[0;1]$ therefore:
$$\mathsf E(g(X,Y)\mid Y) = \int_0^1 g(s,Y)\mathrm d s$$
Comment: Shouldn't it be the other way, in the first case the integral and in the second the sum? Apart from this (if I am right), nice clear answer.
Comment: No. The conditional expectation, $\mathsf E(g(X,Y)\mid X)$, is a random variable that is a function of $X$ so clearly you don't "integrate out" the $X$.  $$\mathsf E(g(X,Y)\mid X)=\sum_t g(X, t) \mathsf P(Y=t\mid \sigma(X))$$
Comment: A, yes right. Thanks a lot. Very clear answer


Possibility of choosing $ε$ as function of $x_{n}$

Question: In the definition of the limit of sequence $(x_{n})$ (https://en.wikipedia.org/wiki/Limit_of_a_sequence#Definition)
I know that the definition is for all $ε>0$.
Traditionally, the values of $ε$ are not depends on $n$.
If I choose $ε$ (I am speaking on a particular case from the case $ε>0$) as function of $x_{n}$, i.e., taking $ε=g(x_{n})$ for some real function $g$. The existence of $N$ is guaranteed by the fact that the sequence is convergent.
My question is: Can I find an $N$ for this particular case where $ε_{n}=g(x_{n})$ such that the inequality $|x_{n}-l|<g(x_{n})$ holds for all $n>N$.
Comment: Well, I don't see the point, but you can just take $\epsilon = 1$ if you want.  The constant function.
Comment: Constant functions are still functions.  But take $\epsilon(n)=\frac 1n$ if you'd rather.
Comment: Not following.  the limit requires something to hold $\textit {for all } \epsilon$, not just a single value.   Where would $n$ fit in?
Comment: @lulu: I am not asking for all values. I am asking on the possibility of choosing one of that form..
Comment: @Helena So given x_n, you want a function that returns epsilon. But what epsilon do you want to return? Do you want an epsilon such that there exists an N such that d(x_k,x) < epsilon for all k>=N where k>=n ?
If so, this is not a function, because the output of the function, epsilon, can take many values.
Comment: Please edit your post for clarity.  It is not at all clear what you are asking.
Comment: @lulu: Yes. I have edited the question.
Comment: Still not clear.  Since the definition of a limit refers to all $\epsilon >0$, you are free to choose a particular such $\epsilon $ if you like.  Is that what you are asking?  Of course, that's a lot weaker than the definition of a limit.  And it still isn't clear where $n$ fits in.
Comment: @lulu: Yes. this is exactly the question.
Comment: @lulu: I required that it depends on $n$.
Comment: Not intending to be mean here, but I feel like the question still isn't being asked clearly. This function epsilon thing is weird. OP, you should consider re-wording the question to make it crystal clear what you mean. Spend longer thinking about exactly what question you want to ask... For example, you need to either reference the definition  of convergent sequence in the link (for any epsilon...), or your question needs to *not* be related to the definition of convergent  sequence in the link (which I suspect is the case).
Comment: @AdamRubinson: The question is edited.
Comment: So g is *any* function, not at all related to the convergence of (x_n)? You haven't specified what the properties of the function g are.
Comment: @AdamRubinson: you can consider it strictly positive and bijective.
Comment: "The existence of N is guaranteed by the fact that the sequence is convergent." Are you talking about the sequence $\epsilon_n = g(x_n) $or the sequence $x_n$ here ?
Comment: @AdamRubinson: In the question I write the sequence $x_n$
Comment: You don't tell us much about the function g. $g(x_n)$ could be a divergent sequence, meaning the answer to your question, as it stands, is "no".
Comment: @AdamRubinson: So the condition that this sequence $g(x_{n})$ is **bounded** is required.
Comment: That's not good enough though. $g(x_n)$ could be bounded but divergent e.g. -1, 1, -1, 1, ... . Or, even if $g(x_n)$ converges, it could converge to some limit $m =/= l$.
Answer: Consider any convergent sequence $(x_n)$ with limit $l$.
Let us suppose the sequence is not eventually constant (i.e. there is no $N$ such that i.e. $x_n=l$ for all $n\geq N$). Then if and only if $g(x_n)>0$ for all $n$, for all $n$ there is an $N$ such that $d(x_i,l) < g(x_i)$ for all $i \geq N$.
If the sequence if eventually constant then the inequality is relaxed to  $g(x_n)\geq 0$ for $n\geq N$, where $N$ is the point when the sequence becomes constant.
Comment: Your choice of epsilon wouldn't fit the *strict inequality* definition of convergence. epsilon would have to be just greater than sup{...} in order to guarantee the conditions of the definition are satisfied.
Comment: You're right. I think it should be easily fixed, though...
Comment: Yes that makes sense to me now. Although I suspect we have both misunderstood OP's actual question lol.
Comment: @AdamRubinson: Yes. the answer is not compatible with question.
Comment: So are you asking if the condition holds for $\epsilon$ chosen as any function of $x_n$? The answer is then clearly no, but for some functions it is clearly yes.
Comment: @broncoAbierto: Can you give a characterization of those functions.
Comment: @Helena I think it's a bit messy because of sequences that are eventually constant, but if you discard those, any strictly positive function works.
Comment: @Helena I think this should work. The wording could be improved, I guess...


what does "_height" mean in css?

Question: I'm familiar with
height

and
min-height

but in the code I am looking at there is _height: 100px
What's that about?  Is it an IE thing?
Answer: That's a CSS hack.
IE6 will ignore the underscore and read it as height; real browsers will (correctly) ignore the whole line.
Comment: @MichaelDurrant: Yes, it does.  The point is to set a separate `height` for IE6 only.
Comment: So a selector with both `height` and `_height` set to the same `90px` value would be pointless, right? There's no reason that explains what I'm reading in one of our CSS files?
Comment: No or people would just use height.  the reason is that ie6 recognizes height BUT USES IT AS MINIMUM HEIGHT.  so it looks really different.  To get around this you use both height (ok in most browers) and then another value with miminum_height to actually set the height using a different value.  Or something like that ;)
Comment: ah ok.  Do they not recognize 'height' by itself ?

what does "_height" mean in css?


Describing epimorphisms in Set-valued functor categories without using pointwise computation of colimits

Question: Let $\mathscr{A}$ be a small category and consider the functor category $[\mathscr{A}, \mathbf{Set}]$.

Fact.
The epimorphisms in $[\mathscr{A}, \mathbf{Set}]$ are precisely those natural transformations that are surjective in each component.

This fact can be proven by characterizing epimorphisms via pushouts, and then use that colimits in functor categories are computed pointwise.

Problem.
Can we prove the above fact in a more explicit way, without relying on the pointwise computation of colimints in functor categories? (And possibly also without the characterization of epimorphisms via pushouts.)

This problem is part of Exercise 6.2.20 in Tom Leinster's book Basic Category Theory.
In this exercise, the reader is asked to describe monomorphisms and epimorphisms in $[\mathscr{A}, \mathbf{Set}]$ in two ways:

By using their characterization via pullbacks, resp. pushouts, and the fact that (co)limits in functor categories are computed pointwise.

Without this pointwise computation of (co)limits in functor categories.

It is straightforward to check that pointwise injective/surjective transformations are monomorphisms/epimorphisms in $[\mathscr{A}, \mathbf{Set}]$.
One can also use Yoneda's lemma to show that monomorphisms in $[\mathscr{A}, \mathbf{Set}]$ are pointwise injective.
But I have not been able to solve the above problem so far.
I've also searched to solutions to the problem online, but have only found the following so far:

A related question on this site (Epimorphism in the functor category $[\mathbf{C}^{op}, \mathbf{Set}]$) has two anwers.
One of the answers uses the pointwise computation of colimits, and the other one deals only with the "easy" implication.

On MathOverflow (https://mathoverflow.net/questions/52846/prove-natural-transformation-is-epimorphism), only the solution via pointwise computation of colimits is given.
One of the answers is actually by Leinster himself.
As part of his answer, he points to…

materials for a course on Category Theory given by Leinster in 2007 (https://www.maths.ed.ac.uk/~tl/msci/).
The problem is already present in the problem sheets for this course (Problem 1 on Sheet 9). But in the hints/solutions to these problem sheets, Leinster admits that he also doesn't have a solution to the problem.
(But I don't know if he had a solution in mind when his book was released in 2014.)

Two inofficial collections of solutions to Leinster's book can be found online:
One by positrón0802 (https://positron0802.wordpress.com/basic-category-theory-leinster/) and one by Michael Weiss (https://diagonalargument.com/mathnotes/).
Both only deal with monomorphisms, and claim that epimorphisms can be dealt with "dually".
But I don't see how this dualization is supposed to work.¹

¹ More explicitly, both solutions use the Yoneda isomorphism $\operatorname{Nat}(H^A, X) ≅ X(A)$ to deal with monomorphisms.
To adapt their arguments to epimorphhisms, we would need such an isomorphism for $\operatorname{Nat}(X, H^A)$.
But dualizing the Yoneda lemma gives instead the isomorphism $\operatorname{Nat}(H_A, X) ≅ X(A)$.
Answer: Here is a fairly explicit proof which comes naturally out of topos theory, using the fact that $[\mathscr{A}, \mathbf{Set}]$ forms a topos.  The basic idea here is that we want to generalize the following argument in $\mathbf{Set}$: Suppose $f : X \to Y$ is an epimorphism in $\mathbf{Set}$.  Then consider the two maps $\chi_{\operatorname{im}(f)} : Y \to \{ 0, 1 \}$ where $y\mapsto 1$ if there is $x\in X$ with $f(x) = y$, and $y\mapsto 0$ otherwise; and the second map $Y\to \{ 0, 1 \}$ will be the constant map 1.  It is easy to see that $\chi_{\operatorname{im}(f)} \circ f = 1 \circ f$, so $\chi_{\operatorname{im}(f)} = 1$, and from this it follows that $f$ is surjective.
To generalize this to $[\mathscr{A}, \mathbf{Set}]$, what we end up needing in place of $\{ 0, 1 \}$ is known as a subobject classifier $\Omega$.  For this case, $\Omega$ is the functor where $\Omega(A)$ is the set of $S \subseteq \bigsqcup_{B\in \mathscr{A}} \operatorname{Hom}(A, B)$ such that whenever $f \in \operatorname{Hom}(A, B)$, $g \in \operatorname{Hom}(B, C)$, and $f\in S$, then $g\circ f \in S$.  The operation of this functor on morphisms is: for $f_0 \in \operatorname{Hom}(A, B)$ and $S \in \Omega(A)$, $\Omega_*(f_0)$ maps $S$ to $\{ f \in \operatorname{Hom}(B, C) \mid f \circ f_0 \in S \} \in \Omega(B)$.
Now suppose we have a natural transformation $\alpha : F \to G$ which is an epimorphism in $[\mathscr{A}, \mathbf{Set}]$.  Then we can consider two morphisms $G \to \Omega$.  The first, which will be a generalization of $\chi_{\operatorname{im}(\alpha)}$, will map $y \in G(A)$ to $\{ f \in \operatorname{Hom}(A, B) \mid \exists x \in F(B), \alpha_B(x) = G_*(f)(y) \} \in \Omega(A)$.  The second, which will be a generalization of the constant map 1, we will call $\operatorname{true}$ and it will send any $y \in G(A)$ to the full set $\bigsqcup_{B\in \mathscr{A}} \operatorname{Hom}(A, B)$.
It is straightforward to check that $\Omega$ is a functor; $\chi_{\operatorname{im}(\alpha)}$ and $\operatorname{true}$ are both natural transformations; and $\chi_{\operatorname{im}(\alpha)} \circ \alpha = \operatorname{true} \circ \alpha$.  Therefore, since $\alpha$ is an epimorphism, $\chi_{\operatorname{im}(\alpha)} = \operatorname{true}$.  It should also be straightforward to show using this that $\alpha_A$ is surjective for every $A$ (hint: use the special case that $\operatorname{id}_A \in (\chi_{\operatorname{im}(f)})_A(y)$ for every $y \in G(A)$).


Validate percentage value

Question: I am validating percentage value:
validateFloatValue: function(value) {
    var number = parseFloat(value);
    if (isNaN(number)) {
        console.log("Invalid value");
    }
}

Basically, value is passed as string. It passes for "33.45" which is fine. But, I do not want to allow user to enter "33.45%". But, in this case, there is no error for "33.45%" since parseFloat is converting "33.45%" to 33.45 parseFloat("33.45"). How can I throw error, if value is "33.45%"?
Comment: @Yogesh: You could use a `+` cast instead: `var number = +value`.
Comment: No need for using `parseFloat`. You can just simply check it with `isNaN`.
Comment: simple check if string contains "%" with indexOf .
Answer: You can eventually exclude all things that does not match a regex... like if value not match \d[.,]+\d You should write a regex that match your needs ;)

(function validateFloatValue(value) {
    var number = parseFloat(value);
    if (! /^\d+[., ]+\d+$/.test(value) || isNaN(number)) {
      document.getElementById('res').innerHTML = "Invalid value";
    }
})("12.34%");

Answer: Number.isFinite validates input slightly more strictly:
validateFloatValue: function(value) {
    if (!Number.isFinite(number)) {
        console.log("Invalid value");
    }
}

You can also use isNaN directly - it would be more portable:
validateFloatValue: function(value) {
    if (isNaN(number)) {
        console.log("Invalid value");
    }
}

Answer: If you only what  to check if the string contains %, you can use indexOf like this.
if (value.indexOf('%') === -1) {

} else {
  console.log("Invalid value");
}

If you want to check if the string is a number, you can try to convert the string to number using the Number function.
If the value cannot be converted to a legal number, NaN (Not a Number) is returned.
So you just have to verify if the result is NaN using the isNaN function like this :
var valueNumber = Number(value);
if (!isNaN(valueNumber)) {

} else {
  console.log("Invalid value");
}

Comment: It doesn't handle properly input like this: `12.3 spam`, which is still invalid.

Validate percentage value


how can I get alert by success and fail

Question: I have problem: how could I display alert with this situation?
This alert shows the same alert when it does pass or not pass data to database.
I tried success and error method, but still didn't get anything.
ajax.php:
 $(document).ready(function(){
    $('#addDocumentForm').on('submit', function(e){
  $('#select_image').change(function(){
       $('#addDocumentForm').submit();
  });

       e.preventDefault();
       $.ajax({
            url :"main.php",
            method:"POST",
            data:new FormData(this),
            contentType:false,
            processData:false,
            success:function(data){

            location.reload(true);

            }
       })
  });

main.php:
 if (!in_array($fileExtension,$fileExtensions)) {
   echo "";

    }else if (in_array($fileExtension,$fileExtensions)) {

    $stmt = $dbh->prepare("insert into document values('',?)");
    $stmt->bindParam(1,$filename);
    $stmt->execute();
   echo "";

I put alert like this in main.php, but not working, only show alert in ajax.php.
I want to get alert also when data fail insert to database such as "file should be image", or "successfully added" when data insert successfully.
Comment: Please fix your code indentation.
Comment: Of course it works, you might as well post minified code. On stackoverflow it is necessary to have proper code indentation for better readability and good practice in general.
Comment: i just made short but i just need alert
Comment: it's works and it insert to database i just need alert by fail and success
Answer: When you are in a different file, echoing a script does not affect the other file that the AJAX request was sent from. However, you can use the data parameter provided by AJAX's success function and append the script that you received to the body:
$.ajax({
    url: "main.php",
    method: "POST",
    data: new FormData(this),
    contentType: false,
    processData: false,
    success: function(data){
        // append script to the body
        $('body').append(data);
    }
});

You can also echo the string that you want to alert in main.php and use alert(data) directly from the success callback instead, and I really suggest you do, but in the end it is your choice.
EDIT (solution for the latter)
main.php
if (!in_array($fileExtension,$fileExtensions)) {
   echo "asd";
// etc ...

ajax.php
{
    success: function(data) {
        // alerts echoed content if any
        if(data) alert(data);
    }
}

how can I get alert by success and fail


What are the differences between pthread reader-writer locks and fcntl()-based file locks?

Question: For a project I am thinking about using pthread reader-writer locks or fcntl()-based file locks. I have to choose on of them. Could you please explain the differences between them? What are the advantages and disadvantages?
Answer: They're two completely different tools and are generally used for different tasks. A fair or complete contrast between the two is difficult as it's like comparing apples to couches.
TL;DR:
fcntl(2):

Advisory locking interface
Primarily works on files
Easily works between multiple processes

pthread_rwlock:

Advisory locking interface
Serializes access to conflicting operations (writes/reads, writes/writes, reads/writes)
Provides safety for shared resources (memory, file descriptors, etc) between multiple threads in a single process

fcntl(2)-based locks implement POSIX advisory locks on files, or ranges of bytes within the files. As they are advisory, nothing enforces these locks -- all processes (or threads) must cooperate and respect the semantics of the locks for them to be effective. For example, consider two processes A and B operating on some file f. If process A sets locks on f, B can completely ignore these locks and do whatever it likes. In general, this interface is used to protect access to entire files (or ranges within a file) between multiple threads and / or processes.
The pthread_rwlock interface could also be considered an advisory locking system (all threads must use the API for the locking to be effective). However, it is not implemented on top of files and is not limited in scope to protecting access to files. A reader-writer lock is a form of shared memory mutual exclusion interface such that multiple readers may concurrently execute a critical section while writers are blocked, or such that individual writers may execute a critical section, blocking all other concurrent readers and writers. In general, this interface is used to safeguard access to shared mutable state (possibly shared memory, possibly file access) between multiple threads in a process in read-mostly workloads. This API is not typically used to protect concurrent access in multiple processes.
If I were faced with the decision on picking one of these interfaces for serializing access to some data, I'd expect to ask myself at least a couple of questions:

Am I primarily working on files?
Do I have multiple processes?

If the intent is largely to protect access to a file, but only ever in a single process, I might settle for using pthread_rwlock. The downside to this approach is that if I ever needed to use multiple processes to access the file in the future, I wouldn't have a good way to express my locking intent to those other processes. Similarly, if I'm primarily trying to serialize access to some shared memory, I would use pthread_rwlock because the fcntl(2) interface expresses some intent on a file.
When trying to cooperate between multiple processes reading and writing a single file, I might use fcntl(2). However, this is likely to become very complicated, very quickly. For example, how do I handle events like truncation? Consider a case where process A has read 1024 bytes into a file that is then truncated to 0 bytes by process B. A must then seek to the beginning of the file and wait for new data to be written to continue reading without errors -- or to correctly append new data itself!
Solving these issues requires more locked communication in additional files, and the complexity can quickly spiral out of control. If I was required to implement some sort of concurrent system working on a file, I'd likely choose multiple threads and use the pthread_rwlock API. It's just easier to manage the totality of updates required to implement such a system in a single process. Without knowing the requirements you're faced with, it's rather difficult to guide one way or another.


Multiple application/json for same http POST request

Question: I am designing a REST API for incident reporting. There are are three state for one incident. i.e investigation,resolved and postmortem.
I use uri for incident resource as
 /incident/{incident_id}/{status}

Here incident_id denotes unique id of an incident and status denotes state of an incident.
User can create new incident(this is in investigation state) using
 POST - /incident

Say uri  after creating incident is
/incident/123

The applicatoin/json which is needed to be send with POST request to create resolved state and postmortem state of an incident are different.
Then there are two application/json for same uri.
I don't need change uri to
 POST -/incident/investigation/{incident_id}
 POST -/incident/resolved/{incident_id}
 POST -/incident/postmortem/{incident_id}

How to fix this problem?
Comment: Can you please clarify _Now I want to post two application/json for resolved and postmortem states. But I can't use two post requests for same uri._?
Comment: When some one report a resolved state or postmortem state of an incident, jsons sent with POST request are different.
Comment: It's very hard to understand what you want to achieve with such level of details. Can you please try to provide a concrete example? Also, please read your question _again_ and ask yourself if, anyone without a prior context would be able to understand what you mean.
Answer:
The application/json which is needed to be send with POST request to create resolved state and postmortem state of an incident are different.

So there are two common answers here.
One is that the POST endpoint for the resource inspects the JSON object to figure out which request was made by the client, and then does the right thing.
The more mature version of this same idea is to use a different Content-Type to distinguish the json documents.  That is to say, if you define an application/vnd.resolved+json schema and an application/vnd.postmortem+json schema, then the client reports in the http headers which form of message it is sending to you.
POST /incident/12345
Content-Type: application/vnd.resolved+json

{ "resolved" : { ... } }

POST /indicdent/12345
Content-Type: application/vnd.postmortem+json

{ "post-mortem" : { ... } }

RFC 6838 describes the protocols for registering new media type formats, as well as reserving several namespaces for unregistered types.


How to interpret coefficients of a multinomial elastic net (glmnet) regression

Question: I'm trying to model a membership in one of three well-being clusters (flourisher, normative, languisher) based on a set of predictors, using elastic net for both variable selection & modelling. I first use the caret package in combination with the glmnet package to do a 10-fold crossvalidation of a multinomial logistic regression to find the optimal values for $\alpha$ and $\lambda$:
set.seed(123456)
elastic_train <- train(cluster_membership ~ ., data =
                   data_multi, method = "glmnet",
                   tuneLength = 25, trControl =
                   trainControl(method = "repeatedcv",
                   search = "random"))

After that, I refit a glmnet model with the optimal $\alpha$ and $\lambda$ and pull out the coefficients of the model:
elastic_mod <- glmnet(model.matrix(cluster_membership ~ .,
                     data = data_multi),
data_multi$cluster_membership,family = "multinomial", alpha =
elastic_net$bestTune$alpha,
lambda = elastic_net$bestTune$lambda)

coef(elastic_mod, s = 'lambda.min')

My question is, why are there three sets of predictors & how do I interpret them? I understand that in ordinary multinomial regression, one of the outcome categories is used as a reference level & therefore there are $n_{category} - 1$ sets of predictors (e.g. in my case, there would be one set of predictors predicting flourisher vs normative, and another set of predictors predicting languisher vs normative). However, this is not the case in the glmnet multinomial output - there are clearly three sets of predictors:
$flourisher
24 x 1 sparse Matrix of class "dgCMatrix"
                                        1
(Intercept)                  -1.097799622
(Intercept)                   .
genderFemale                  .
ethnicAsian                  -0.209824802
ethnicMaori/Pacific Islander  .
ethnicOther                  -0.976265266
age                           .
BMI                           .
BMR_kcal                      .
CRPmgL                        .
md_ndrink                     .
md_refresh                    0.262365972
md_sleep                      .
md_dstress                   -0.135152345
md_dwrkld                     .
md_dcreate                   -0.028441041
md_dpac                       0.007127653
md_dfruit                     .
md_dveg                       .
md_dchips                    -0.091275151
md_dsweets                    .
md_dsoftdrk                  -0.069636339
md_dmood_happy                1.514874739
md_dmood_sad                 -1.167555384

$normative
24 x 1 sparse Matrix of class "dgCMatrix"
                                      1
(Intercept)                  1.10289610
(Intercept)                  .
genderFemale                 0.11272708
ethnicAsian                  0.06757730
ethnicMaori/Pacific Islander .
ethnicOther                  .
age                          .
BMI                          .
BMR_kcal                     .
CRPmgL                       .
md_ndrink                    .
md_refresh                   .
md_sleep                     .
md_dstress                   0.01914515
md_dwrkld                    .
md_dcreate                   .
md_dpac                      .
md_dfruit                    .
md_dveg                      .
md_dchips                    .
md_dsweets                   .
md_dsoftdrk                  .
md_dmood_happy               .
md_dmood_sad                 .

$languisher
24 x 1 sparse Matrix of class "dgCMatrix"
                                        1
(Intercept)                  -0.005096477
(Intercept)                   .
genderFemale                  .
ethnicAsian                   .
ethnicMaori/Pacific Islander  .
ethnicOther                   0.037015029
age                           .
BMI                           0.105868542
BMR_kcal                      .
CRPmgL                        .
md_ndrink                    -0.027819620
md_refresh                   -0.020768855
md_sleep                      .
md_dstress                    .
md_dwrkld                     .
md_dcreate                    0.121300148
md_dpac                      -0.016322027
md_dfruit                     .
md_dveg                       .
md_dchips                     .
md_dsweets                    .
md_dsoftdrk                   .
md_dmood_happy               -0.032887466
md_dmood_sad                  1.028937162

How do I interpret the predictors for each category? Do I understand it correctly that there's no concrete reference category?
Answer: I emailed kind Dr. Hastie who is the maintainer of the glmnet package and got the following answer:
In the traditional case, the base category is arbitrary.
In fact you can take a fitted model where say category one is the base category, and simply by subtraction of coefficients,
make an equivalent model where another is the base (and the fit is identical). (Care must be taken with the standard errors).
Concretely, if category 1 is the base, and you have coefficient vector \beta_k for category k , k=2,…,K (with \beta_1=0)
you can make say category K the base. In this case the new coefficients would be
\beta'_k = \beta_k-\beta_K
and the fitted probabilities would be unchanged.
With glmnet we chose a symmetric option instead, because we use regularization.
With regularization, it would matter and make a difference if you used an asymmetric representation
because of the way the shrinking works.
I like the type.multinomial= "grouped" option. In this case a group lasso penalty is applied to the set of coefficients for each feature,
and the estimated coefficients average 0.
Again, you can post hoc move to an asymmetric representation as above without changing the fitted model.


webpage is not centered in tablet

Question: I developing a webpage in django and now i came to test it in all devices. page is running well in all major pc webbrowsers.
this is my page: http://locateyourdate.de/
but if you open the page in tablet pc, the whole page's align goes to left, and not like how it looks in normal pc webbrowser which is centered
how can i fix it? i tried with position absolute but i destroyed the page, I am really stuck how to make it work
Comment: Which tablet browser are you seeing the problem in?
Comment: Please read [Something on my web site doesn't work. Can I just paste a link to it?](http://meta.stackexchange.com/questions/125997/something-on-my-web-site-doesnt-work-can-i-just-paste-a-link-to-it)
Comment: [55 Errors, 5 warning(s)](http://validator.w3.org/check?uri=http%3A%2F%2Flocateyourdate.de%2F&charset=%28detect+automatically%29&doctype=Inline&group=0)
Answer: Disregarding the errors Quentin mentioned, if your tablet has a max-width resolution of 1024px like most tablets, it's understandable why the site appears aligned to the left. The main container is simply larger than 1024px.
If you want your site to look good on tablets and smaller devices, it needs to be responsive.
Google for 'responsive web design'.
Comment: Without meta viewport, most tablets will tell the world they're >960px wide and "zoom out" to display the page as on a 1024px monitor. @Jacob question is still unanswered.
Comment: @FelipeAls, so i should set meta tag viewport?

webpage is not centered in tablet


JQuery Ajax error when call server side method in asp C#

Question: I'm trying to call server side method using ajax in asp C# application.
i have the following code in aspx file
function editApp(appID) {
            $.ajax({
            type: "POST",
            url: "Default.aspx/GetSquare",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{}",
            success: function (data) {
                alert(data);
            },

            error: function () {
                alert("Ajax Error");
            }
        });
}

and the following code in aspx.cs file
[WebMethod]
    public static string GetSquare()
    {
        return "OK";
    }

but in each time i call editApp function i get the following alert "Ajax Error"
Comment: Change error part like this and update your question with error message:
    `error: function (request, status, error) {
            alert(error);
        }`
Comment: And put breakpoint inside GetSquare method and run the application. And see if it hits the breakpoint or not?
Comment: Try getting rid of the data type. It looks to me you are expecting a json but your server method is not returning a json.
Comment: Please remove `data: "{}",`
Comment: change -  data: "{ }" to data: { } and come back to us
Answer: Since you are not passing any parameters, mentioning as data: "{}" is giving you errors. Instead you have to specify as data: {} as shown below.
function editApp(appID) {
            $.ajax({
            type: "POST",
            url: "Default.aspx/GetSquare",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: {},
            success: function (data) {
                alert(data);
            },

            error: function () {
                alert("Ajax Error");
            }
        });
}


Self-referential paradox

Question: In some legal documents, we read, "this page is intentionally left blank." Since this text is written on this page, the page is not really blank.
Is there a mathematical formulation for this paradox? I thought this was similar to Russell's paradox, but it doesn't seem so.
Comment: There is no paradox, this is simply a false statement (if you interpret "blank" as "not containing any text"). Much like "this sentence contains zero letters" is not a paradoxical statement but simply a false one.
Comment: I'm pointing out the obvious here, because I suspect OP is asking this question out of curiosity. "This page is intentionally left blank" implicitly means, "This page is intentionally left blank of legal documentation", and this would not be a false statment. So whether or not the statement is true or not depends if you interpret the sentence "This page is blank" *word-for-word literally,* in which case the statement is false, or if you care about the intended meaning behind the statement, in which case it is true.
Comment: As per comment above, not every "self referential" statement is paradoxical.
Answer: I admit I am not going to add much to the answers already in the comments, but typing this out helped me to clarify my own thoughts on the matter and might help OP as well. Any comment and correction is more than welcome.
In order to give an answer one should first define what paradox really means. Etymologically, a paradox is any sentence that goes against common belief. Quite literally anything that is somewhat unexpected or surprising. This is a tremendously informal definition which serves only to capture the broadest usage and meaning of the word paradox. A different and - in my opinion - more precise word to use in this context, is antinomy.
Antinomy: An antinomy is a proposition which leads to a conclusion of the form $A \iff \neg A$.
An example of antinomy is: $A$: "$A$ is false". That is, a sentence which states its own falsehood. If $A$ is true, then it is true that "$A$ is false". Thus $A$ should be false. If $A$ is false, then it is false that "$ A$ is false". Thus, $A$ should be true. Therefore, we have deduced that $A$ is true if and only if it is false; i.e., $A \iff \neg A$. An antinomy.
Perhaps the most famous antinomy of mathematics is Russell's paradox. Although this is conventionally identified as a paradox, there is nothing wrong, under our terminology, to call it an antinomy. More or less formally, this can derived as follows. Consider the set $S$ of all sets which do not contain themselves; i.e., $S = \{x \mid x \notin x\}$. If $S \in S$, then by definition of $S$ one should have $S \notin S$. If $S \notin S$, then by definition of $S$ again, one should have $S \in S$. Therefore, $S \in S \iff S \notin S$. An antinomy.
Now for the question. The proposition $B$: "This page is blank" could be surprising to some extent as it seems to clash with reality, but it is not an antinomy by our definitions and it is quite distinct from Russell's paradox. Assuming $B$ is true, leads to the belief that the page should be blank. The actual state of the world in this moment is such that the page is not blank. Thus, $B$ should be false. However, assuming $B$ is false leads to the belief that the page should have some text on it. As the world states right now this is perfectly true and $B$ remains false. Thus, although assuming that $B$ is true, leads to the conclusion that $B$ is false, the converse is not true. Assuming that $B$ is false is consistent with the state of the world.

Self-referential paradox