Programs & Examples On #Strtok

strtok() is a Standard C (ISO 9899:1989) function for splitting a string in tokens. strtok_r() is the thread-safe variant defined by IEEE Std 1003.1:2004 (aka "POSIX").

Using strtok with a std::string

Assuming that by "string" you're talking about std::string in C++, you might have a look at the Tokenizer package in Boost.

Split string into tokens and save them in an array

Why strtok() is a bad idea

Do not use strtok() in normal code, strtok() uses static variables which have some problems. There are some use cases on embedded microcontrollers where static variables make sense but avoid them in most other cases. strtok() behaves unexpected when more than 1 thread uses it, when it is used in a interrupt or when there are some other circumstances where more than one input is processed between successive calls to strtok(). Consider this example:

#include <stdio.h>
#include <string.h>

//Splits the input by the / character and prints the content in between
//the / character. The input string will be changed
void printContent(char *input)
{
    char *p = strtok(input, "/");
    while(p)
    {
        printf("%s, ",p);
        p = strtok(NULL, "/");
    }
}

int main(void)
{
    char buffer[] = "abc/def/ghi:ABC/DEF/GHI";
    char *p = strtok(buffer, ":");
    while(p)
    {
        printContent(p);
        puts(""); //print newline
        p = strtok(NULL, ":");
    }
    return 0;
}

You may expect the output:

abc, def, ghi,
ABC, DEF, GHI,

But you will get

abc, def, ghi,

This is because you call strtok() in printContent() resting the internal state of strtok() generated in main(). After returning, the content of strtok() is empty and the next call to strtok() returns NULL.

What you should do instead

You could use strtok_r() when you use a POSIX system, this versions does not need static variables. If your library does not provide strtok_r() you can write your own version of it. This should not be hard and Stackoverflow is not a coding service, you can write it on your own.

How to split a string to 2 strings in C

For purposes such as this, I tend to use strtok_r() instead of strtok().

For example ...

int main (void) {
char str[128];
char *ptr;

strcpy (str, "123456 789asdf");
strtok_r (str, " ", &ptr);

printf ("'%s'  '%s'\n", str, ptr);
return 0;
}

This will output ...

'123456' '789asdf'

If more delimiters are needed, then loop.

Hope this helps.

How does strtok() split the string into tokens in C?

strtok doesn't change the parameter itself (str). It stores that pointer (in a local static variable). It can then change what that parameter points to in subsequent calls without having the parameter passed back. (And it can advance that pointer it has kept however it needs to perform its operations.)

From the POSIX strtok page:

This function uses static storage to keep track of the current string position between calls.

There is a thread-safe variant (strtok_r) that doesn't do this type of magic.

Exit from app when click button in android phonegap?

I used a combination of the above because my app works in the browser as well as on device. The problem with browser is it won't let you close the window from a script unless your app was opened by a script (like browsersync).

        if (typeof cordova !== 'undefined') {
            if (navigator.app) {
                navigator.app.exitApp();
            }
            else if (navigator.device) {
                navigator.device.exitApp();
            }
        } else {
            window.close();
            $timeout(function () {
                self.showCloseMessage = true;  //since the browser can't be closed (otherwise this line would never run), ask the user to close the window
            });
        }

jQuery Validation using the class instead of the name value

I know this is an old question. But I too needed the same one recently, and I got this question from stackoverflow + another answer from this blog. The answer which was in the blog was more straight forward as it focuses specially for this kind of a validation. Here is how to do it.

$.validator.addClassRules("price", {
     required: true,
     minlength: 2
});

This method does not require you to have validate method above this call.

Hope this will help someone in the future too. Source here.

htmlentities() vs. htmlspecialchars()

**HTML Character Entity Reference Chart at W3.org**

https://dev.w3.org/html5/html-author/charref

&Tab;
&NewLine;
!
&excl;
"
&quot; &QUOT;
#
&num;
$
&dollar;
%
&percnt;
&
&amp; &AMP;
'
&apos;
(
&lpar;
)
&rpar;
*
&ast; &midast;
+
&plus;
,
&comma;
.
&period;
/
&sol;
:
&colon;
;
&semi;
<
&lt; &LT;
=
&equals;
>
&gt; &GT;
?
&quest;
@
&commat;
[
&lsqb; &lbrack;
\
&bsol;
]
&rsqb; &rbrack;
^
&Hat;
_
&lowbar;
`
&grave; &DiacriticalGrave;
{
&lcub; &lbrace;
|
&verbar; &vert; &VerticalLine;
}
&rcub; &rbrace;

&nbsp; &NonBreakingSpace;
¡
&iexcl;
¢
&cent;
£
&pound;
¤
&curren;
¥
&yen;
¦
&brvbar;
§
&sect;
¨
&Dot; &die; &DoubleDot; &uml;
©
&copy; &COPY;
ª
&ordf;
«
&laquo;
¬
&not;
&shy;
®
&reg; &circledR; &REG;
¯
&macr; &OverBar; &strns;
°
&deg;
±
&plusmn; &pm; &PlusMinus;
²
&sup2;
³
&sup3;
´
&acute; &DiacriticalAcute;
µ
&micro;
¶
&para;
·
&middot; &centerdot; &CenterDot;
¸
&cedil; &Cedilla;
¹
&sup1;
º
&ordm;
»
&raquo;
¼
&frac14;
½
&frac12; &half;
¾
&frac34;
¿
&iquest;
À
&Agrave;
Á
&Aacute;
Â
&Acirc;
Ã
&Atilde;
Ä
&Auml;
Å
&Aring;
Æ
&AElig;
Ç
&Ccedil;
È
&Egrave;
É
&Eacute;
Ê
&Ecirc;
Ë
&Euml;
Ì
&Igrave;
Í
&Iacute;
Î
&Icirc;
Ï
&Iuml;
Ð
&ETH;
Ñ
&Ntilde;
Ò
&Ograve;
Ó
&Oacute;
Ô
&Ocirc;
Õ
&Otilde;
Ö
&Ouml;
×
&times;
Ø
&Oslash;
Ù
&Ugrave;
Ú
&Uacute;
Û
&Ucirc;
Ü
&Uuml;
Ý
&Yacute;
Þ
&THORN;
ß
&szlig;
à
&agrave;
á
&aacute;
â
&acirc;
ã
&atilde;
ä
&auml;
å
&aring;
æ
&aelig;
ç
&ccedil;
è
&egrave;
é
&eacute;
ê
&ecirc;
ë
&euml;
ì
&igrave;
í
&iacute;
î
&icirc;
ï
&iuml;
ð
&eth;
ñ
&ntilde;
ò
&ograve;
ó
&oacute;
ô
&ocirc;
õ
&otilde;
ö
&ouml;
÷
&divide; &div;
ø
&oslash;
ù
&ugrave;
ú
&uacute;
û
&ucirc;
ü
&uuml;
ý
&yacute;
þ
&thorn;
ÿ
&yuml;
A
&Amacr;
a
&amacr;
A
&Abreve;
a
&abreve;
A
&Aogon;
a
&aogon;
C
&Cacute;
c
&cacute;
C
&Ccirc;
c
&ccirc;
C
&Cdot;
c
&cdot;
C
&Ccaron;
c
&ccaron;
D
&Dcaron;
d
&dcaron;
Ð
&Dstrok;
d
&dstrok;
E
&Emacr;
e
&emacr;
E
&Edot;
e
&edot;
E
&Eogon;
e
&eogon;
E
&Ecaron;
e
&ecaron;
G
&Gcirc;
g
&gcirc;
G
&Gbreve;
g
&gbreve;
G
&Gdot;
g
&gdot;
G
&Gcedil;
H
&Hcirc;
h
&hcirc;
H
&Hstrok;
h
&hstrok;
I
&Itilde;
i
&itilde;
I
&Imacr;
i
&imacr;
I
&Iogon;
i
&iogon;
I
&Idot;
i
&imath; &inodot;
?
&IJlig;
?
&ijlig;
J
&Jcirc;
j
&jcirc;
K
&Kcedil;
k
&kcedil;
?
&kgreen;
L
&Lacute;
l
&lacute;
L
&Lcedil;
l
&lcedil;
L
&Lcaron;
l
&lcaron;
?
&Lmidot;
?
&lmidot;
L
&Lstrok;
l
&lstrok;
N
&Nacute;
n
&nacute;
N
&Ncedil;
n
&ncedil;
N
&Ncaron;
n
&ncaron;
?
&napos;
?
&ENG;
?
&eng;
O
&Omacr;
o
&omacr;
O
&Odblac;
o
&odblac;
Œ
&OElig;
œ
&oelig;
R
&Racute;
r
&racute;
R
&Rcedil;
r
&rcedil;
R
&Rcaron;
r
&rcaron;
S
&Sacute;
s
&sacute;
S
&Scirc;
s
&scirc;
S
&Scedil;
s
&scedil;
Š
&Scaron;
š
&scaron;
T
&Tcedil;
t
&tcedil;
T
&Tcaron;
t
&tcaron;
T
&Tstrok;
t
&tstrok;
U
&Utilde;
u
&utilde;
U
&Umacr;
u
&umacr;
U
&Ubreve;
u
&ubreve;
U
&Uring;
u
&uring;
U
&Udblac;
u
&udblac;
U
&Uogon;
u
&uogon;
W
&Wcirc;
w
&wcirc;
Y
&Ycirc;
y
&ycirc;
Ÿ
&Yuml;
Z
&Zacute;
z
&zacute;
Z
&Zdot;
z
&zdot;
Ž
&Zcaron;
ž
&zcaron;
ƒ
&fnof;
?
&imped;
?
&gacute;
?
&jmath;
ˆ
&circ;
?
&caron; &Hacek;
?
&breve; &Breve;
?
&dot; &DiacriticalDot;
°
&ring;
?
&ogon;
˜
&tilde; &DiacriticalTilde;
?
&dblac; &DiacriticalDoubleAcute;
?
&DownBreve;
_
&UnderBar;
?
&Alpha;
?
&Beta;
G
&Gamma;
?
&Delta;
?
&Epsilon;
?
&Zeta;
?
&Eta;
T
&Theta;
?
&Iota;
?
&Kappa;
?
&Lambda;
?
&Mu;
?
&Nu;
?
&Xi;
?
&Omicron;
?
&Pi;
?
&Rho;
S
&Sigma;
?
&Tau;
?
&Upsilon;
F
&Phi;
?
&Chi;
?
&Psi;
O
&Omega;
a
&alpha;
ß
&beta;
?
&gamma;
d
&delta;
e
&epsiv; &varepsilon; &epsilon;
?
&zeta;
?
&eta;
?
&theta;
?
&iota;
?
&kappa;
?
&lambda;
µ
&mu;
?
&nu;
?
&xi;
?
&omicron;
p
&pi;
?
&rho;
?
&sigmav; &varsigma; &sigmaf;
s
&sigma;
t
&tau;
?
&upsi; &upsilon;
f
&phi; &phiv; &varphi;
?
&chi;
?
&psi;
?
&omega;
?
&thetav; &vartheta; &thetasym;
?
&Upsi; &upsih;
?
&straightphi;
?
&piv; &varpi;
?
&Gammad;
?
&gammad; &digamma;
?
&kappav; &varkappa;
?
&rhov; &varrho;
?
&epsi; &straightepsilon;
?
&bepsi; &backepsilon;
?
&IOcy;
?
&DJcy;
?
&GJcy;
?
&Jukcy;
?
&DScy;
?
&Iukcy;
?
&YIcy;
?
&Jsercy;
?
&LJcy;
?
&NJcy;
?
&TSHcy;
?
&KJcy;
?
&Ubrcy;
?
&DZcy;
?
&Acy;
?
&Bcy;
?
&Vcy;
?
&Gcy;
?
&Dcy;
?
&IEcy;
?
&ZHcy;
?
&Zcy;
?
&Icy;
?
&Jcy;
?
&Kcy;
?
&Lcy;
?
&Mcy;
?
&Ncy;
?
&Ocy;
?
&Pcy;
?
&Rcy;
?
&Scy;
?
&Tcy;
?
&Ucy;
?
&Fcy;
?
&KHcy;
?
&TScy;
?
&CHcy;
?
&SHcy;
?
&SHCHcy;
?
&HARDcy;
?
&Ycy;
?
&SOFTcy;
?
&Ecy;
?
&YUcy;
?
&YAcy;
?
&acy;
?
&bcy;
?
&vcy;
?
&gcy;
?
&dcy;
?
&iecy;
?
&zhcy;
?
&zcy;
?
&icy;
?
&jcy;
?
&kcy;
?
&lcy;
?
&mcy;
?
&ncy;
?
&ocy;
?
&pcy;
?
&rcy;
?
&scy;
?
&tcy;
?
&ucy;
?
&fcy;
?
&khcy;
?
&tscy;
?
&chcy;
?
&shcy;
?
&shchcy;
?
&hardcy;
?
&ycy;
?
&softcy;
?
&ecy;
?
&yucy;
?
&yacy;
?
&iocy;
?
&djcy;
?
&gjcy;
?
&jukcy;
?
&dscy;
?
&iukcy;
?
&yicy;
?
&jsercy;
?
&ljcy;
?
&njcy;
?
&tshcy;
?
&kjcy;
?
&ubrcy;
?
&dzcy;
 
&ensp;
 
&emsp;
 
&emsp13;
 
&emsp14;
 
&numsp;
 
&puncsp;
 
&thinsp; &ThinSpace;
 
&hairsp; &VeryThinSpace;
?
&ZeroWidthSpace; &NegativeVeryThinSpace; &NegativeThinSpace; &NegativeMediumSpace; &NegativeThickSpace;
?
&zwnj;
?
&zwj;
?
&lrm;
?
&rlm;
-
&hyphen; &dash;
–
&ndash;
—
&mdash;
-
&horbar;
?
&Verbar; &Vert;
‘
&lsquo; &OpenCurlyQuote;
’
&rsquo; &rsquor; &CloseCurlyQuote;
‚
&lsquor; &sbquo;
“
&ldquo; &OpenCurlyDoubleQuote;
”
&rdquo; &rdquor; &CloseCurlyDoubleQuote;
„
&ldquor; &bdquo;
†
&dagger;
‡
&Dagger; &ddagger;
•
&bull; &bullet;
?
&nldr;
…
&hellip; &mldr;
‰
&permil;
?
&pertenk;
'
&prime;
"
&Prime;
?
&tprime;
`
&bprime; &backprime;
‹
&lsaquo;
›
&rsaquo;
?
&oline;
?
&caret;
?
&hybull;
/
&frasl;
?
&bsemi;
?
&qprime;
?
&MediumSpace;
?
&NoBreak;
?
&ApplyFunction; &af;
?
&InvisibleTimes; &it;
?
&InvisibleComma; &ic;
€
&euro;
?
&tdot; &TripleDot;
?
&DotDot;
C
&Copf; &complexes;
?
&incare;
g
&gscr;
H
&hamilt; &HilbertSpace; &Hscr;
H
&Hfr; &Poincareplane;
H
&quaternions; &Hopf;
h
&planckh;
?
&planck; &hbar; &plankv; &hslash;
I
&Iscr; &imagline;
I
&image; &Im; &imagpart; &Ifr;
L
&Lscr; &lagran; &Laplacetrf;
l
&ell;
N
&Nopf; &naturals;
?
&numero;
?
&copysr;
P
&weierp; &wp;
P
&Popf; &primes;
Q
&rationals; &Qopf;
R
&Rscr; &realine;
R
&real; &Re; &realpart; &Rfr;
R
&reals; &Ropf;
?
&rx;
™
&trade; &TRADE;
Z
&integers; &Zopf;
?
&ohm;
?
&mho;
Z
&Zfr; &zeetrf;
?
&iiota;
Å
&angst;
B
&bernou; &Bernoullis; &Bscr;
C
&Cfr; &Cayleys;
e
&escr;
E
&Escr; &expectation;
F
&Fscr; &Fouriertrf;
M
&phmmat; &Mellintrf; &Mscr;
o
&order; &orderof; &oscr;
?
&alefsym; &aleph;
?
&beth;
?
&gimel;
?
&daleth;
?
&CapitalDifferentialD; &DD;
?
&DifferentialD; &dd;
?
&ExponentialE; &exponentiale; &ee;
?
&ImaginaryI; &ii;
?
&frac13;
?
&frac23;
?
&frac15;
?
&frac25;
?
&frac35;
?
&frac45;
?
&frac16;
?
&frac56;
?
&frac18;
?
&frac38;
?
&frac58;
?
&frac78;
?
&larr; &leftarrow; &LeftArrow; &slarr; &ShortLeftArrow;
?
&uarr; &uparrow; &UpArrow; &ShortUpArrow;
?
&rarr; &rightarrow; &RightArrow; &srarr; &ShortRightArrow;
?
&darr; &downarrow; &DownArrow; &ShortDownArrow;
?
&harr; &leftrightarrow; &LeftRightArrow;
?
&varr; &updownarrow; &UpDownArrow;
?
&nwarr; &UpperLeftArrow; &nwarrow;
?
&nearr; &UpperRightArrow; &nearrow;
?
&searr; &searrow; &LowerRightArrow;
?
&swarr; &swarrow; &LowerLeftArrow;
?
&nlarr; &nleftarrow;
?
&nrarr; &nrightarrow;
?
&rarrw; &rightsquigarrow;
?
&Larr; &twoheadleftarrow;
?
&Uarr;
?
&Rarr; &twoheadrightarrow;
?
&Darr;
?
&larrtl; &leftarrowtail;
?
&rarrtl; &rightarrowtail;
?
&LeftTeeArrow; &mapstoleft;
?
&UpTeeArrow; &mapstoup;
?
&map; &RightTeeArrow; &mapsto;
?
&DownTeeArrow; &mapstodown;
?
&larrhk; &hookleftarrow;
?
&rarrhk; &hookrightarrow;
?
&larrlp; &looparrowleft;
?
&rarrlp; &looparrowright;
?
&harrw; &leftrightsquigarrow;
?
&nharr; &nleftrightarrow;
?
&lsh; &Lsh;
?
&rsh; &Rsh;
?
&ldsh;
?
&rdsh;
?
&crarr;
?
&cularr; &curvearrowleft;
?
&curarr; &curvearrowright;
?
&olarr; &circlearrowleft;
?
&orarr; &circlearrowright;
?
&lharu; &LeftVector; &leftharpoonup;
?
&lhard; &leftharpoondown; &DownLeftVector;
?
&uharr; &upharpoonright; &RightUpVector;
?
&uharl; &upharpoonleft; &LeftUpVector;
?
&rharu; &RightVector; &rightharpoonup;
?
&rhard; &rightharpoondown; &DownRightVector;
?
&dharr; &RightDownVector; &downharpoonright;
?
&dharl; &LeftDownVector; &downharpoonleft;
?
&rlarr; &rightleftarrows; &RightArrowLeftArrow;
?
&udarr; &UpArrowDownArrow;
?
&lrarr; &leftrightarrows; &LeftArrowRightArrow;
?
&llarr; &leftleftarrows;
?
&uuarr; &upuparrows;
?
&rrarr; &rightrightarrows;
?
&ddarr; &downdownarrows;
?
&lrhar; &ReverseEquilibrium; &leftrightharpoons;
?
&rlhar; &rightleftharpoons; &Equilibrium;
?
&nlArr; &nLeftarrow;
?
&nhArr; &nLeftrightarrow;
?
&nrArr; &nRightarrow;
?
&lArr; &Leftarrow; &DoubleLeftArrow;
?
&uArr; &Uparrow; &DoubleUpArrow;
?
&rArr; &Rightarrow; &Implies; &DoubleRightArrow;
?
&dArr; &Downarrow; &DoubleDownArrow;
?
&hArr; &Leftrightarrow; &DoubleLeftRightArrow; &iff;
?
&vArr; &Updownarrow; &DoubleUpDownArrow;
?
&nwArr;
?
&neArr;
?
&seArr;
?
&swArr;
?
&lAarr; &Lleftarrow;
?
&rAarr; &Rrightarrow;
?
&zigrarr;
?
&larrb; &LeftArrowBar;
?
&rarrb; &RightArrowBar;
?
&duarr; &DownArrowUpArrow;
?
&loarr;
?
&roarr;
?
&hoarr;
?
&forall; &ForAll;
?
&comp; &complement;
?
&part; &PartialD;
?
&exist; &Exists;
?
&nexist; &NotExists; &nexists;
Ø
&empty; &emptyset; &emptyv; &varnothing;
?
&nabla; &Del;
?
&isin; &isinv; &Element; &in;
?
&notin; &NotElement; &notinva;
?
&niv; &ReverseElement; &ni; &SuchThat;
?
&notni; &notniva; &NotReverseElement;
?
&prod; &Product;
?
&coprod; &Coproduct;
?
&sum; &Sum;
-
&minus;
±
&mnplus; &mp; &MinusPlus;
?
&plusdo; &dotplus;
\
&setmn; &setminus; &Backslash; &ssetmn; &smallsetminus;
*
&lowast;
°
&compfn; &SmallCircle;
v
&radic; &Sqrt;
?
&prop; &propto; &Proportional; &vprop; &varpropto;
8
&infin;
?
&angrt;
?
&ang; &angle;
?
&angmsd; &measuredangle;
?
&angsph;
|
&mid; &VerticalBar; &smid; &shortmid;
?
&nmid; &NotVerticalBar; &nsmid; &nshortmid;
?
&par; &parallel; &DoubleVerticalBar; &spar; &shortparallel;
?
&npar; &nparallel; &NotDoubleVerticalBar; &nspar; &nshortparallel;
?
&and; &wedge;
?
&or; &vee;
n
&cap;
?
&cup;
?
&int; &Integral;
?
&Int;
?
&tint; &iiint;
?
&conint; &oint; &ContourIntegral;
?
&Conint; &DoubleContourIntegral;
?
&Cconint;
?
&cwint;
?
&cwconint; &ClockwiseContourIntegral;
?
&awconint; &CounterClockwiseContourIntegral;
?
&there4; &therefore; &Therefore;
?
&becaus; &because; &Because;
:
&ratio;
?
&Colon; &Proportion;
?
&minusd; &dotminus;
?
&mDDot;
?
&homtht;
~
&sim; &Tilde; &thksim; &thicksim;
?
&bsim; &backsim;
?
&ac; &mstpos;
?
&acd;
?
&wreath; &VerticalTilde; &wr;
?
&nsim; &NotTilde;
?
&esim; &EqualTilde; &eqsim;
?
&sime; &TildeEqual; &simeq;
?
&nsime; &nsimeq; &NotTildeEqual;
?
&cong; &TildeFullEqual;
?
&simne;
?
&ncong; &NotTildeFullEqual;
˜
&asymp; &ap; &TildeTilde; &approx; &thkap; &thickapprox;
?
&nap; &NotTildeTilde; &napprox;
?
&ape; &approxeq;
?
&apid;
?
&bcong; &backcong;
?
&asympeq; &CupCap;
?
&bump; &HumpDownHump; &Bumpeq;
?
&bumpe; &HumpEqual; &bumpeq;
?
&esdot; &DotEqual; &doteq;
?
&eDot; &doteqdot;
?
&efDot; &fallingdotseq;
?
&erDot; &risingdotseq;
?
&colone; &coloneq; &Assign;
?
&ecolon; &eqcolon;
?
&ecir; &eqcirc;
?
&cire; &circeq;
?
&wedgeq;
?
&veeeq;
?
&trie; &triangleq;
?
&equest; &questeq;
?
&ne; &NotEqual;
=
&equiv; &Congruent;
?
&nequiv; &NotCongruent;
=
&le; &leq;
=
&ge; &GreaterEqual; &geq;
?
&lE; &LessFullEqual; &leqq;
?
&gE; &GreaterFullEqual; &geqq;
?
&lnE; &lneqq;
?
&gnE; &gneqq;
«
&Lt; &NestedLessLess; &ll;
»
&Gt; &NestedGreaterGreater; &gg;
?
&twixt; &between;
?
&NotCupCap;
?
&nlt; &NotLess; &nless;
?
&ngt; &NotGreater; &ngtr;
?
&nle; &NotLessEqual; &nleq;
?
&nge; &NotGreaterEqual; &ngeq;
?
&lsim; &LessTilde; &lesssim;
?
&gsim; &gtrsim; &GreaterTilde;
?
&nlsim; &NotLessTilde;
?
&ngsim; &NotGreaterTilde;
?
&lg; &lessgtr; &LessGreater;
?
&gl; &gtrless; &GreaterLess;
?
&ntlg; &NotLessGreater;
?
&ntgl; &NotGreaterLess;
?
&pr; &Precedes; &prec;
?
&sc; &Succeeds; &succ;
?
&prcue; &PrecedesSlantEqual; &preccurlyeq;
?
&sccue; &SucceedsSlantEqual; &succcurlyeq;
?
&prsim; &precsim; &PrecedesTilde;
?
&scsim; &succsim; &SucceedsTilde;
?
&npr; &nprec; &NotPrecedes;
?
&nsc; &nsucc; &NotSucceeds;
?
&sub; &subset;
?
&sup; &supset; &Superset;
?
&nsub;
?
&nsup;
?
&sube; &SubsetEqual; &subseteq;
?
&supe; &supseteq; &SupersetEqual;
?
&nsube; &nsubseteq; &NotSubsetEqual;
?
&nsupe; &nsupseteq; &NotSupersetEqual;
?
&subne; &subsetneq;
?
&supne; &supsetneq;
?
&cupdot;
?
&uplus; &UnionPlus;
?
&sqsub; &SquareSubset; &sqsubset;
?
&sqsup; &SquareSuperset; &sqsupset;
?
&sqsube; &SquareSubsetEqual; &sqsubseteq;
?
&sqsupe; &SquareSupersetEqual; &sqsupseteq;
?
&sqcap; &SquareIntersection;
?
&sqcup; &SquareUnion;
?
&oplus; &CirclePlus;
?
&ominus; &CircleMinus;
?
&otimes; &CircleTimes;
?
&osol;
?
&odot; &CircleDot;
?
&ocir; &circledcirc;
?
&oast; &circledast;
?
&odash; &circleddash;
?
&plusb; &boxplus;
?
&minusb; &boxminus;
?
&timesb; &boxtimes;
?
&sdotb; &dotsquare;
?
&vdash; &RightTee;
?
&dashv; &LeftTee;
?
&top; &DownTee;
?
&bottom; &bot; &perp; &UpTee;
?
&models;
?
&vDash; &DoubleRightTee;
?
&Vdash;
?
&Vvdash;
?
&VDash;
?
&nvdash;
?
&nvDash;
?
&nVdash;
?
&nVDash;
?
&prurel;
?
&vltri; &vartriangleleft; &LeftTriangle;
?
&vrtri; &vartriangleright; &RightTriangle;
?
&ltrie; &trianglelefteq; &LeftTriangleEqual;
?
&rtrie; &trianglerighteq; &RightTriangleEqual;
?
&origof;
?
&imof;
?
&mumap; &multimap;
?
&hercon;
?
&intcal; &intercal;
?
&veebar;
?
&barvee;
?
&angrtvb;
?
&lrtri;
?
&xwedge; &Wedge; &bigwedge;
?
&xvee; &Vee; &bigvee;
?
&xcap; &Intersection; &bigcap;
?
&xcup; &Union; &bigcup;
?
&diam; &diamond; &Diamond;
·
&sdot;
?
&sstarf; &Star;
?
&divonx; &divideontimes;
?
&bowtie;
?
&ltimes;
?
&rtimes;
?
&lthree; &leftthreetimes;
?
&rthree; &rightthreetimes;
?
&bsime; &backsimeq;
?
&cuvee; &curlyvee;
?
&cuwed; &curlywedge;
?
&Sub; &Subset;
?
&Sup; &Supset;
?
&Cap;
?
&Cup;
?
&fork; &pitchfork;
?
&epar;
?
&ltdot; &lessdot;
?
&gtdot; &gtrdot;
?
&Ll;
?
&Gg; &ggg;
?
&leg; &LessEqualGreater; &lesseqgtr;
?
&gel; &gtreqless; &GreaterEqualLess;
?
&cuepr; &curlyeqprec;
?
&cuesc; &curlyeqsucc;
?
&nprcue; &NotPrecedesSlantEqual;
?
&nsccue; &NotSucceedsSlantEqual;
?
&nsqsube; &NotSquareSubsetEqual;
?
&nsqsupe; &NotSquareSupersetEqual;
?
&lnsim;
?
&gnsim;
?
&prnsim; &precnsim;
?
&scnsim; &succnsim;
?
&nltri; &ntriangleleft; &NotLeftTriangle;
?
&nrtri; &ntriangleright; &NotRightTriangle;
?
&nltrie; &ntrianglelefteq; &NotLeftTriangleEqual;
?
&nrtrie; &ntrianglerighteq; &NotRightTriangleEqual;
?
&vellip;
?
&ctdot;
?
&utdot;
?
&dtdot;
?
&disin;
?
&isinsv;
?
&isins;
?
&isindot;
?
&notinvc;
?
&notinvb;
?
&isinE;
?
&nisd;
?
&xnis;
?
&nis;
?
&notnivc;
?
&notnivb;
?
&barwed; &barwedge;
?
&Barwed; &doublebarwedge;
?
&lceil; &LeftCeiling;
?
&rceil; &RightCeiling;
?
&lfloor; &LeftFloor;
?
&rfloor; &RightFloor;
?
&drcrop;
?
&dlcrop;
?
&urcrop;
?
&ulcrop;
¬
&bnot;
?
&profline;
?
&profsurf;
?
&telrec;
?
&target;
?
&ulcorn; &ulcorner;
?
&urcorn; &urcorner;
?
&dlcorn; &llcorner;
?
&drcorn; &lrcorner;
?
&frown; &sfrown;
?
&smile; &ssmile;
?
&cylcty;
?
&profalar;
?
&topbot;
?
&ovbar;
?
&solbar;
?
&angzarr;
?
&lmoust; &lmoustache;
?
&rmoust; &rmoustache;
?
&tbrk; &OverBracket;
?
&bbrk; &UnderBracket;
?
&bbrktbrk;
?
&OverParenthesis;
?
&UnderParenthesis;
?
&OverBrace;
?
&UnderBrace;
?
&trpezium;
?
&elinters;
?
&blank;
?
&oS; &circledS;
-
&boxh; &HorizontalLine;
¦
&boxv;
+
&boxdr;
+
&boxdl;
+
&boxur;
+
&boxul;
+
&boxvr;
¦
&boxvl;
-
&boxhd;
-
&boxhu;
+
&boxvh;
-
&boxH;
¦
&boxV;
+
&boxdR;
+
&boxDr;
+
&boxDR;
+
&boxdL;
+
&boxDl;
+
&boxDL;
+
&boxuR;
+
&boxUr;
+
&boxUR;
+
&boxuL;
+
&boxUl;
+
&boxUL;
¦
&boxvR;
¦
&boxVr;
¦
&boxVR;
¦
&boxvL;
¦
&boxVl;
¦
&boxVL;
-
&boxHd;
-
&boxhD;
-
&boxHD;
-
&boxHu;
-
&boxhU;
-
&boxHU;
+
&boxvH;
+
&boxVh;
+
&boxVH;
¯
&uhblk;
_
&lhblk;
¦
&block;
¦
&blk14;
¦
&blk12;
¦
&blk34;
?
&squ; &square; &Square;
?
&squf; &squarf; &blacksquare; &FilledVerySmallSquare;
?
&EmptyVerySmallSquare;
?
&rect;
?
&marker;
?
&fltns;
?
&xutri; &bigtriangleup;
?
&utrif; &blacktriangle;
?
&utri; &triangle;
?
&rtrif; &blacktriangleright;
?
&rtri; &triangleright;
?
&xdtri; &bigtriangledown;
?
&dtrif; &blacktriangledown;
?
&dtri; &triangledown;
?
&ltrif; &blacktriangleleft;
?
&ltri; &triangleleft;
?
&loz; &lozenge;
?
&cir;
?
&tridot;
?
&xcirc; &bigcirc;
?
&ultri;
?
&urtri;
?
&lltri;
?
&EmptySmallSquare;
?
&FilledSmallSquare;
?
&starf; &bigstar;
?
&star;
?
&phone;
?
&female;
?
&male;
?
&spades; &spadesuit;
?
&clubs; &clubsuit;
?
&hearts; &heartsuit;
?
&diams; &diamondsuit;
?
&sung;
?
&flat;
?
&natur; &natural;
?
&sharp;
?
&check; &checkmark;
?
&cross;
?
&malt; &maltese;
?
&sext;
|
&VerticalSeparator;
?
&lbbrk;
?
&rbbrk;
?
&lobrk; &LeftDoubleBracket;
?
&robrk; &RightDoubleBracket;
?
&lang; &LeftAngleBracket; &langle;
?
&rang; &RightAngleBracket; &rangle;
?
&Lang;
?
&Rang;
?
&loang;
?
&roang;
?
&xlarr; &longleftarrow; &LongLeftArrow;
?
&xrarr; &longrightarrow; &LongRightArrow;
?
&xharr; &longleftrightarrow; &LongLeftRightArrow;
?
&xlArr; &Longleftarrow; &DoubleLongLeftArrow;
?
&xrArr; &Longrightarrow; &DoubleLongRightArrow;
?
&xhArr; &Longleftrightarrow; &DoubleLongLeftRightArrow;
?
&xmap; &longmapsto;
?
&dzigrarr;
?
&nvlArr;
?
&nvrArr;
?
&nvHarr;
?
&Map;
?
&lbarr;
?
&rbarr; &bkarow;
?
&lBarr;
?
&rBarr; &dbkarow;
?
&RBarr; &drbkarow;
?
&DDotrahd;
?
&UpArrowBar;
?
&DownArrowBar;
?
&Rarrtl;
?
&latail;
?
&ratail;
?
&lAtail;
?
&rAtail;
?
&larrfs;
?
&rarrfs;
?
&larrbfs;
?
&rarrbfs;
?
&nwarhk;
?
&nearhk;
?
&searhk; &hksearow;
?
&swarhk; &hkswarow;
?
&nwnear;
?
&nesear; &toea;
?
&seswar; &tosa;
?
&swnwar;
?
&rarrc;
?
&cudarrr;
?
&ldca;
?
&rdca;
?
&cudarrl;
?
&larrpl;
?
&curarrm;
?
&cularrp;
?
&rarrpl;
?
&harrcir;
?
&Uarrocir;
?
&lurdshar;
?
&ldrushar;
?
&LeftRightVector;
?
&RightUpDownVector;
?
&DownLeftRightVector;
?
&LeftUpDownVector;
?
&LeftVectorBar;
?
&RightVectorBar;
?
&RightUpVectorBar;
?
&RightDownVectorBar;
?
&DownLeftVectorBar;
?
&DownRightVectorBar;
?
&LeftUpVectorBar;
?
&LeftDownVectorBar;
?
&LeftTeeVector;
?
&RightTeeVector;
?
&RightUpTeeVector;
?
&RightDownTeeVector;
?
&DownLeftTeeVector;
?
&DownRightTeeVector;
?
&LeftUpTeeVector;
?
&LeftDownTeeVector;
?
&lHar;
?
&uHar;
?
&rHar;
?
&dHar;
?
&luruhar;
?
&ldrdhar;
?
&ruluhar;
?
&rdldhar;
?
&lharul;
?
&llhard;
?
&rharul;
?
&lrhard;
?
&udhar; &UpEquilibrium;
?
&duhar; &ReverseUpEquilibrium;
?
&RoundImplies;
?
&erarr;
?
&simrarr;
?
&larrsim;
?
&rarrsim;
?
&rarrap;
?
&ltlarr;
?
&gtrarr;
?
&subrarr;
?
&suplarr;
?
&lfisht;
?
&rfisht;
?
&ufisht;
?
&dfisht;
?
&lopar;
?
&ropar;
?
&lbrke;
?
&rbrke;
?
&lbrkslu;
?
&rbrksld;
?
&lbrksld;
?
&rbrkslu;
?
&langd;
?

Not fully, pls track the link for fully document.

"google is not defined" when using Google Maps V3 in Firefox remotely

instead of this

var defaultLocation = new google.maps.LatLng(lat, lng);

use this

var defaultLocation = new window.google.maps.LatLng(lat, lng);

and this worked for me.

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Often used with/as a part of OOAD and business modeling. The definition by Neil is correct, but it is basically identical to MVC, but just abstracted for the business. The "Good summary" is well done so I will not copy it here as it is not my work, more detailed but inline with Neil's bullet points.

Good summary - Conceito: Entity-Control-Boundary Pattern

OOAD

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

How to change package name in flutter?

Change App Package Name easily using change_app_package_name package

just add the above package in dev dependencies

dev_dependencies:
  flutter_test:
    sdk: flutter
  change_app_package_name: ^0.1.2

and run the following command, replace "com.new.package.name" with your new package name

flutter pub run change_app_package_name:main com.new.package.name

Package Link on Pub Dev

screenshot of Package

How to get a value from a Pandas DataFrame and not the index and object type

Use the values attribute to return the values as a np array and then use [0] to get the first value:

In [4]:
df.loc[df.Letters=='C','Letters'].values[0]

Out[4]:
'C'

EDIT

I personally prefer to access the columns using subscript operators:

df.loc[df['Letters'] == 'C', 'Letters'].values[0]

This avoids issues where the column names can have spaces or dashes - which mean that accessing using ..

Javascript onHover event

How about something like this?

<html>
<head>
<script type="text/javascript">

var HoverListener = {
  addElem: function( elem, callback, delay )
  {
    if ( delay === undefined )
    {
      delay = 1000;
    }

    var hoverTimer;

    addEvent( elem, 'mouseover', function()
    {
      hoverTimer = setTimeout( callback, delay );
    } );

    addEvent( elem, 'mouseout', function()
    {
      clearTimeout( hoverTimer );
    } );
  }
}

function tester()
{
  alert( 'hi' );
}

//  Generic event abstractor
function addEvent( obj, evt, fn )
{
  if ( 'undefined' != typeof obj.addEventListener )
  {
    obj.addEventListener( evt, fn, false );
  }
  else if ( 'undefined' != typeof obj.attachEvent )
  {
    obj.attachEvent( "on" + evt, fn );
  }
}

addEvent( window, 'load', function()
{
  HoverListener.addElem(
      document.getElementById( 'test' )
    , tester 
  );
  HoverListener.addElem(
      document.getElementById( 'test2' )
    , function()
      {
        alert( 'Hello World!' );
      }
    , 2300
  );
} );

</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>

Does Android support near real time push notification?

Google recently(18May2016) announced that Firebase is now it's unified platform for mobile developers including near real time push notifications.It is also multi-platform :

The company now offers all Firebase users free and unlimited notifications with support for iOS, Android and the Web.

source

Format cell color based on value in another sheet and cell

You can also do this with named ranges so you don't have to copy the cells from Sheet1 to Sheet2:

  1. Define a named range, say Sheet1Vals for the column that has the values on which you want to base your condition. You can define a new named range by using the Insert\Name\Define... menu item. Type in your name, then use the cell browser in the Refers to box to select the cells you want in the range. If the range will change over time (add or remove rows) you can use this formula instead of selecting the cells explicitly:

    =OFFSET('SheetName'!$COL$ROW,0,0,COUNTA('SheetName'!$COL:$COL)).

    Add a -1 before the last ) if the column has a header row.

  2. Define a named range, say Sheet2Vals for the column that has the values you want to conditionally format.

  3. Use the Conditional Formatting dialog to create your conditions. Specify Formula Is in the dropdown, then put this for the formula:

    =INDEX(Sheet1Vals, MATCH([FirstCellInRange],Sheet2Vals))=[Condition]

    where [FirstCellInRange] is the address of the cell you want to format and [Condition] is the value your checking.

For example, if my conditions in Sheet1 have the values of 1, 2 and 3 and the column I'm formatting is column B in Sheet2 then my conditional formats would be something like:

=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=1
=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=2
=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=3

You can then use the format painter to copy these formats to the rest of the cells.

What is the best way to call a script from another script?

You should not be doing this. Instead, do:

test1.py:

 def print_test():
      print "I am a test"
      print "see! I do nothing productive."

service.py

#near the top
from test1 import print_test
#lots of stuff here
print_test()

jQuery animate margin top

You had MarginTop instead of marginTop

http://jsfiddle.net/kX7b6/1/

It is also very buggy if you leave mid animation, here is update:

http://jsfiddle.net/kX7b6/3/

Note I changed it to mouseenter and mouseleave because I don't think the intention was to cancel the animation when you hover over the red or green area.

How to set Default Controller in asp.net MVC 4 & MVC 5

Set below code in RouteConfig.cs in App_Start folder

public static void RegisterRoutes(RouteCollection routes)
{
 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 routes.MapRoute(
 name: "Default",
 url: "{controller}/{action}/{id}",
 defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional });
}

IF still not working then do below steps

Second Way : You simple follow below steps,

1) Right click on your Project

2) Select Properties

3) Select Web option and then Select Specific Page (Controller/View) and then set your login page

Here, Account is my controller and Login is my action method (saved in Account Controller)

Please take a look attachedenter image description here screenshot.

Simple http post example in Objective-C?

Here i'm adding sample code for http post print response and parsing as JSON if possible, it will handle everything async so your GUI will be refreshing just fine and will not freeze at all - which is important to notice.

//POST DATA
NSString *theBody = [NSString stringWithFormat:@"parameter=%@",YOUR_VAR_HERE];
NSData *bodyData = [theBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//URL CONFIG
NSString *serverURL = @"https://your-website-here.com";
NSString *downloadUrl = [NSString stringWithFormat:@"%@/your-friendly-url-here/json",serverURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: downloadUrl]];
//POST DATA SETUP
[request setHTTPMethod:@"POST"];
[request setHTTPBody:bodyData];
//DEBUG MESSAGE
NSLog(@"Trying to call ws %@",downloadUrl);
//EXEC CALL
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {
        NSLog(@"Download Error:%@",error.description);
    }
    if (data) {

        //
        // THIS CODE IS FOR PRINTING THE RESPONSE
        //
        NSString *returnString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
        NSLog(@"Response:%@",returnString);

        //PARSE JSON RESPONSE
        NSDictionary *json_response = [NSJSONSerialization JSONObjectWithData:data
                                                                      options:0
                                                                        error:NULL];

        if ( json_response ) {
            if ( [json_response isKindOfClass:[NSDictionary class]] ) {
                // do dictionary things
                for ( NSString *key in [json_response allKeys] ) {
                    NSLog(@"%@: %@", key, json_response[key]);
                }
            }
            else if ( [json_response isKindOfClass:[NSArray class]] ) {
                NSLog(@"%@",json_response);
            }
        }
        else {
            NSLog(@"Error serializing JSON: %@", error);
            NSLog(@"RAW RESPONSE: %@",data);
            NSString *returnString2 = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
            NSLog(@"Response:%@",returnString2);
        }
    }
}];

Hope this helps!

Custom Cell Row Height setting in storyboard is not responding

If you want to set a static row height, you can do something like this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}

How do I turn off PHP Notices?

For PHP code:

<?php
error_reporting(E_ALL & ~E_NOTICE);

For php.ini config:

error_reporting = E_ALL & ~E_NOTICE

Check if string contains only letters in javascript

try to add \S at your pattern

^[A-Za-z]\S*$

An invalid XML character (Unicode: 0xc) was found

There are a few characters that are dissallowed in XML documents, even when you encapsulate data in CDATA-blocks.

If you generated the document you will need to entity encode it or strip it out. If you have an errorneous document, you should strip away these characters before trying to parse it.

See dolmens answer in this thread: Invalid Characters in XML

Where he links to this article: http://www.w3.org/TR/xml/#charsets

Basically, all characters below 0x20 is disallowed, except 0x9 (TAB), 0xA (CR?), 0xD (LF?)

jquery clone div and append it after specific div

You can use clone, and then since each div has a class of car_well you can use insertAfter to insert after the last div.

$("#car2").clone().insertAfter("div.car_well:last");

Copying files into the application folder at compile time

You can use the PostBuild event of the project. After the build is completed, you can run a DOS batch file and copy the desired files to your desired folder.

How to make a link open multiple pages when clicked

HTML:

<a href="#" class="yourlink">Click Here</a>

JS:

$('a.yourlink').click(function(e) {
    e.preventDefault();
    window.open('http://yoururl1.com');
    window.open('http://yoururl2.com');
});

window.open also can take additional parameters. See them here: http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

You should also know that window.open is sometimes blocked by popup blockers and/or ad-filters.

Addition from Paul below: This approach also places a dependency on JavaScript being enabled. Not typically a good idea, but sometimes necessary.

Can't access to HttpContext.Current

Have you included the System.Web assembly in the application?

using System.Web;

If not, try specifying the System.Web namespace, for example:

 System.Web.HttpContext.Current

Understanding The Modulus Operator %

(This explanation is only for positive numbers since it depends on the language otherwise)

Definition

The Modulus is the remainder of the euclidean division of one number by another. % is called the modulo operation.

For instance, 9 divided by 4 equals 2 but it remains 1. Here, 9 / 4 = 2 and 9 % 4 = 1.

Euclidean Division

In your example: 5 divided by 7 gives 0 but it remains 5 (5 % 7 == 5).

Calculation

The modulo operation can be calculated using this equation:

a % b = a - floor(a / b) * b
  • floor(a / b) represents the number of times you can divide a by b
  • floor(a / b) * b is the amount that was successfully shared entirely
  • The total (a) minus what was shared equals the remainder of the division

Applied to the last example, this gives:

5 % 7 = 5 - floor(5 / 7) * 7 = 5

Modular Arithmetic

That said, your intuition was that it could be -2 and not 5. Actually, in modular arithmetic, -2 = 5 (mod 7) because it exists k in Z such that 7k - 2 = 5.

You may not have learned modular arithmetic, but you have probably used angles and know that -90° is the same as 270° because it is modulo 360. It's similar, it wraps! So take a circle, and say that it's perimeter is 7. Then you read where is 5. And if you try with 10, it should be at 3 because 10 % 7 is 3.

Open a URL in a new tab (and not a new window)

How about creating an <a> with _blank as target attribute value and the url as href, with style display:hidden with a a children element? Then add to the DOM and then trigger the click event on a children element.

UPDATE

That doesn't work. The browser prevents the default behaviour. It could be triggered programmatically, but it doesn't follow the default behaviour.

Check and see for yourself: http://jsfiddle.net/4S4ET/

Quickly reading very large tables as dataframes

An update, several years later

This answer is old, and R has moved on. Tweaking read.table to run a bit faster has precious little benefit. Your options are:

  1. Using vroom from the tidyverse package vroom for importing data from csv/tab-delimited files directly into an R tibble. See Hector's answer.

  2. Using fread in data.table for importing data from csv/tab-delimited files directly into R. See mnel's answer.

  3. Using read_table in readr (on CRAN from April 2015). This works much like fread above. The readme in the link explains the difference between the two functions (readr currently claims to be "1.5-2x slower" than data.table::fread).

  4. read.csv.raw from iotools provides a third option for quickly reading CSV files.

  5. Trying to store as much data as you can in databases rather than flat files. (As well as being a better permanent storage medium, data is passed to and from R in a binary format, which is faster.) read.csv.sql in the sqldf package, as described in JD Long's answer, imports data into a temporary SQLite database and then reads it into R. See also: the RODBC package, and the reverse depends section of the DBI package page. MonetDB.R gives you a data type that pretends to be a data frame but is really a MonetDB underneath, increasing performance. Import data with its monetdb.read.csv function. dplyr allows you to work directly with data stored in several types of database.

  6. Storing data in binary formats can also be useful for improving performance. Use saveRDS/readRDS (see below), the h5 or rhdf5 packages for HDF5 format, or write_fst/read_fst from the fst package.


The original answer

There are a couple of simple things to try, whether you use read.table or scan.

  1. Set nrows=the number of records in your data (nmax in scan).

  2. Make sure that comment.char="" to turn off interpretation of comments.

  3. Explicitly define the classes of each column using colClasses in read.table.

  4. Setting multi.line=FALSE may also improve performance in scan.

If none of these thing work, then use one of the profiling packages to determine which lines are slowing things down. Perhaps you can write a cut down version of read.table based on the results.

The other alternative is filtering your data before you read it into R.

Or, if the problem is that you have to read it in regularly, then use these methods to read the data in once, then save the data frame as a binary blob with save saveRDS, then next time you can retrieve it faster with load readRDS.

Installation of SQL Server Business Intelligence Development Studio

This worked for me:

Start /wait setup.exe /qb  ADDLOCAL=SQL_DTS,Client_Components,Connectivity,SQL_Tools90,SQL_WarehouseDevWorkbench,SQLXML,Tools_Legacy,SQL_Documentation,SQL_BooksOnline

Based off this TechNet Article:

https://technet.microsoft.com/en-us/library/ms144259(v=sql.90).aspx

Preferred way of loading resources in Java

I tried a lot of ways and functions that suggested above, but they didn't work in my project. Anyway I have found solution and here it is:

try {
    InputStream path = this.getClass().getClassLoader().getResourceAsStream("img/left-hand.png");
    img = ImageIO.read(path);
} catch (IOException e) {
    e.printStackTrace();
}

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

I had similar issue with <input type="range" /> and I solved it with

-webkit-tap-highlight-color: transparent;

_x000D_
_x000D_
input[type="range"]{
  -webkit-tap-highlight-color: transparent;
}
_x000D_
 <input type="range" id="volume" name="demo"
         min="0" max="11">
  <label for="volume">Demo</label>
_x000D_
_x000D_
_x000D_

HTML5 Pre-resize images before uploading

fd.append("image", dataurl);

This will not work. On PHP side you can not save file with this.

Use this code instead:

var blobBin = atob(dataurl.split(',')[1]);
var array = [];
for(var i = 0; i < blobBin.length; i++) {
  array.push(blobBin.charCodeAt(i));
}
var file = new Blob([new Uint8Array(array)], {type: 'image/png', name: "avatar.png"});

fd.append("image", file); // blob file

How to return Json object from MVC controller to view

When you do return Json(...) you are specifically telling MVC not to use a view, and to serve serialized JSON data. Your browser opens a download dialog because it doesn't know what to do with this data.

If you instead want to return a view, just do return View(...) like you normally would:

var dictionary = listLocation.ToDictionary(x => x.label, x => x.value);
return View(new { Values = listLocation });

Then in your view, simply encode your data as JSON and assign it to a JavaScript variable:

<script>
    var values = @Html.Raw(Json.Encode(Model.Values));
</script>

EDIT

Here is a bit more complete sample. Since I don't have enough context from you, this sample will assume a controller Foo, an action Bar, and a view model FooBarModel. Additionally, the list of locations is hardcoded:

Controllers/FooController.cs

public class FooController : Controller
{
    public ActionResult Bar()
    {
        var locations = new[]
        {
            new SelectListItem { Value = "US", Text = "United States" },
            new SelectListItem { Value = "CA", Text = "Canada" },
            new SelectListItem { Value = "MX", Text = "Mexico" },
        };

        var model = new FooBarModel
        {
            Locations = locations,
        };

        return View(model);
    }
}

Models/FooBarModel.cs

public class FooBarModel
{
    public IEnumerable<SelectListItem> Locations { get; set; }
}

Views/Foo/Bar.cshtml

@model MyApp.Models.FooBarModel

<script>
    var locations = @Html.Raw(Json.Encode(Model.Locations));
</script>

By the looks of your error message, it seems like you are mixing incompatible types (i.e. Ported_LI.Models.Locatio??n and MyApp.Models.Location) so, to recap, make sure the type sent from the controller action side match what is received from the view. For this sample in particular, new FooBarModel in the controller matches @model MyApp.Models.FooBarModel in the view.

How can I download a file from a URL and save it in Rails?

Check out Net::HTTP in the standard library. The documentation provides several examples on how to download documents using HTTP.

How does a hash table work?

It's even simpler than that.

A hashtable is nothing more than an array (usually sparse one) of vectors which contain key/value pairs. The maximum size of this array is typically smaller than the number of items in the set of possible values for the type of data being stored in the hashtable.

The hash algorithm is used to generate an index into that array based on the values of the item that will be stored in the array.

This is where storing vectors of key/value pairs in the array come in. Because the set of values that can be indexes in the array is typically smaller than the number of all possible values that the type can have, it is possible that your hash algorithm is going to generate the same value for two separate keys. A good hash algorithm will prevent this as much as possible (which is why it is relegated to the type usually because it has specific information which a general hash algorithm can't possibly know), but it's impossible to prevent.

Because of this, you can have multiple keys that will generate the same hash code. When that happens, the items in the vector are iterated through, and a direct comparison is done between the key in the vector and the key that is being looked up. If it is found, great and the value associated with the key is returned, otherwise, nothing is returned.

How do I mock a class without an interface?

If worse comes to worse, you can create an interface and adapter pair. You would change all uses of ConcreteClass to use the interface instead, and always pass the adapter instead of the concrete class in production code.

The adapter implements the interface, so the mock can also implement the interface.

It's more scaffolding than just making a method virtual or just adding an interface, but if you don't have access to the source for the concrete class it can get you out of a bind.

Datetime in where clause

Use a convert function to get all entries for a particular day.

Select * from tblErrorLog where convert(date,errorDate,101) = '12/20/2008'

See CAST and CONVERT for more info

Are there any standard exit status codes in Linux?

Standard Unix exit codes are defined by sysexits.h, as another poster mentioned. The same exit codes are used by portable libraries such as Poco - here is a list of them:

http://pocoproject.org/docs/Poco.Util.Application.html#16218

A signal 11 is a SIGSEGV (segment violation) signal, which is different from a return code. This signal is generated by the kernel in response to a bad page access, which causes the program to terminate. A list of signals can be found in the signal man page (run "man signal").

How can I install a local gem?

Yup, when you do gem install, it will search the current directory first, so if your .gem file is there, it will pick it up. I found it on the gem reference, which you may find handy as well:

gem install will install the named gem. It will attempt a local installation (i.e. a .gem file in the current directory), and if that fails, it will attempt to download and install the most recent version of the gem you want.

Detecting a mobile browser

This is just an es6 port of the accepted answer that I'm using in my project. Note that this also includes tablets.

export const isMobile = () => {
  const vendor = navigator.userAgent || navigator.vendor || window.opera;

  return !!(
    /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(
      vendor
    ) ||
    /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(
      vendor.substr(0, 4)
    )
  );
};

How to add a button dynamically using jquery

Try this:

<script type="text/javascript">

function test()
{
    if($('input#field').length==0)
    {
       $('<input type="button" id="field"/>').appendTo('body');
     }
}
</script>

Dynamically updating css in Angular 2

This should do it:

<div class="home-component" 
     [style.width]="width + 'px'" 
     [style.height]="height + 'px'">Some stuff in this div</div>

How to put a tooltip on a user-defined function

A lot of dancing around the answer. You can add the UDF context help, but you have to export the Module and edit the contents in a text editor, then re-import it to VBA. Here's the example from Chip Pearson: Adding Code Attributes

How to display length of filtered ng-repeat data

Here is worked example See on Plunker

  <body ng-controller="MainCtrl">
    <input ng-model="search" type="text">
    <br>
    Showing {{data.length}} Persons; <br>
    Filtered {{counted}}
    <ul>
      <li ng-repeat="person in data | filter:search">
        {{person.name}}
      </li>
    </ul>
  </body>

<script> 
var app = angular.module('angularjs-starter', [])

app.controller('MainCtrl', function($scope, $filter) {
  $scope.data = [
    {
      "name": "Jim", "age" : 21
    }, {
      "name": "Jerry", "age": 26
    }, {
      "name": "Alex",  "age" : 25
    }, {
      "name": "Max", "age": 22
    }
  ];

  $scope.counted = $scope.data.length; 
  $scope.$watch("search", function(query){
    $scope.counted = $filter("filter")($scope.data, query).length;
  });
});

How to send an email from JavaScript

JavaScript can't send email from a web browser. However, stepping back from the solution you've already tried to implement, you can do something that meets the original requirement:

send an email without refreshing the page

You can use JavaScript to construct the values that the email will need and then make an AJAX request to a server resource that actually sends the email. (I don't know what server-side languages/technologies you're using, so that part is up to you.)

If you're not familiar with AJAX, a quick Google search will give you a lot of information. Generally you can get it up and running quickly with jQuery's $.ajax() function. You just need to have a page on the server that can be called in the request.

find path of current folder - cmd

for /f "delims=" %%i in ("%0") do set "curpath=%%~dpi"
echo "%curpath%"

or

echo "%cd%"

The double quotes are needed if the path contains any & characters.

Upload file to SFTP using PowerShell

There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.

Here is an example using Posh-SSH:

# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)

# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'

# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'

# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH

# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential

# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath

#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }

# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath

Some additional notes:

  • You'll have to download the Posh-SSH module which you can install to your user module directory (e.g. C:\Users\jon_dechiro\Documents\WindowsPowerShell\Modules) and just load using the name or put it anywhere and load it like I have in the code above.
  • If having the credentials in the script is not acceptable you'll have to use a credential file. If you need help with that I can update with some details or point you to some links.
  • Change the paths, IPs, etc. as needed.

That should give you a decent starting point.

onSaveInstanceState () and onRestoreInstanceState ()

I think this thread was quite old. I just mention another case, that onSaveInstanceState() will also be called, is when you call Activity.moveTaskToBack(boolean nonRootActivity).

How to Publish Web with msbuild?

Using the deployment profiles introduced in VS 2012, you can publish with the following command line:

msbuild MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=<profile-name> /p:Password=<insert-password> /p:VisualStudioVersion=11.0

For more information on the parameters see this.

The values for the /p:VisualStudioVersion parameter depend on your version of Visual Studio. Wikipedia has a table of Visual Studio releases and their versions.

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

I am assuming you're using Chrome.

If so, the root problem is a certificate mismatch / expired certificate.

You can see this for yourself in the code here.

Note in particular the use of the very constant you reference in the code on line 48 of the C++ file I sent you:

 case net::ERR_INSECURE_RESPONSE:

The current version of this file is here. The error status ERR_INSECURE_RESPONSE may not any longer be on line 48 but the error code still exists in the SSL certificate portion of the code.

Note: Make sure to use the hostname which is listed in the SSL certificate, chrome automatically switches to the right hostname if you are browsing but not when using javascript.

TypeError: unhashable type: 'list' when using built-in set function

Sets remove duplicate items. In order to do that, the item can't change while in the set. Lists can change after being created, and are termed 'mutable'. You cannot put mutable things in a set.

Lists have an unmutable equivalent, called a 'tuple'. This is how you would write a piece of code that took a list of lists, removed duplicate lists, then sorted it in reverse.

result = sorted(set(map(tuple, my_list)), reverse=True)

Additional note: If a tuple contains a list, the tuple is still considered mutable.

Some examples:

>>> hash( tuple() )
3527539
>>> hash( dict() )

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    hash( dict() )
TypeError: unhashable type: 'dict'
>>> hash( list() )

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    hash( list() )
TypeError: unhashable type: 'list'

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

I believe for windows you may use: os.execute("ping 1.1.1.1 /n 1 /w <time in milliseconds> >nul as a simple timer. (remove the "<>" when inserting the time in milliseconds) (there is a space between the rest of the code and >nul)

How to paste yanked text into the Vim command line

For context, this information comes from out-of-the-box, no plugins, no .vimrc Vim 7.4 behavior in Linux Mint with the default options.

You can always select text with the mouse (or using V or v and placing the selection in the "* register), and paste it into the command line with Shift + Ctrl + v.

Typing Ctrl + r in the command line will cause a prompt for a register name. so typing :CTRL-r* will place the content register * into the command line. It will paste any register, not just "*. See :help c_CTRL-R.

Furthermore, the middle mouse button will paste into the command line.

See :help->quote-plus for a description of the how X Window deals with selection. Even in a plain, out-of-the-box Vim (again, in Vim 7.4 in Linux Mint, anyway), any selection made with the left mouse button can be pasted in the command line with the middle mouse button.

In addition, the middle mouse button will also paste text selected in Vim into many other X Window applications, even GUI ones (for example, Firefox and Thunderbird) and pasting text into the command line is also possible where the text was selected from other apps.

See :help->x11-selection for addl information.

tl;dr

Try the :CTRL-r approach first, and then use Shift + Ctrl + v or the middle mouse button if you need something else.

It is conceded that it can be confusing.

How do I pull my project from github?

You Can do by Two ways,

1. Cloning the Remote Repo to your Local host

example: git clone https://github.com/user-name/repository.git

2. Pulling the Remote Repo to your Local host

First you have to create a git local repo by,

example: git init or git init repo-name then, git pull https://github.com/user-name/repository.git

That's all, All commits and branch in the remote repo now available in the local repository of your computer.

Happy Coding, cheers -:)

Sticky and NON-Sticky sessions

I've made an answer with some more details here : https://stackoverflow.com/a/11045462/592477

Or you can read it there ==>

When you use loadbalancing it means you have several instances of tomcat and you need to divide loads.

  • If you're using session replication without sticky session : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send some of these requests to the first tomcat instance, and send some other of these requests to the secondth instance, and other to the third.
  • If you're using sticky session without replication : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send the first user request to one of the three tomcat instances, and all the other requests that are sent by this user during his session will be sent to the same tomcat instance. During these requests, if you shutdown or restart this tomcat instance (tomcat instance which is used) the loadbalancer sends the remaining requests to one other tomcat instance that is still running, BUT as you don't use session replication, the instance tomcat which receives the remaining requests doesn't have a copy of the user session then for this tomcat the user begin a session : the user loose his session and is disconnected from the web app although the web app is still running.
  • If you're using sticky session WITH session replication : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send the first user request to one of the three tomcat instances, and all the other requests that are sent by this user during his session will be sent to the same tomcat instance. During these requests, if you shutdown or restart this tomcat instance (tomcat instance which is used) the loadbalancer sends the remaining requests to one other tomcat instance that is still running, as you use session replication, the instance tomcat which receives the remaining requests has a copy of the user session then the user keeps on his session : the user continue to browse your web app without being disconnected, the shutdown of the tomcat instance doesn't impact the user navigation.

plot.new has not been called yet

If someone is using print function (for example, with mtext), then firstly depict a null plot:

plot(0,type='n',axes=FALSE,ann=FALSE)

and then print with newpage = F

print(data, newpage = F)

Regular expression to match characters at beginning of line only

Not sure how to apply that to your file on your server, but typically, the regex to match the beginning of a string would be :

^CTR


The ^ means beginning of string / line

SELECT max(x) is returning null; how can I make it return 0?

Oracle would be

SELECT NVL(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1;

Add image to left of text via css

Try something like:

.create
 { 
  margin: 0px;
  padding-left: 20px;
  background-image: url('yourpic.gif');
    background-repeat: no-repeat;

}

Update int column in table with unique incrementing values

You can try :

DECLARE @counter int
SET @counter = 0
UPDATE [table]
SET [column] = @counter, @counter = @counter + 1```

How to get the integer value of day of week

The correct answer, is indeed the correct answer to get the int value.

But, if you're just checking to make sure it's Sunday for example... Consider using the following code, instead of casting to an int. This provides much more readability.

if (yourDateTimeObject.DayOfWeek == DayOfWeek.Sunday)
{
    // You can easily see you're checking for sunday, and not just "0"
}

How can I build for release/distribution on the Xcode 4?

The "play" button is specifically for build and run (or test or profile, etc). The Archive action is intended to build for release and to generate an archive that is suitable for submission to the app store. If you want to skip that, you can choose Product > Build For > Archive to force the release build without actually archiving. To find the built product, expand the Products group in the Project navigator, right-click the product and choose to show in Finder.

That said, you can click and hold the play button for a menu of other build actions (including Build and Archive).

How to use bitmask?

Let's say I have 32-bit ARGB value with 8-bits per channel. I want to replace the alpha component with another alpha value, such as 0x45

unsigned long alpha = 0x45
unsigned long pixel = 0x12345678;
pixel = ((pixel & 0x00FFFFFF) | (alpha << 24));

The mask turns the top 8 bits to 0, where the old alpha value was. The alpha value is shifted up to the final bit positions it will take, then it is OR-ed into the masked pixel value. The final result is 0x45345678 which is stored into pixel.

java.lang.ClassNotFoundException on working app

This is my observation with respect to the Error. I recently Updated the ADT to 22.0.1. I am getting following Error when i imported my previous Projects "E/AndroidRuntime(24807): Caused by: java.lang.ClassNotFoundException: com.sherl.sherlockfragmentsapp.StartActivity in loader dalvik.system.PathClassLoader[/data/app/com.sherl.sherlockfragmentsapp-1.apk]"

Then I changed "Properties->Java Build Path-> Order and Export" in the following manner [Unable to add the Image because of the Forum rules]

  1. Android Private Libraries - checked
  2. Android 4.2.2 - unchecked
  3. Android Dependencies - checked
  4. /src - selected
  5. /gen - selected

It resolved the issue. Hope this is Help you guys.

Check synchronously if file/directory exists in Node.js

I use below function to test if file exists. It catches also other exceptions. So in case there are rights issues e.g. chmod ugo-rwx filename or in Windows Right Click -> Properties -> Security -> Advanced -> Permission entries: empty list .. function returns exception as it should. The file exists but we don't have rights to access it. It would be wrong to ignore this kinds of exceptions.

function fileExists(path) {

  try  {
    return fs.statSync(path).isFile();
  }
  catch (e) {

    if (e.code == 'ENOENT') { // no such file or directory. File really does not exist
      console.log("File does not exist.");
      return false;
    }

    console.log("Exception fs.statSync (" + path + "): " + e);
    throw e; // something else went wrong, we don't have rights, ...
  }
}

Exception output, nodejs errors documentation in case file doesn't exist:

{
  [Error: ENOENT: no such file or directory, stat 'X:\\delsdfsdf.txt']
  errno: -4058,
  code: 'ENOENT',
  syscall: 'stat',
  path: 'X:\\delsdfsdf.txt'
}

Exception in case we don't have rights to the file, but exists:

{
  [Error: EPERM: operation not permitted, stat 'X:\file.txt']
  errno: -4048,
  code: 'EPERM',
  syscall: 'stat',
  path: 'X:\\file.txt'
}

PHP session lost after redirect

you should use "exit" after header-call

header('Location: http://www.example.com/?blabla=blubb');
exit;

How do I vertically center text with CSS?

I needed a row of clickable elephants, vertically centered, but without using a table to get around some Internet Explorer 9 weirdness.

I eventually found the nicest CSS (for my needs) and it's great with Firefox, Chrome, and Internet Explorer 11. Sadly Internet Explorer 9 is still laughing at me...

_x000D_
_x000D_
div {_x000D_
  border: 1px dotted blue;_x000D_
  display: inline;_x000D_
  line-height: 100px;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
span {_x000D_
  border: 1px solid red;_x000D_
  display: inline-block;_x000D_
  line-height: normal;_x000D_
  vertical-align: middle;_x000D_
}_x000D_
_x000D_
.out {_x000D_
  border: 3px solid silver;_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="out" onclick="alert(1)">_x000D_
  <div> <span><img src="http://www.birdfolk.co.uk/littleredsolo.png"/></span> </div>_x000D_
  <div> <span>A lovely clickable option.</span> </div>_x000D_
</div>_x000D_
_x000D_
<div class="out" onclick="alert(2)">_x000D_
  <div> <span><img src="http://www.birdfolk.co.uk/bang2/Ship01.png"/></span> </div>_x000D_
  <div> <span>Something charming to click on.</span> </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Obviously you don't need the borders, but they can help you see how it works.

How to make an autocomplete TextBox in ASP.NET?

aspx Page Coding

<form id="form1" runat="server">
       <input type="search" name="Search" placeholder="Search for a Product..." list="datalist1"
                    required="">
       <datalist id="datalist1" runat="server">

       </datalist>
 </form>

.cs Page Coding

protected void Page_Load(object sender, EventArgs e)
{
     autocomplete();
}
protected void autocomplete()
{
    Database p = new Database();
    DataSet ds = new DataSet();
    ds = p.sqlcall("select [name] from [stu_reg]");
    int row = ds.Tables[0].Rows.Count;
    string abc="";
    for (int i = 0; i < row;i++ )
        abc = abc + "<option>"+ds.Tables[0].Rows[i][0].ToString()+"</option>";
    datalist1.InnerHtml = abc;
}

Here Database is a File (Database.cs) In Which i have created on method named sqlcall for retriving data from database.

Excel VBA Macro: User Defined Type Not Defined

Your error is caused by these:

Dim oTable As Table, oRow As Row,

These types, Table and Row are not variable types native to Excel. You can resolve this in one of two ways:

  1. Include a reference to the Microsoft Word object model. Do this from Tools | References, then add reference to MS Word. While not strictly necessary, you may like to fully qualify the objects like Dim oTable as Word.Table, oRow as Word.Row. This is called early-binding. enter image description here
  2. Alternatively, to use late-binding method, you must declare the objects as generic Object type: Dim oTable as Object, oRow as Object. With this method, you do not need to add the reference to Word, but you also lose the intellisense assistance in the VBE.

I have not tested your code but I suspect ActiveDocument won't work in Excel with method #2, unless you properly scope it to an instance of a Word.Application object. I don't see that anywhere in the code you have provided. An example would be like:

Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long

Set wdApp = GetObject(,"Word.Application")

Application.ScreenUpdating = False

For Each oTable In wdApp.ActiveDocument.Tables

How to make links in a TextView clickable?

The above solutions didn't work for me, but the following did (and it seems a bit cleaner).
First, in the string resource, define your tag opening chevrons using the HTML entity encoding, i.e.:

&lt;a href="http://www.google.com">Google&lt;/a>

and NOT:

<a href="http://www.google.com">Google</a>

In general, encode all the chevrons in the string like that. BTW, the link must start with http://

Then (as suggested here) set this option on your TextView:

 android:linksClickable="true"

Finally, in code, do:

((TextView) findViewById(R.id.your_text_view)).setMovementMethod(LinkMovementMethod.getInstance());
((TextView) findViewById(R.id.your_text_view)).setText(Html.fromHtml(getResources().getString(R.string.string_with_links)));

That's it, no regexes or other manual hacks required.

Batch files : How to leave the console window open

I just press enter and type Pause and it works fine

Open an image using URI in Android's default gallery image viewer

Accepted answer was not working for me,

What had worked:

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + "/sdcard/test.jpg"), "image/*");
startActivity(intent);

git diff file against its last change

One of the ways to use git diff is:

git diff <commit> <path>

And a common way to refer one commit of the last commit is as a relative path to the actual HEAD. You can reference previous commits as HEAD^ (in your example this will be 123abc) or HEAD^^ (456def in your example), etc ...

So the answer to your question is:

git diff HEAD^^ myfile

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

I had the same error with Oracle.DataAccess but deploying to Azure Web Sites (azurewebsites.net). For me I had to edit a setting in VS.NET 2019 before publishing to Azure. I ticked the checkbox "Use the 64 bit version of IIS Express for Web sites and projects" which is found under Tools > Options > Projects and Solutions > Web Projects.

How can I check if a var is a string in JavaScript?

My personal approach, which seems to work for all cases, is testing for the presence of members that will all only be present for strings.

function isString(x) {
    return (typeof x == 'string' || typeof x == 'object' && x.toUpperCase && x.substr && x.charAt && x.trim && x.replace ? true : false);
}

See: http://jsfiddle.net/x75uy0o6/

I'd like to know if this method has flaws, but it has served me well for years.

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

You just need to add three file and two css links. You can either cdn's as well. Links for the js files and css files are as such :-

  1. jQuery.dataTables.min.js
  2. dataTables.bootstrap.min.js
  3. dataTables.bootstrap.min.css
  4. bootstrap-datepicker.css
  5. bootstrap-datepicker.js

They are valid if you are using bootstrap in your project.

I hope this will help you. Regards, Vivek Singla

Is there a limit on number of tcp/ip connections between machines on linux?

You might wanna check out /etc/security/limits.conf

Cross-Origin Request Headers(CORS) with PHP headers

CORS can become a headache, if we do not correctly understand its functioning. I use them in PHP and they work without problems. reference here

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");

What is a database transaction?

Transaction can be defined as a collection of task that are considered as minimum processing unit. Each minimum processing unit can not be divided further.

The main operation of a transaction are read and write.

All transaction must contain four properties that commonly known as ACID properties for the purpose of ensuring accuracy , completeness and data integrity.

DIV table colspan: how?

So basically, you've turned all your <table>, <tr> and <td> elements into <div> elements, and styled them to work exactly like the original table elements they've replaced?

What's the point in that?

It sounds like someone's told you that you shouldn't be using tables in modern web design, which is sort of right, but not in this way -- what you've done doesn't actually change anything about your code. It certainly hasn't got rid of the table; it's just made it harder to read.

The true meaning of the point about not using tables in modern sites is to achieve the page layout you want without using the kind of layout techniques that involve setting out a grid of table cells.

This is achieved by using position styles and float styles, and a number of others, but certainly not display:table-cell; etc. All of this can be achieved without ever needing colspans or rowspans.

On the other hand, if you are trying to place an actual block of tabular data on the page - for instance a list of items and prices in a shopping basket, or a set of statistics, etc, then a table is still the correct solution. Tables were not removed from HTML, because they are still relevant and still useful. The point is that it is fine to use them, but only in places where you are actually display a table of data.

The short answer to your question is I don't think you can -- colspan and rowspan are specific to tables. If you want to carry on using them, you will need to use tables.

If your page layout is such that it relies on tables, there really isn't any point doing a half-way house effort to get rid of the table elements without reworking how the layout is done. It doesn't achieve anything.

Hope that helps.

Force uninstall of Visual Studio

Microsoft now has this:

https://github.com/Microsoft/VisualStudioUninstaller/releases

I allowed a windows 10 update to go through that completely f****d VS2015 so I am trying this before having to resort to a rebuild. WT*. :-(

https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/3487794-create-a-remove-all-remnants-of-visual-studio-fro

Dealing with multiple Python versions and PIP?

You can use one of the following commands:

pip2 install SomePackage
pip3 install SomePackage

python2 -m pip install SomePackage  
python3 -m pip install SomePackage 

And of course, make sure that you have the correct version of pip installed

sudo apt-get install python-pip
sudo apt-get install python3-pip

I haven't used these commands myself but, some answers above suggests using them to specify exactly the version of python you want to use

pip-2.7 install SomePackage
python-3.6 -m pip install SomePackage

How do you find the first key in a dictionary?

easiest way is:

first_key = my_dict.keys()[0]

but some times you should be more careful and assure that your entity is a valuable list so:

first_key = list(my_dict.keys())[0]

$('body').on('click', '.anything', function(){})

You can try this:

You must follow the following format

    $('element,id,class').on('click', function(){....});

*JQuery code*

    $('body').addClass('.anything').on('click', function(){
      //do some code here i.e
      alert("ok");
    });

What does the question mark operator mean in Ruby?

In your example

product.valid?

Is actually a function call and calls a function named valid?. Certain types of "test for condition"/boolean functions have a question mark as part of the function name by convention.

The I/O operation has been aborted because of either a thread exit or an application request

995 is an error reported by the IO Completion Port. The error comes since you try to continue read from the socket when it has most likely been closed.

Receiving 0 bytes from EndRecieve means that the socket has been closed, as does most exceptions that EndRecieve will throw.

You need to start dealing with those situations.

Never ever ignore exceptions, they are thrown for a reason.

Update

There is nothing that says that the server does anything wrong. A connection can be lost for a lot of reasons such as idle connection being closed by a switch/router/firewall, shaky network, bad cables etc.

What I'm saying is that you MUST handle disconnections. The proper way of doing so is to dispose the socket and try to connect a new one at certain intervals.

As for the receive callback a more proper way of handling it is something like this (semi pseudo code):

public void OnDataReceived(IAsyncResult asyn)
{
    BLCommonFunctions.WriteLogger(0, "In :- OnDataReceived", ref swReceivedLogWriter, strLogPath, 0);

    try
    {
        SocketPacket client = (SocketPacket)asyn.AsyncState;

        int bytesReceived = client.thisSocket.EndReceive(asyn); //Here error is coming
        if (bytesReceived == 0)
        {
          HandleDisconnect(client);
          return;
        }
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }

    try
    {
        string strHEX = BLCommonFunctions.ByteArrToHex(theSockId.dataBuffer);                    

        //do your handling here
    }
    catch (Exception err)
    {
        // Your logic threw an exception. handle it accordinhly
    }

    try
    {
       client.thisSocket.BeginRecieve(.. all parameters ..);
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }
}

the reason to why I'm using three catch blocks is simply because the logic for the middle one is different from the other two. Exceptions from BeginReceive/EndReceive usually indicates socket disconnection while exceptions from your logic should not stop the socket receiving.

How do you change the size of figures drawn with matplotlib?

If you've already got the figure created you can quickly do this:

fig = matplotlib.pyplot.gcf()
fig.set_size_inches(18.5, 10.5)
fig.savefig('test2png.png', dpi=100)

To propagate the size change to an existing gui window add forward=True

fig.set_size_inches(18.5, 10.5, forward=True)

SQL SELECT WHERE field contains words

why not use "in" instead?

Select *
from table
where columnname in (word1, word2, word3)

Accessing the last entry in a Map

move does not make sense for a hashmap since its a dictionary with a hashcode for bucketing based on key and then a linked list for colliding hashcodes resolved via equals. Use a TreeMap for sorted maps and then pass in a custom comparator.

How can I copy a file from a remote server to using Putty in Windows?

One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.

How to prevent gcc optimizing some statements in C?

You can use

#pragma GCC push_options
#pragma GCC optimize ("O0")

your code

#pragma GCC pop_options

to disable optimizations since GCC 4.4.

See the GCC documentation if you need more details.

How to only find files in a given directory, and ignore subdirectories using bash

Is there any particular reason that you need to use find? You can just use ls to find files that match a pattern in a directory.

ls /dev/abc-*

If you do need to use find, you can use the -maxdepth 1 switch to only apply to the specified directory.

How to Set Variables in a Laravel Blade Template

You can set a variable in the view file, but it will be printed just as you set it. Anyway, there is a workaround. You can set the variable inside an unused section. Example:

@section('someSection')
  {{ $yourVar = 'Your value' }}
@endsection

Then {{ $yourVar }} will print Your value anywhere you want it to, but you don't get the output when you save the variable.

EDIT: naming the section is required otherwise an exception will be thrown.

Convert JsonNode into POJO

If you're using org.codehaus.jackson, this has been possible since 1.6. You can convert a JsonNode to a POJO with ObjectMapper#readValue: http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(org.codehaus.jackson.JsonNode, java.lang.Class)


    ObjectMapper mapper = new ObjectMapper();
    JsonParser jsonParser = mapper.getJsonFactory().createJsonParser("{\"foo\":\"bar\"}");
    JsonNode tree = jsonParser.readValueAsTree();
    // Do stuff to the tree
    mapper.readValue(tree, Foo.class);

How to switch text case in visual studio code

To have in Visual Studio Code what you can do in Sublime Text ( CTRL+K CTRL+U and CTRL+K CTRL+L ) you could do this:

  • Open "Keyboard Shortcuts" with click on "File -> Preferences -> Keyboard Shortcuts"
  • Click on "keybindings.json" link which appears under "Search keybindings" field
  • Between the [] brackets add:

    {
        "key": "ctrl+k ctrl+u",
        "command": "editor.action.transformToUppercase",
        "when": "editorTextFocus"
    },
    {
        "key": "ctrl+k ctrl+l",
        "command": "editor.action.transformToLowercase",
        "when": "editorTextFocus"
    }
    
  • Save and close "keybindings.json"


Another way:
Microsoft released "Sublime Text Keymap and Settings Importer", an extension which imports keybindings and settings from Sublime Text to VS Code. - https://marketplace.visualstudio.com/items?itemName=ms-vscode.sublime-keybindings

SQL Server CTE and recursion example

The execution process is really confusing with recursive CTE, I found the best answer at https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx and the abstract of the CTE execution process is as below.

The semantics of the recursive execution is as follows:

  1. Split the CTE expression into anchor and recursive members.
  2. Run the anchor member(s) creating the first invocation or base result set (T0).
  3. Run the recursive member(s) with Ti as an input and Ti+1 as an output.
  4. Repeat step 3 until an empty set is returned.
  5. Return the result set. This is a UNION ALL of T0 to Tn.

In jQuery, what's the best way of formatting a number to 2 decimal places?

If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.

<script type="text/javascript">

    // mini jQuery plugin that formats to two decimal places
    (function($) {
        $.fn.currencyFormat = function() {
            this.each( function( i ) {
                $(this).change( function( e ){
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixed(2);
                });
            });
            return this; //for chaining
        }
    })( jQuery );

    // apply the currencyFormat behaviour to elements with 'currency' as their class
    $( function() {
        $('.currency').currencyFormat();
    });

</script>   
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">

How to have conditional elements and keep DRY with Facebook React's JSX?

Just to add another option - if you like/tolerate coffee-script you can use coffee-react to write your JSX in which case if/else statements are usable as they are expressions in coffee-script and not statements:

render: ->
  <div className="container">
    {
      if something
        <h2>Coffeescript is magic!</h2>
      else
        <h2>Coffeescript sucks!</h2>
    }
  </div>  

best practice to generate random token for forgot password

This answers the 'best random' request:

Adi's answer1 from Security.StackExchange has a solution for this:

Make sure you have OpenSSL support, and you'll never go wrong with this one-liner

$token = bin2hex(openssl_random_pseudo_bytes(16));

1. Adi, Mon Nov 12 2018, Celeritas, "Generating an unguessable token for confirmation e-mails", Sep 20 '13 at 7:06, https://security.stackexchange.com/a/40314/

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

Add-on software packages.

See http://www.pathname.com/fhs/2.2/fhs-3.12.html for details.

Also described at Wikipedia.

Its use dates back at least to the late 1980s, when it was a standard part of System V UNIX. These days, it's also seen in Linux, Solaris (which is SysV), OSX Cygwin, etc. Other BSD unixes (FreeBSD, NetBSD, etc) tend to follow other rules, so you don't usually see BSD systems with an /opt unless they're administered by someone who is more comfortable in other environments.

restrict edittext to single line

As android:singleLine="true" is now Depreciated so use

android:maxLines="1"

Use maxLines instead to change the layout of a static text, and use the textMultiLine flag in the inputType attribute instead for editable text views (if both singleLine and inputType are supplied, the inputType flags will override the value of singleLine).

How to get the public IP address of a user in C#

My version handles both ASP.NET or LAN IPs:

/** 
 * Get visitor's ip address.
 */
public static string GetVisitorIp() {
    string ip = null;
    if (HttpContext.Current != null) { // ASP.NET
        ip = string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"])
            ? HttpContext.Current.Request.UserHostAddress
            : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    }
    if (string.IsNullOrEmpty(ip) || ip.Trim() == "::1") { // still can't decide or is LAN
        var lan = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(r => r.AddressFamily == AddressFamily.InterNetwork);
        ip = lan == null ? string.Empty : lan.ToString();
    }
    return ip;
}

How to display hexadecimal numbers in C?

Your code has no problem. It does print the way you want. Alternatively, you can do this:

printf("%04x",a);

Why is it OK to return a 'vector' from a function?

I do not agree and do not recommend to return a vector:

vector <double> vectorial(vector <double> a, vector <double> b)
{
    vector <double> c{ a[1] * b[2] - b[1] * a[2], -a[0] * b[2] + b[0] * a[2], a[0] * b[1] - b[0] * a[1] };
    return c;
}

This is much faster:

void vectorial(vector <double> a, vector <double> b, vector <double> &c)
{
    c[0] = a[1] * b[2] - b[1] * a[2]; c[1] = -a[0] * b[2] + b[0] * a[2]; c[2] = a[0] * b[1] - b[0] * a[1];
}

I tested on Visual Studio 2017 with the following results in release mode:

8.01 MOPs by reference
5.09 MOPs returning vector

In debug mode, things are much worse:

0.053 MOPS by reference
0.034 MOPs by return vector

Get index of array element faster than O(n)

Still I wonder if there's a more convenient way of finding index of en element without caching (or there's a good caching technique that will boost up the performance).

You can use binary search (if your array is ordered and the values you store in the array are comparable in some way). For that to work you need to be able to tell the binary search whether it should be looking "to the left" or "to the right" of the current element. But I believe there is nothing wrong with storing the index at insertion time and then using it if you are getting the element from the same array.

Using Cygwin to Compile a C program; Execution error

Regarding the cygwin1.dll not found error, a solution I have used for at least 8 years is to add the Cygwin bin directories to the end of my %PATH% in My Computer -> Properties -> Advanced -> Environment Variables. I add them to the end of the path so in my normal work, they are searched last, minimizing the possibility of conflicts (in fact, I have had no problems with conflicts in all this time).

When you invoke the Cygwin Bash Shell, those directories get prepended to the %PATH% so everything works as intended in that environment as well.

When not running in Cygwin shell, my %PATH% is:

Path=c:\opt\perl\bin; \
     ...
     C:\opt\cygwin\bin; \
     C:\opt\cygwin\usr\bin; \
     C:\opt\cygwin\usr\local\bin;

This way, for example, ActiveState Perl's perl is found first when I am not in a Cygwin Shell, but the Cygwin perl is found when I am working in the Cygwin Shell.

Change tab bar item selected color in a storyboard

put this code in the viewDidLoad of the view controller that you want to change the color of

[[UITabBar appearance] setSelectedImageTintColor:[UIColor whiteColor]];

How can I get double quotes into a string literal?

Escape the quotes with backslashes:

printf("She said \"time flies like an arrow, but fruit flies like a banana\"."); 

There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.

move_uploaded_file gives "failed to open stream: Permission denied" error

Try this

find /var/www/html/mysite/images/ -type f -print0 | xargs -0 chmod -v 664

Python For loop get index

Use the enumerate() function to generate the index along with the elements of the sequence you are looping over:

for index, w in enumerate(loopme):
    print "CURRENT WORD IS", w, "AT CHARACTER", index 

"inappropriate ioctl for device"

"inappropriate ioctl for device" is the error string for the ENOTTY error. It used to be triggerred primarily by attempts to configure terminal properties (e.g. echo mode) on a file descriptor that was no terminal (but, say, a regular file), hence ENOTTY. More generally, it is triggered when doing an ioctl on a device that does not support that ioctl, hence the error string.

To find out what ioctl is being made that fails, and on what file descriptor, run the script under strace/truss. You'll recognize ENOTTY, followed by the actual printing of the error message. Then find out what file number was used, and what open() call returned that file number.

How to Set Focus on JTextField?

Try this one,

myFrame.setVisible(true);
EventQueue.invokeLater(new Runnable() {

   @Override
     public void run() {
         myComponent.grabFocus();
         myComponent.requestFocus();//or inWindow
     }
});

Dictionary returning a default value if the key does not exist

I created a DefaultableDictionary to do exactly what you are asking for!

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace DefaultableDictionary {
    public class DefaultableDictionary<TKey, TValue> : IDictionary<TKey, TValue> {
        private readonly IDictionary<TKey, TValue> dictionary;
        private readonly TValue defaultValue;

        public DefaultableDictionary(IDictionary<TKey, TValue> dictionary, TValue defaultValue) {
            this.dictionary = dictionary;
            this.defaultValue = defaultValue;
        }

        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
            return dictionary.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }

        public void Add(KeyValuePair<TKey, TValue> item) {
            dictionary.Add(item);
        }

        public void Clear() {
            dictionary.Clear();
        }

        public bool Contains(KeyValuePair<TKey, TValue> item) {
            return dictionary.Contains(item);
        }

        public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
            dictionary.CopyTo(array, arrayIndex);
        }

        public bool Remove(KeyValuePair<TKey, TValue> item) {
            return dictionary.Remove(item);
        }

        public int Count {
            get { return dictionary.Count; }
        }

        public bool IsReadOnly {
            get { return dictionary.IsReadOnly; }
        }

        public bool ContainsKey(TKey key) {
            return dictionary.ContainsKey(key);
        }

        public void Add(TKey key, TValue value) {
            dictionary.Add(key, value);
        }

        public bool Remove(TKey key) {
            return dictionary.Remove(key);
        }

        public bool TryGetValue(TKey key, out TValue value) {
            if (!dictionary.TryGetValue(key, out value)) {
                value = defaultValue;
            }

            return true;
        }

        public TValue this[TKey key] {
            get
            {
                try
                {
                    return dictionary[key];
                } catch (KeyNotFoundException) {
                    return defaultValue;
                }
            }

            set { dictionary[key] = value; }
        }

        public ICollection<TKey> Keys {
            get { return dictionary.Keys; }
        }

        public ICollection<TValue> Values {
            get
            {
                var values = new List<TValue>(dictionary.Values) {
                    defaultValue
                };
                return values;
            }
        }
    }

    public static class DefaultableDictionaryExtensions {
        public static IDictionary<TKey, TValue> WithDefaultValue<TValue, TKey>(this IDictionary<TKey, TValue> dictionary, TValue defaultValue ) {
            return new DefaultableDictionary<TKey, TValue>(dictionary, defaultValue);
        }
    }
}

This project is a simple decorator for an IDictionary object and an extension method to make it easy to use.

The DefaultableDictionary will allow for creating a wrapper around a dictionary that provides a default value when trying to access a key that does not exist or enumerating through all the values in an IDictionary.

Example: var dictionary = new Dictionary<string, int>().WithDefaultValue(5);

Blog post on the usage as well.

How can I use a carriage return in a HTML tooltip?

We had a requirement where we needed to test all of these, here is what I wish to share

_x000D_
_x000D_
document.getElementById("tooltip").setAttribute("title", "Tool\x0ATip\x0AOn\x0ANew\x0ALine")
_x000D_
<p title='Tool_x000D_
Tip_x000D_
On_x000D_
New_x000D_
Line'>Tooltip with <pre>_x000D_
  new _x000D_
  line</pre> Works in all browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title="Tool&#13;Tip&#13;On&#13;New&#13;Line">Tooltip with <code>&amp;#13;</code> Not works Firefox browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title='Tool&#10;Tip&#10;On&#10;New&#10;Line'>Tooltip with <code>&amp;#10;</code> Works in some browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title='Tool&#x0aTip&#x0aOn&#x0aNew&#x0aLine'>Tooltip with <code>&amp;#xD;</code> May work in some browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p id='tooltip'>Tooltip with <code>document.getElementById("tooltip").setAttribute("title", "Tool\x0ATip\x0AOn\x0ANew\x0ALine")</code> May work in some browsers</p>_x000D_
<hr/>_x000D_
_x000D_
_x000D_
<p title="List:_x000D_
  • List item here_x000D_
  • Another list item here_x000D_
  • Aaaand another list item, lol">Tooltip with <code>• </code>Unordered list tooltip</p>_x000D_
<hr/>_x000D_
_x000D_
_x000D_
<p title='Tool\nTip\nOn\nNew\nLine'>Tooltip with <code>\n</code> May not work in modern browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title='Tool\tTip\tOn\tNew\tLine'>Tooltip with <code>\t</code> May not work in modern browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title='Tool&#013;Tip&#013;On&#013;New&#013;Line'>Tooltip with <code>&amp;#013;</code> Works in most browsers</p>_x000D_
<hr/>
_x000D_
_x000D_
_x000D_

Fiddle

What is the equivalent of Java's final in C#?

What everyone here is missing is Java's guarantee of definite assignment for final member variables.

For a class C with final member variable V, every possible execution path through every constructor of C must assign V exactly once - failing to assign V or assigning V two or more times will result in an error.

C#'s readonly keyword has no such guarantee - the compiler is more than happy to leave readonly members unassigned or allow you to assign them multiple times within a constructor.

So, final and readonly (at least with respect to member variables) are definitely not equivalent - final is much more strict.

NLTK and Stopwords Fail #lookuperror

I tried from ubuntu terminal and I don't know why the GUI didn't show up according to tttthomasssss answer. So I followed the comment from KLDavenport and it worked. Here is the summary:

Open your terminal/command-line and type python then

>>> import nltk .>>> nltk.download("stopwords")

This will store the stopwords corpus under the nltk_data. For my case it was /home/myusername/nltk_data/corpora/stopwords.

If you need another corpus then visit nltk data and find the corpus with their ID. Then use the ID to download like we did for stopwords.

How can I retrieve the remote git address of a repo?

The long boring solution, which is not involved with CLI, you can manually navigate to:

your local repo folder ? .git folder (hidden) ? config file

then choose your text editor to open it and look for url located under the [remote "origin"] section.

Copy rows from one table to another, ignoring duplicates

Your problem is that you need another where clause in the subquery that identifies what makes a duplicate:

INSERT INTO destTable
SELECT Field1,Field2,Field3,... 
FROM srcTable
WHERE NOT EXISTS(SELECT * 
                 FROM destTable 
                 WHERE (srcTable.Field1=destTable.Field1 and
                       SrcTable.Field2=DestTable.Field2...etc.)
                 )

As noted by another answerer, an outer join is probably a more concise approach. My above example was just an attempt to explain using your current query to be more understandible. Either approach could technically work.

INSERT INTO destTable
SELECT s.field1,s.field2,s.field3,... 
FROM srcTable s 
       LEFT JOIN destTable d ON (d.Key1 = s.Key1 AND d.Key2 = s.Key2 AND...)
WHERE d.Key1 IS NULL

Both of the above approaches assume you are woried about inserting rows from source that might already be in destination. If you are instead concerned about the possibility that source has duplicate rows you should try something like.

INSERT INTO destTable
SELECT Distinct field1,field2,field3,... 
FROM srcTable  

One more thing. I'd also suggest listing the specific fields on your insert statement instead of using SELECT *.

Remove items from one list in another

You could use LINQ, but I would go with RemoveAll method. I think that is the one that better expresses your intent.

var integers = new List<int> { 1, 2, 3, 4, 5 };

var remove = new List<int> { 1, 3, 5 };

integers.RemoveAll(i => remove.Contains(i));

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.

To change your Platform Toolset:

  1. Right click your project, go to Properties.
  2. Under Configuration Properties, go to General.
  3. Change your Platform Toolset to one of the available ones.

Why catch and rethrow an exception in C#?

Sorry, but many examples as "improved design" still smell horribly or can be extremely misleading. Having try { } catch { log; throw } is just utterly pointless. Exception logging should be done in central place inside the application. exceptions bubble up the stacktrace anyway, why not log them somewhere up and close to the borders of the system?

Caution should be used when you serialize your context (i.e. DTO in one given example) just into the log message. It can easily contain sensitive information one might not want to reach the hands of all the people who can access the log files. And if you don't add any new information to the exception, I really don't see the point of exception wrapping. Good old Java has some point for that, it requires caller to know what kind of exceptions one should expect then calling the code. Since you don't have this in .NET, wrapping doesn't do any good on at least 80% of the cases I've seen.

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

It might be easier for you to understand using Functionoids which are expressively neater and more powerful to use, see this excellent and highly recommended C++ FAQ lite, in particular, look at section 33.12 onwards, but nonetheless, read it from the start of that section to gain a grasp and understanding of it.

To answer your question:

typedef void (*foobar)() fubarfn;

void Fun(fubarfn& baz){
   fubarfn = baz;
   baz();
}

Edit:

  • & means the reference address
  • * means the value of what's contained at the reference address, called de-referencing

So using the reference, example below, shows that we are passing in a parameter, and directly modify it.

void FunByRef(int& iPtr){
    iPtr = 2;
}

int main(void){
    // ...
    int n;
    FunByRef(n);
    cout << n << endl; // n will have value of 2
}

Java better way to delete file if exists

Apache Commons IO's FileUtils offers FileUtils.deleteQuietly:

Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. The difference between File.delete() and this method are:

  • A directory to be deleted does not have to be empty.
  • No exceptions are thrown when a file or directory cannot be deleted.

This offers a one-liner delete call that won't complain if the file fails to be deleted:

FileUtils.deleteQuietly(new File("test.txt"));

swift 3.0 Data to String?

for swift 5

let testString = "This is a test string"
let somedata = testString.data(using: String.Encoding.utf8)
let backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String?
print("testString > \(testString)")
//testString > This is a test string
print("somedata > \(String(describing: somedata))")
//somedata > Optional(21 bytes)
print("backToString > \(String(describing: backToString))")
//backToString > Optional("This is a test string")

What to use now Google News API is deprecated?

Depending on your needs, you want to use their section feeds, their search feeds

http://news.google.com/news?q=apple&output=rss

or Bing News Search.

http://www.bing.com/toolbox/bingdeveloper/

Send HTML in email via PHP

Use PHPMailer,

To send HTML mail you have to set $mail->isHTML() only, and you can set your body with HTML tags

Here is a well written tutorial :

rohitashv.wordpress.com/2013/01/19/how-to-send-mail-using-php/

Setting width as a percentage using jQuery

Using the width function:

$('div#somediv').width('70%');

will turn:

<div id="somediv" />

into:

<div id="somediv" style="width: 70%;"/>

Display HTML form values in same page after submit using Ajax

Try this one:

onsubmit="return f(this.'yourfieldname'.value);"

I hope this will help you.

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

The problems are to do with your paths.

  1. Make sure that the directory "E:\java resources\apache-maven-2.2.0\bin" is on your command search path.

  2. Make sure that the JAVA_HOME variable refers to the home directory for your Java installation. If you are executing Java from "E:\Sun\SDK\jdk\bin", then the JAVA_HOME variable needs to point to "E:\Sun\SDK\jdk".

    NB: JAVA_HOME should NOT end with "\bin"1.

  3. Make sure that you haven't put a semicolon in the JAVA_HOME variable2.

    NB: JAVA_HOME should be a single directory name, not "PATH-like" list of directory names separated by semicolons.

Also note that you could run into problems if you have ignored this advice in the Maven on Windows instructions about spaces in key pathnames.

"Maven, like many cross-platform tools, can encounter problems when there are space characters in important pathnames."

"You need to install the Java SDK (e.g. from Oracle's download site), and you should install it to a pathname without spaces, such as c:\j2se1.6."'

"You need to unpack the Maven distribution. Don't unpack it in the middle of your source code; pick some location (with no spaces in the path!) and unpack it there."

The simple remedy for this would be to reinstall Java or Maven in a different location so that there isn't a space in the path


1 - .... unless you have made an insane choice for the name for your installation location.

2 - Apparently a common "voodoo" solution to Windows path problems is to whack a semicolon on the end. It is not recommended in general, absolutely does not work here.

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

A package called styled-components can solve this problem in an ELEGANT way.

Reference

  1. Glen Maddern - Styling React Apps with Styled Components

Example

_x000D_
_x000D_
const styled = styled.default_x000D_
const Square = styled.div`_x000D_
  height: 120px;_x000D_
  width: 200px;_x000D_
  margin: 100px;_x000D_
  background-color: green;_x000D_
  cursor: pointer;_x000D_
  position: relative;_x000D_
  &:hover {_x000D_
    background-color: red;_x000D_
  };_x000D_
`_x000D_
class Application extends React.Component {_x000D_
  render() {_x000D_
    return (_x000D_
      <Square>_x000D_
      </Square>_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
/*_x000D_
 * Render the above component into the div#app_x000D_
 */_x000D_
ReactDOM.render(<Application />, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>_x000D_
<div id='app'></div>
_x000D_
_x000D_
_x000D_

Add new attribute (element) to JSON object using JavaScript

A JSON object is simply a javascript object, so with Javascript being a prototype based language, all you have to do is address it using the dot notation.

mything.NewField = 'foo';

Proper way to set response status and JSON content in a REST API made with nodejs and express

Express API reference covers this case.

See status and send.

In short, you just have to call the status method before calling json or send:

res.status(500).send({ error: "boo:(" });

Can I add jars to maven 2 build classpath without installing them?

This is what I have done, it also works around the package issue and it works with checked out code.

I created a new folder in the project in my case I used repo, but feel free to use src/repo

In my POM I had a dependency that is not in any public maven repositories

<dependency>
    <groupId>com.dovetail</groupId>
    <artifactId>zoslog4j</artifactId>
    <version>1.0.1</version>
    <scope>runtime</scope>
</dependency>

I then created the following directories repo/com/dovetail/zoslog4j/1.0.1 and copied the JAR file into that folder.

I created the following POM file to represent the downloaded file (this step is optional, but it removes a WARNING) and helps the next guy figure out where I got the file to begin with.

<?xml version="1.0" encoding="UTF-8" ?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.dovetail</groupId>
    <artifactId>zoslog4j</artifactId>
    <packaging>jar</packaging>
    <version>1.0.1</version>
    <name>z/OS Log4J Appenders</name>
    <url>http://dovetail.com/downloads/misc/index.html</url>
    <description>Apache Log4j Appender for z/OS Logstreams, files, etc.</description>
</project>

Two optional files I create are the SHA1 checksums for the POM and the JAR to remove the missing checksum warnings.

shasum -b < repo/com/dovetail/zoslog4j/1.0.1/zoslog4j-1.0.1.jar \
          > repo/com/dovetail/zoslog4j/1.0.1/zoslog4j-1.0.1.jar.sha1

shasum -b < repo/com/dovetail/zoslog4j/1.0.1/zoslog4j-1.0.1.pom \
          > repo/com/dovetail/zoslog4j/1.0.1/zoslog4j-1.0.1.pom.sha1

Finally I add the following fragment to my pom.xml that allows me to refer to the local repository

<repositories>
    <repository>
        <id>project</id>
        <url>file:///${basedir}/repo</url>
    </repository>
</repositories>

stopPropagation vs. stopImmediatePropagation

1)event.stopPropagation(): =>It is used to stop executions of its corresponding parent handler only.

2) event.stopImmediatePropagation(): => It is used to stop the execution of its corresponding parent handler and also handler or function attached to itself except the current handler. => It also stops all the handler attached to the current element of entire DOM.

Here is the example: Jsfiddle!

Thanks, -Sahil

In Maven how to exclude resources from the generated jar?

When I create an executable jar with dependencies (using this guide), all properties files are packaged into that jar too. How to stop it from happening? Thanks.

Properties files from where? Your main jar? Dependencies?

In the former case, putting resources under src/test/resources as suggested is probably the most straight forward and simplest option.

In the later case, you'll have to create a custom assembly descriptor with special excludes/exclude in the unpackOptions.

android start activity from service

If you need to recal an Activity that is in bacgrounde, from your service, I suggest the following link. Intent.FLAG_ACTIVITY_NEW_TASK is not the solution.

https://stackoverflow.com/a/8759867/1127429

How to get the first non-null value in Java?

This situation calls for some preprocessor. Because if you write a function (static method) which picks the first not null value, it evaluates all items. It is problem if some items are method calls (may be time expensive method calls). And this methods are called even if any item before them is not null.

Some function like this

public static <T> T coalesce(T ...items) …

should be used but before compiling into byte code there should be a preprocessor which find usages of this „coalesce function“ and replaces it with construction like

a != null ? a : (b != null ? b : c)

Update 2014-09-02:

Thanks to Java 8 and Lambdas there is possibility to have true coalesce in Java! Including the crucial feature: particular expressions are evaluated only when needed – if earlier one is not null, then following ones are not evaluated (methods are not called, computation or disk/network operations are not done).

I wrote an article about it Java 8: coalesce – hledáme neNULLové hodnoty – (written in Czech, but I hope that code examples are understandable for everyone).

Time part of a DateTime Field in SQL

you can use CONVERT(TIME,GETDATE()) in this case:

INSERT INTO infoTbl
(itDate, itTime)
VALUES (GETDATE(),CONVERT(TIME,GETDATE()))

or if you want print it or return that time use like this:

DECLARE @dt TIME
SET @dt = CONVERT(TIME,GETDATE())
PRINT @dt

Background image jumps when address bar hides iOS/Android/Mobile Chrome

I've got a similar issue on a header of our website.

html, body {
    height:100%;
}
.header {
    height:100%;
}

This will end up in a jumpy scrolling experience on android chrome, because the .header-container will rescale after the url-bar hides and the finger is removed from screen.

CSS-Solution:

Adding the following two lines, will prevent that the url-bar hides and vertical scrolling is still possible:

html {
    overflow: hidden;
}
body {
    overflow-y: scroll;
    -webkit-overflow-scrolling:touch;
}

Retrieving JSON Object Literal from HttpServletRequest

There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request

String jsonString = IOUtils.toString(request.getInputStream());

Then you can do whatever you want, convert it to JSON or other object with Gson, etc.

JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);

PHP MySQL Query Where x = $variable

You have to do this to echo it:

echo $row['note'];

(The data is coming as an array)

Getting rid of all the rounded corners in Twitter Bootstrap

The code posted above by @BrunoS did not work for me,

* {
  .border-radius(0) !important;
}

what i used was

* {
  border-radius: 0 !important;
}

I hope this helps someone

Detect backspace and del on "input" event?

Have you tried using 'onkeydown'? This is the event you are looking for.

It operates before the input is inserted and allows you to cancel char input.

How to get an Array with jQuery, multiple <input> with the same name

For multiple elements, you should give it a class rather than id eg:

<input type="text" class="task" name="task[]" />

Now you can get those using jquery something like this:

$('.task').each(function(){
   alert($(this).val());
});

How to recover corrupted Eclipse workspace?

This thread may be a bit older, but since this still is a problem nowadays, I thought I’d propose a new solution for backing up Eclipse.

  • At http://profiles.yatta.de you can download the Yatta Eclipse Launcher. You can use it to save your Eclipse and workspace setup.

  • After installation, the Launcher will discover your existing Eclipse installations and workspaces.

  • Click the Upload & Share button (the blue one) on the right of the entry you want to back up.

(You won’t actually “share” your Eclipse or workspace with anyone. You’ll just upload a setup file with your metadata that only you have access to yourself . You could share this later, but you can also just use it as a backup).

If you do that, you’ll be able to re-setup your IDE really fast if you ever have a fragged workspace or Eclipse installation.

In SQL, how can you "group by" in ranges?

I would do this a little differently so that it scales without having to define every case:

select t.range as [score range], count(*) as [number of occurences]
from (
  select FLOOR(score/10) as range
  from scores) t
group by t.range

Not tested, but you get the idea...

sorting integers in order lowest to highest java

For sorting narrow range of integers try Counting sort, which has a complexity of O(range + n), where n is number of items to be sorted. If you'd like to sort something not discrete use optimal n*log(n) algorithms (quicksort, heapsort, mergesort). Merge sort is also used in a method already mentioned by other responses Arrays.sort. There is no simple way how to recommend some algorithm or function call, because there are dozens of special cases, where you would use some sort, but not the other.

So please specify the exact purpose of your application (to learn something (well - start with the insertion sort or bubble sort), effectivity for integers (use counting sort), effectivity and reusability for structures (use n*log(n) algorithms), or zou just want it to be somehow sorted - use Arrays.sort :-)). If you'd like to sort string representations of integers, than u might be interrested in radix sort....

How do I clone a github project to run locally?

I use @Thiho answer but i get this error:

'git' is not recognized as an internal or external command

For solving that i use this steps:

I add the following paths to PATH:

  • C:\Program Files\Git\bin\

  • C:\Program Files\Git\cmd\

In windows 7:

  1. Right-click "Computer" on the Desktop or Start Menu.
  2. Select "Properties".
  3. On the very far left, click the "Advanced system settings" link.
  4. Click the "Environment Variables" button at the bottom.
  5. Double-click the "Path" entry under "System variables".
  6. At the end of "Variable value", insert a ; if there is not already one, and then C:\Program Files\Git\bin\;C:\Program Files\Git\cmd. Do not put a space between ; and the entry.

Finally close and re-open your console.

How to reset selected file with input tag file type in Angular 2?

I am using a a very simple aproach. After a file has been uploaded, i shortly remove the input control, using *ngIf. That will cause the input field being removed from the dom and re-added, consequencely it is a new control, and therefore it is emply:

_x000D_
_x000D_
showUploader: boolean = true;

async upload($event) {
  await dosomethingwiththefile();
  this.showUploader = false;
  setTimeout(() =>{ this.showUploader = true }, 100);
}
_x000D_
<input type="file" (change)="upload($event)" *ngIf="showUploader">
_x000D_
_x000D_
_x000D_

DateTime format to SQL format using C#

if you want to store current date in table so you can use

GETDATE();

or pass this function as a parameter

eg. 'update tblname set curdate=GETDATE() where colname=123'

Vertically align text to top within a UILabel

I riffed off dalewking's suggestion and added a UIEdgeInset to allow for an adjustable margin. nice work around.

- (id)init
{
    if (self = [super init]) {
        contentEdgeInsets = UIEdgeInsetsZero;
    }

    return self;
}

- (void)layoutSubviews
{
    CGRect localBounds = self.bounds;
    localBounds = CGRectMake(MAX(0, localBounds.origin.x + contentEdgeInsets.left), 
                             MAX(0, localBounds.origin.y + contentEdgeInsets.top), 
                             MIN(localBounds.size.width, localBounds.size.width - (contentEdgeInsets.left + contentEdgeInsets.right)), 
                             MIN(localBounds.size.height, localBounds.size.height - (contentEdgeInsets.top + contentEdgeInsets.bottom)));

    for (UIView *subview in self.subviews) {
        if ([subview isKindOfClass:[UILabel class]]) {
            UILabel *label = (UILabel*)subview;
            CGSize lineSize = [label.text sizeWithFont:label.font];
            CGSize sizeForText = [label.text sizeWithFont:label.font constrainedToSize:localBounds.size lineBreakMode:label.lineBreakMode];

            NSInteger numberOfLines = ceilf(sizeForText.height/lineSize.height);

            label.numberOfLines = numberOfLines;
            label.frame = CGRectMake(MAX(0, contentEdgeInsets.left), MAX(0, contentEdgeInsets.top), localBounds.size.width, MIN(localBounds.size.height, lineSize.height * numberOfLines)); 
        }
    }
}

Output data from all columns in a dataframe in pandas

Use:

pandas.set_option('display.max_columns', 7)

This will force Pandas to display the 7 columns you have. Or more generally:

pandas.set_option('display.max_columns', None)

which will force it to display any number of columns.

Explanation: the default for max_columns is 0, which tells Pandas to display the table only if all the columns can be squeezed into the width of your console.

Alternatively, you can change the console width (in chars) from the default of 80 using e.g:

pandas.set_option('display.width', 200)

git checkout tag, git pull fails in branch

I had the same problem and fixed it with this command:

$ git push -u origin master

From the help file the -u basically sets the default for pulls:

-u, --set-upstream`

  For every branch that is up to date or successfully pushed, add 
  upstream (tracking) reference, used by argument-less git-pull(1) and
  other commands. For more information, see branch.<name>.merge in 
  git-config(1).

Hiding and Showing TabPages in tabControl

You Can Use the Following

tabcontainer.tabs(1).visible=true

1 is tabindex

What is SuppressWarnings ("unchecked") in Java?

One trick is to create an interface that extends a generic base interface...

public interface LoadFutures extends Map<UUID, Future<LoadResult>> {}

Then you can check it with instanceof before the cast...

Object obj = context.getAttribute(FUTURES);
if (!(obj instanceof LoadFutures)) {
    String format = "Servlet context attribute \"%s\" is not of type "
            + "LoadFutures. Its type is %s.";
    String msg = String.format(format, FUTURES, obj.getClass());
    throw new RuntimeException(msg);
}
return (LoadFutures) obj;

How can I remove jenkins completely from linux

if you are ubuntu user than try this:

sudo apt-get remove jenkins
sudo apt-get remove --auto-remove jenkins

'apt-get remove' command is use to remove package.

How to get TimeZone from android mobile?

ZoneId from java.time and ThreeTenABP

Modern answer:

    ZoneId zone = ZoneId.systemDefault();
    System.out.println(zone);

When I ran this snippet in Australia/Sydney time zone, the output was exactly that:

Australia/Sydney

If you want the summer time (DST) aware time zone name or abbreviation:

    DateTimeFormatter longTimeZoneFormatter = DateTimeFormatter.ofPattern("zzzz", Locale.getDefault());
    String longTz = ZonedDateTime.now(zone).format(longTimeZoneFormatter);
    System.out.println(longTz);

    DateTimeFormatter shortTimeZoneFormatter = DateTimeFormatter.ofPattern("zzz", Locale.getDefault());
    String shortTz = ZonedDateTime.now(zone).format(shortTimeZoneFormatter);
    System.out.println(shortTz);
Eastern Summer Time (New South Wales)
EST

The TimeZone class used in most of the other answers was what we had when the question was asked in 2011, even though it was poorly designed. Today it’s long outdated, and I recommend that instead we use java.time, the modern Java date and time API that came out in 2014.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

What is the difference between %g and %f in C?

As Unwind points out f and g provide different default outputs.

Roughly speaking if you care more about the details of what comes after the decimal point I would do with f and if you want to scale for large numbers go with g. From some dusty memories f is very nice with small values if your printing tables of numbers as everything stays lined up but something like g is needed if you stand a change of your numbers getting large and your layout matters. e is more useful when your numbers tend to be very small or very large but never near ten.

An alternative is to specify the output format so that you get the same number of characters representing your number every time.

Sorry for the woolly answer but it is a subjective out put thing that only gets hard answers if the number of characters generated is important or the precision of the represented value.

Get a list of all git commits, including the 'lost' ones

We'll git log sometimes is not good to get all commits detail, so to view this...

For Mac: Get into you git project and type:

$ nano .git/logs/HEAD

to view you all commits in that, or:

$ gedit .git/logs/HEAD

to view you all commits in that,

then you can edit in any of your favourite browser.

How to print object array in JavaScript?

Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.

Function

function print_r(printthis, returnoutput) {
    var output = '';

    if($.isArray(printthis) || typeof(printthis) == 'object') {
        for(var i in printthis) {
            output += i + ' : ' + print_r(printthis[i], true) + '\n';
        }
    }else {
        output += printthis;
    }
    if(returnoutput && returnoutput == true) {
        return output;
    }else {
        alert(output);
    }
}

Usage

var data = [1, 2, 3, 4];
print_r(data);

Join two sql queries

I would just use a Union

In your second query add the extra column name and add a '' in all the corresponding locations in the other queries

Example

//reverse order to get the column names
select top 10 personId, '' from Telephone//No Column name assigned 
Union 
select top 10 personId, loanId from loan

Python popen command. Wait until the command is finished

Let the command you are trying to pass be

os.system('x')

then you covert it to a statement

t = os.system('x')

now the python will be waiting for the output from the commandline so that it could be assigned to the variable t.

I want to delete all bin and obj folders to force all projects to rebuild everything

Nothing worked for me. I needed to delete all files in bin and obj folders for debug and release. My solution:

1.Right click project, unload, right click again edit, go to bottom

2.Insert

<Target Name="DeleteBinObjFolders" BeforeTargets="Clean">
  <RemoveDir Directories="..\..\Publish" />
  <RemoveDir Directories=".\bin" />
  <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
</Target>

3. Save, reload project, right click clean and presto.

Add a dependency in Maven

I'd do this:

  1. add the dependency as you like in your pom:

    <dependency>
            <groupId>com.stackoverflow...</groupId>
            <artifactId>artifactId...</artifactId>
            <version>1.0</version>
    </dependency>
    

  2. run mvn install it will try to download the jar and fail. On the process, it will give you the complete command of installing the jar with the error message. Copy that command and run it! easy huh?!

Convert string to binary then back again using PHP

I would most definitely recommend using the built in standard password libraries that come with PHP - Here is a good example on how to use them.


For those coming here to figure out how to go from Binary Strings to Decimals and back, there are some good examples below.

For converting binary "strings" to decimals/chars you can do something like this...

echo bindec("00000001") . "\n";
echo bindec("00000010") . "\n";
echo bindec("00000100") . "\n";
echo bindec("00001000") . "\n";
echo bindec("00010000") . "\n";
echo bindec("00100000") . "\n";
echo bindec("01000000") . "\n";
echo bindec("10000000") . "\n";
echo bindec("01000001") . "\n";

# big binary string
echo bindec("111010110111011110000110001")."\n";

The above outputs:

1
2
4
8
16
32
64
128
65
123452465

For converting decimals to char/strings you can do this:

# convert to binary strings "00000001"
echo decbin(1) . "\n";
echo decbin(2) . "\n";
echo decbin(4) . "\n";
echo decbin(8) . "\n";
echo decbin(16) . "\n";
echo decbin(32) . "\n";
echo decbin(64) . "\n";
echo decbin(128) . "\n";

# convert a ascii character
echo str_pad(decbin(65), 8, 0, STR_PAD_LEFT) ."\n";

# convert a 'char'
echo str_pad(decbin(ord('A')), 8, 0, STR_PAD_LEFT) ."\n";

# big number...
echo str_pad(decbin(65535), 8, 0, STR_PAD_LEFT) ."\n";
echo str_pad(decbin(123452465), 8, 0, STR_PAD_LEFT) ."\n";

The above outputs:

1
10
100
1000
10000
100000
1000000
10000000
01000001
01000001
1111111111111111
111010110111011110000110001

How to write log base(2) in c/c++

All the above answers are correct. This answer of mine below can be helpful if someone needs it. I have seen this requirement in many questions which we are solving using C.

log2 (x) = logy (x) / logy (2)

However, if you are using C language and you want the result in integer, you can use the following:

int result = (int)(floor(log(x) / log(2))) + 1;

Hope this helps.

Access denied for user 'root'@'localhost' with PHPMyAdmin

Edit your phpmyadmin config.inc.php file and if you have Password, insert that in front of Password in following code:

$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = '**your-root-username**';
$cfg['Servers'][$i]['password'] = '**root-password**';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

how to get all markers on google-maps-v3

If you are using JQuery Google map plug-in then below code will work for you -

var markers = $('#map_canvas').gmap('get','markers');

jQuery scroll() detect when user stops scrolling

This detects the scroll stop after 1 milisecond (or change it) using a global timer:

var scrollTimer;

$(window).on("scroll",function(){
    clearTimeout(scrollTimer);
    //Do  what you want whilst scrolling
    scrollTimer=setTimeout(function(){afterScroll()},1);
})

function afterScroll(){
    //I catched scroll stop.
}

Efficient SQL test query or validation query that will work across all (or most) databases

I use this for Firebird

select 1 from RDB$RELATION_FIELDS rows 1

Find duplicate records in MySQL

    SELECT *
    FROM (SELECT  address, COUNT(id) AS cnt
    FROM list
    GROUP BY address
    HAVING ( COUNT(id) > 1 ))

Figure out size of UILabel based on String in Swift

I found that the accepted answer worked for a fixed width, but not a fixed height. For a fixed height, it would just increase the width to fit everything on one line, unless there was a line break in the text.

The width function calls the height function multiple times, but it is a quick calculation and I didn't notice performance issues using the function in the rows of a UITable.

extension String {

    public func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font : font], context: nil)

        return ceil(boundingBox.height)
    }

    public func width(withConstrainedHeight height: CGFloat, font: UIFont, minimumTextWrapWidth:CGFloat) -> CGFloat {

        var textWidth:CGFloat = minimumTextWrapWidth
        let incrementWidth:CGFloat = minimumTextWrapWidth * 0.1
        var textHeight:CGFloat = self.height(withConstrainedWidth: textWidth, font: font)

        //Increase width by 10% of minimumTextWrapWidth until minimum width found that makes the text fit within the specified height
        while textHeight > height {
            textWidth += incrementWidth
            textHeight = self.height(withConstrainedWidth: textWidth, font: font)
        }
        return ceil(textWidth)
    }
}

Can't find bundle for base name /Bundle, locale en_US

I had the same problemo, and balus solution fixed it.

For the record:

WEB-INF\faces-config is

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
    <application>
        <locale-config>
            <default-locale>en</default-locale>
        </locale-config>
        <message-bundle>
            Message
        </message-bundle>
    </application>
</faces-config>

And had Message.properties under WebContent\Resources (after mkyong's tutorial)

the pesky exception appeared even when i renamed the bundle to "Message_en_us" and "Message_en". Moving it to src\ worked.

Should someone post the missing piece to make bundles work under resources,it would be a beautiful thing.

How to shift a block of code left/right by one space in VSCode?

In MacOS, a simple way is to use Sublime settings and bindings.

Navigate to VS Code.

Click on Help -> Welcome

On the top right, you can find Customise section and in that click on Sublime.

Bingo. Done.

Reload VS Code and you are free to use Command + [ and Command + ]

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

This link helped: https://stackoverflow.com/a/11199865/1307104

I edit my command by adding quotes for every parameter like this:

mvn install:install-file "-DgroupId=org.mozilla" "-DartifactId=jss" "-Dversion=4.2.5" "-Dpackaging=jar" "-Dfile=C:\Users\AArmijos\workspace\componentes-1.0.4\deps\jss-4.2.5.jar"

It's worked.

How to keep one variable constant with other one changing with row in excel

Yeah. Just put the $ sign in front of your desired constant cell.

Like $A6 if you wish to just change the number 6 serially and keep a constant, or $A$6 if you do not want anything from that reference to change at all.

Example: Cell A5 contains my exchange rate. In B1 you put say ( = C1 * $A$1). when you fill B1 through B....... the value in A5 remains constant and the value in C1 increases serially.

I am by far not be good at teacher, but I hope this helps!!!! Wink wink

MVC - Set selected value of SelectList

If you have your SelectList object, just iterate through the items in it and set the "Selected" property of the item you wish.

foreach (var item in selectList.Items)
{
  if (item.Value == selectedValue)
  {
    item.Selected = true;
    break;
  }
}

Or with Linq:

var selected = list.Where(x => x.Value == "selectedValue").First();
selected.Selected = true;

How do I create a self-signed certificate for code signing on Windows?

As stated in the answer, in order to use a non deprecated way to sign your own script, one should use New-SelfSignedCertificate.

  1. Generate the key:
New-SelfSignedCertificate -DnsName [email protected] -Type CodeSigning -CertStoreLocation cert:\CurrentUser\My
  1. Export the certificate without the private key:
Export-Certificate -Cert (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)[0] -FilePath code_signing.crt

The [0] will make this work for cases when you have more than one certificate... Obviously make the index match the certificate you want to use... or use a way to filtrate (by thumprint or issuer).

  1. Import it as Trusted Publisher
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\TrustedPublisher
  1. Import it as a Root certificate authority.
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\Root
  1. Sign the script (assuming here it's named script.ps1, fix the path accordingly).
Set-AuthenticodeSignature .\script.ps1 -Certificate (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)

Obviously once you have setup the key, you can simply sign any other scripts with it.
You can get more detailed information and some troubleshooting help in this article.

Prevent linebreak after </div>

display:inline;

OR

float:left;

OR

display:inline-block; -- Might not work on all browsers.

What is the purpose of using a div here? I'd suggest a span, as it is an inline-level element, whereas a div is a block-level element.


Do note that each option above will work differently.

display:inline; will turn the div into the equivalent of a span. It will be unaffected by margin-top, margin-bottom, padding-top, padding-bottom, height, etc.

float:left; keeps the div as a block-level element. It will still take up space as if it were a block, however the width will be fitted to the content (assuming width:auto;). It can require a clear:left; for certain effects.

display:inline-block; is the "best of both worlds" option. The div is treated as a block element. It responds to all of the margin, padding, and height rules as expected for a block element. However, it is treated as an inline element for the purpose of placement within other elements.

Read this for more information.

How to place two forms on the same page?

Here are two form with two submit button:

<form method="post" action="page.php">
  <input type="submit" name="btnPostMe1" value="Confirm"/>
</form>

<form method="post" action="page.php">
  <input type="submit" name="btnPostMe2" value="Confirm"/>
</form>

And here is your PHP code:

if (isset($_POST['btnPostMe1'])) { //your code 1 }
if (isset($_POST['btnPostMe2'])) { //your code 2 }

Removing spaces from string

When I am reading numbers from contact book, then it doesn't worked I used

number=number.replaceAll("\\s+", "");

It worked and for url you may use

url=url.replaceAll(" ", "%20");

Linux cmd to search for a class file among jars irrespective of jar path

Most of the solutions are directly using grep command to find the class. However, it would not give you the package name of the class. Also if the jar is compressed, grep will not work.

This solution is using jar command to list the contents of the file and grep the class you are looking for.

It will print out the class with package name and also the jar file name.

find . -type f -name '*.jar' -print0 |  xargs -0 -I '{}' sh -c 'jar tf {} | grep Hello.class &&  echo {}'

You can also search with your package name like below:

find . -type f -name '*.jar' -print0 |  xargs -0 -I '{}' sh -c 'jar tf {} | grep com/mypackage/Hello.class &&  echo {}'

How to download all dependencies and packages to directory

This will download all the Debs to the current directory, and will NOT fail if It can't find a candidate.

Also does NOT require sudo to run sript!

nano getdebs.sh && chmod +x getdebs.sh && ./getdebs.sh

#!/bin/bash

package=ssmtp

apt-cache depends "$package" | grep Depends: >> deb.list

sed -i -e 's/[<>|:]//g' deb.list

sed -i -e 's/Depends//g' deb.list

sed -i -e 's/ //g' deb.list

filename="deb.list"

while read -r line
do
    name="$line"
    apt-get download "$name"
done < "$filename"

apt-get download "$package"

Note: I used this as my example because I was actually trying to DL the Deps for SSMTP and it failed on debconf-2.0, but this script got me what I need! Hope it helps.

Ctrl+click doesn't work in Eclipse Juno

If the project is a Maven project, make sure that the java class you have open is inside src/main/java.

Mac SQLite editor

I use Liya from the Mac App Store, it's free, does the job, and the project is maintained (a month or so between updates as of Jan 2013).

I also test a lot on the device. You can access the SQLITE database on the device by:

  1. Add Application supports iTunes file sharing to the info.plist and setting it to YES
  2. Running the app on a device
  3. Open iTunes
  4. Select the device
  5. Select the "Apps" tab
  6. Scroll down to the "File Sharing" section and select the app
  7. The .sqlite file should appear in the right hand pane - select it and "Save to..."
  8. Once it's saved open it up in your favourite SQLITE editor

You can also edit it and copy it back.

EDIT: You can also do this through the Organizer in XCode

  1. Open the Organizer in XCode (Window > Organiser)
  2. Select the "Devices" tab
  3. Expand the device on the left that you want to download/upload data to
  4. Select Applications
  5. Select an Application in the main panel
  6. The panel at the bottom (Data files in Sandbox) will update with all the files within that application
  7. Choose Download and save it somewhere
  8. Find the file in Finder
  9. Right click and select "Show Package Contents"

You can now view, edit, and re-upload the package to your debug device. This can be really handy for keeping snapshots of different states to try out on other devices.

dereferencing pointer to incomplete type

A - Solution

Speaking for C language, I've just found ampirically that following declaration code will be the solution;

typedef struct ListNode
{
    int data;
    ListNode * prev;
    ListNode * next;
} ListNode;

So as a general rule, I give the same name both for both type definition and name of the struct;

typedef struct X
{
    // code for additional types here
    X* prev; // reference to pointer
    X* next; // reference to pointer
} X;

B - Problemetic Samples

Where following declarations are considered both incomplete by the gcc compiler when executing following statement. ;

removed->next->prev = removed->prev;

And I get same error for the dereferencing code reported in the error output;

>gcc Main.c LinkedList.c -o Main.exe -w
LinkedList.c: In function 'removeFromList':
LinkedList.c:166:18: error: dereferencing pointer to incomplete type 'struct ListNode'
     removed->next->prev = removed->prev;

For both of the header file declarations listed below;

typedef struct
{
    int data;
    ListNode * prev;
    ListNode * next;
} ListNode;

Plus this one;

typedef struct ListNodeType
{
    int data;
    ListNode * prev;
    ListNode * next;
} ListNode;

How do I run a docker instance from a DockerFile?

Straightforward and easy solution is:

docker build .
=> ....
=> Successfully built a3e628814c67
docker run -p 3000:3000 a3e628814c67

3000 - can be any port

a3e628814c68 - hash result given by success build command

NOTE: you should be within directory that contains Dockerfile.

Get the time difference between two datetimes

It is very simple with moment below code will return diffrence in hour from current time:

moment().diff('2021-02-17T14:03:55.811000Z', "h")

process.waitFor() never returns

There are many reasons that waitFor() doesn't return.

But it usually boils down to the fact that the executed command doesn't quit.

This, again, can have many reasons.

One common reason is that the process produces some output and you don't read from the appropriate streams. This means that the process is blocked as soon as the buffer is full and waits for your process to continue reading. Your process in turn waits for the other process to finish (which it won't because it waits for your process, ...). This is a classical deadlock situation.

You need to continually read from the processes input stream to ensure that it doesn't block.

There's a nice article that explains all the pitfalls of Runtime.exec() and shows ways around them called "When Runtime.exec() won't" (yes, the article is from 2000, but the content still applies!)

javascript date + 7 days

Using the Date object's methods will could come in handy.

e.g.:

myDate = new Date();
plusSeven = new Date(myDate.setDate(myDate.getDate() + 7));

Cleanest way to build an SQL string in Java

First of all consider using query parameters in prepared statements:

PreparedStatement stm = c.prepareStatement("UPDATE user_table SET name=? WHERE id=?");
stm.setString(1, "the name");
stm.setInt(2, 345);
stm.executeUpdate();

The other thing that can be done is to keep all queries in properties file. For example in a queries.properties file can place the above query:

update_query=UPDATE user_table SET name=? WHERE id=?

Then with the help of a simple utility class:

public class Queries {

    private static final String propFileName = "queries.properties";
    private static Properties props;

    public static Properties getQueries() throws SQLException {
        InputStream is = 
            Queries.class.getResourceAsStream("/" + propFileName);
        if (is == null){
            throw new SQLException("Unable to load property file: " + propFileName);
        }
        //singleton
        if(props == null){
            props = new Properties();
            try {
                props.load(is);
            } catch (IOException e) {
                throw new SQLException("Unable to load property file: " + propFileName + "\n" + e.getMessage());
            }           
        }
        return props;
    }

    public static String getQuery(String query) throws SQLException{
        return getQueries().getProperty(query);
    }

}

you might use your queries as follows:

PreparedStatement stm = c.prepareStatement(Queries.getQuery("update_query"));

This is a rather simple solution, but works well.

Check for false

Checking if something isn't false... So it's true, just if you're doing something that is quantum physics.

if(!(borrar() === false))

or

if(borrar() === true)

inline conditionals in angular.js

I'll throw mine in the mix:

https://gist.github.com/btm1/6802312

this evaluates the if statement once and adds no watch listener BUT you can add an additional attribute to the element that has the set-if called wait-for="somedata.prop" and it will wait for that data or property to be set before evaluating the if statement once. that additional attribute can be very handy if you're waiting for data from an XHR request.

angular.module('setIf',[]).directive('setIf',function () {
    return {
      transclude: 'element',
      priority: 1000,
      terminal: true,
      restrict: 'A',
      compile: function (element, attr, linker) {
        return function (scope, iterStartElement, attr) {
          if(attr.waitFor) {
            var wait = scope.$watch(attr.waitFor,function(nv,ov){
              if(nv) {
                build();
                wait();
              }
            });
          } else {
            build();
          }

          function build() {
            iterStartElement[0].doNotMove = true;
            var expression = attr.setIf;
            var value = scope.$eval(expression);
            if (value) {
              linker(scope, function (clone) {
                iterStartElement.after(clone);
                clone.removeAttr('set-if');
                clone.removeAttr('wait-for');
              });
            }
          }
        };
      }
    };
  });

Check existence of input argument in a Bash shell script

Only because there's a more base point to point out I'll add that you can simply test your string is null:

if [ "$1" ]; then
  echo yes
else
  echo no
fi

Likewise if you're expecting arg count just test your last:

if [ "$3" ]; then
  echo has args correct or not
else
  echo fixme
fi

and so on with any arg or var

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

In Object Explorer, expand the table, and expand the Keys:

enter image description here

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

It happens when upgrading to el capitan from yosemite. Virtual box needs to be installed again. Reinstalling geny motion does nothing. You will keep all your virtual devices unchanged.