SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

Sprintf equivalent in Java

Since Java 13 you have formatted 1 method on String, which was added along with text blocks as a preview feature 2. You can use it instead of String.format()

Assertions.assertEquals(
   "%s %d %.3f".formatted("foo", 123, 7.89),
   "foo 123 7.890"
);

How do I efficiently iterate over each entry in a Java Map?

With Java 8, you can iterate Map using forEach and lambda expression,

map.forEach((k, v) -> System.out.println((k + ":" + v)));

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

Visual Studio 2008 does have a designer that allows you to add FK's. Just right-click the table... Table Properties, then go to the "Add Relations" section.

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

The minimum required:

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MessageSender {

    public static void sendHardCoded() throws AddressException, MessagingException {
        String to = "[email protected]";
        final String from = "[email protected]";

        Properties properties = new Properties();
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");

        Session session = Session.getInstance(properties,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(from, "BeNice");
                    }
                });

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject("Hello");
        message.setText("What's up?");

        Transport.send(message);
    }

}

When do you use POST and when do you use GET?

Simple version of POST GET PUT DELETE

  • use GET - when you want to get any resource like List of data based on any Id or Name
  • use POST - when you want to send any data to server. keep in mind POST is heavy weight operation because for updation we should use PUT instead of POST internally POST will create new resource
  • use PUT - when you

Response.Redirect with POST instead of Get?

The GET (and HEAD) method should never be used to do anything that has side-effects. A side-effect might be updating the state of a web application, or it might be charging your credit card. If an action has side-effects another method (POST) should be used instead.

So, a user (or their browser) shouldn't be held accountable for something done by a GET. If some harmful or expensive side-effect occurred as the result of a GET, that would be the fault of the web application, not the user. According to the spec, a user agent must not automatically follow a redirect unless it is a response to a GET or HEAD request.

Of course, a lot of GET requests do have some side-effects, even if it's just appending to a log file. The important thing is that the application, not the user, should be held responsible for those effects.

The relevant sections of the HTTP spec are 9.1.1 and 9.1.2, and 10.3.

htmlentities() vs. htmlspecialchars()

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

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

	


!
!
"
" "
#
#
$
$
%
%
&
& &
'
'
(
(
)
)
*
* *
+
+
,
,
.
.
/
/
:
:
;
;
<
&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.

Possible to perform cross-database queries with PostgreSQL?

Just to add a bit more information.

There is no way to query a database other than the current one. Because PostgreSQL loads database-specific system catalogs, it is uncertain how a cross-database query should even behave.

contrib/dblink allows cross-database queries using function calls. Of course, a client can also make simultaneous connections to different databases and merge the results on the client side.

PostgreSQL FAQ

How to validate an email address in JavaScript

W3Schools gives a good simple and efficient script to validate an email:

function validateEmail(email) {
    var atpos=email.indexOf("@");
    var dotpos=email.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.length) {
        alert("Not a valid e-mail address");
        return false;
    }
    return true;
}

Note that you will have to remove spaces if there are any though, with something like this:

.replace(/ /g,'')

Source: JavaScript Form Validation

How do you move a file?

With TortoiseSVN I just move the file on disk.

When I come to commit my changes I select the missing file and the new one and select "Repair move" from the right click menu:

enter image description here

This means I can let my IDE move round files and use it refactoring tools without losing history.

php execute a background process

Here is a function to launch a background process in PHP. Finally created one that actually works on Windows too, after a lot of reading and testing different approaches and parameters.

function LaunchBackgroundProcess($command){
  // Run command Asynchroniously (in a separate thread)
  if(PHP_OS=='WINNT' || PHP_OS=='WIN32' || PHP_OS=='Windows'){
    // Windows
    $command = 'start "" '. $command;
  } else {
    // Linux/UNIX
    $command = $command .' /dev/null &';
  }
  $handle = popen($command, 'r');
  if($handle!==false){
    pclose($handle);
    return true;
  } else {
    return false;
  }
}

Note 1: On windows, do not use /B parameter as suggested elsewhere. It forces process to run the same console window as start command itself, resulting in the process being processed synchronously. To run the process in a separate thread (asynchronously), do not use /B.

Note 2: The empty double quotes after start "" are required if the command is a quoted path. start command interprets the first quoted parameter as window title.

How do you add an image?

In order to add attributes, XSL wants

<xsl:element name="img">
     (attributes)
</xsl:element>

instead of just

<img>
     (attributes)
</img>

Although, yes, if you're just copying the element as-is, you don't need any of that.

How do you automatically set the focus to a textbox when a web page loads?

It is possible to set autofocus on input elements

<input type="text" class="b_calle" id="b_calle" placeholder="Buscar por nombre de calle" autofocus="autofocus">

SQL: How to get the id of values I just INSERTed?

From the site i found out the following things:

SQL SERVER – @@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record March 25, 2007 by pinaldave

SELECT @@IDENTITY It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value. @@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.

SELECT SCOPE_IDENTITY() It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value. SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.

SELECT IDENT_CURRENT(‘tablename’) It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

How do you detect/avoid Memory leaks in your (Unmanaged) code?

Memory debugging tools are worth their weight in gold but over the years I've found that two simple ideas can be used to prevent most memory/resource leaks from being coded in the first place.

  1. Write release code immediatly after writing the acquisition code for the resources you want to allocate. With this method its harder to "forget" and in some sense forces one to seriously think of the lifecycle of resources being used upfront instead of as an aside.

  2. Use return as sparringly as possible. What is allocated should only be freed in one place if possible. The conditional path between acquisition of resource and release should be designed to be as simple and obvious as possible.

Get month and year from a datetime in SQL Server 2005

returns the full month name, -, full year e.g. March-2017

CONCAT(DATENAME(mm, GetDate()), '-', DATEPART(yy, GetDate()))

MySQL Error 1093 - Can't specify target table for update in FROM clause

If you can't do

UPDATE table SET a=value WHERE x IN
    (SELECT x FROM table WHERE condition);

because it is the same table, you can trick and do :

UPDATE table SET a=value WHERE x IN
    (SELECT * FROM (SELECT x FROM table WHERE condition) as t)

[update or delete or whatever]

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

I've had this problem a lot, and just did again. I tried fixing it using these suggestions, and nothing worked. I finally found that I had the 'Title' attribute in the page header twice(I added to the end, not realizing that VS added a blank Title="" to the beginning)-- removing the extra attribute caused VS2008 to re-generate the designer file... I hope VS2010 fixes this problem, letting us know why the designer file generation isn't happening...

-- Derek

Why does the order in which libraries are linked sometimes cause errors in GCC?

A quick tip that tripped me up: if you're invoking the linker as "gcc" or "g++", then using "--start-group" and "--end-group" won't pass those options through to the linker -- nor will it flag an error. It will just fail the link with undefined symbols if you had the library order wrong.

You need to write them as "-Wl,--start-group" etc. to tell GCC to pass the argument through to the linker.

How to parse a string into a nullable int

This solution is generic without reflection overhead.

public static Nullable<T> ParseNullable<T>(string s, Func<string, T> parser) where T : struct
{
    if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(s.Trim())) return null;
    else return parser(s);
}

static void Main(string[] args)
{
    Nullable<int> i = ParseNullable("-1", int.Parse);
    Nullable<float> dt = ParseNullable("3.14", float.Parse);
}

Safely turning a JSON string into an object

If we have a string like this:

"{\"status\":1,\"token\":\"65b4352b2dfc4957a09add0ce5714059\"}"

then we can simply use JSON.parse twice to convert this string to a JSON object:

var sampleString = "{\"status\":1,\"token\":\"65b4352b2dfc4957a09add0ce5714059\"}"
var jsonString= JSON.parse(sampleString)
var jsonObject= JSON.parse(jsonString)

And we can extract values from the JSON object using:

// instead of last JSON.parse:
var { status, token } = JSON.parse(jsonString);

The result will be:

status = 1 and token = 65b4352b2dfc4957a09add0ce5714059

Complex CSS selector for parent of active child

I had the same problem with Drupal. Given the limitations of CSS, the way to get this working is to add the "active" class to the parent elements when the menu HTML is generated. There's a good discussion of this at http://drupal.org/node/219804, the upshot of which is that this functionality has been rolled in to version 6.x-2.x of the nicemenus module. As this is still in development, I've backported the patch to 6.x-1.3 at http://drupal.org/node/465738 so that I can continue to use the production-ready version of the module.

What is a monad?

According to What we talk about when we talk about monads the question "What is a monad" is wrong:

The short answer to the question "What is a monad?" is that it is a monoid in the category of endofunctors or that it is a generic data type equipped with two operations that satisfy certain laws. This is correct, but it does not reveal an important bigger picture. This is because the question is wrong. In this paper, we aim to answer the right question, which is "What do authors really say when they talk about monads?"

While that paper does not directly answer what a monad is it helps understanding what people with different backgrounds mean when they talk about monads and why.

Explicit vs implicit SQL joins

Performance wise, they are exactly the same (at least in SQL Server) but be aware that they are deprecating this join syntax and it's not supported by sql server2005 out of the box.

I think you are thinking of the deprecated *= and =* operators vs. "outer join".

I have just now tested the two formats given, and they work properly on a SQL Server 2008 database. In my case they yielded identical execution plans, but I couldn't confidently say that this would always be true.

Java Delegates?

It doesn't have an explicit delegate keyword as C#, but you can achieve similar in Java 8 by using a functional interface (i.e. any interface with exactly one method) and lambda:

private interface SingleFunc {
    void printMe();
}

public static void main(String[] args) {
    SingleFunc sf = () -> {
        System.out.println("Hello, I am a simple single func.");
    };
    SingleFunc sfComplex = () -> {
        System.out.println("Hello, I am a COMPLEX single func.");
    };
    delegate(sf);
    delegate(sfComplex);
}

private static void delegate(SingleFunc f) {
    f.printMe();
}

Every new object of type SingleFunc must implement printMe(), so it is safe to pass it to another method (e.g. delegate(SingleFunc)) to call the printMe() method.

C# switch statement limitations - why?

This is my original post, which sparked some debate... because it is wrong:

The switch statement is not the same thing as a big if-else statement. Each case must be unique and evaluated statically. The switch statement does a constant time branch regardless of how many cases you have. The if-else statement evaluates each condition until it finds one that is true.


In fact, the C# switch statement is not always a constant time branch.

In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table. However, in sparse cases as pointed out by Ivan Hamilton the compiler may generate something else entirely.

This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool.

Can someone explain __all__ in Python?

I'm just adding this to be precise:

All other answers refer to modules. The original question explicitely mentioned __all__ in __init__.py files, so this is about python packages.

Generally, __all__ only comes into play when the from xxx import * variant of the import statement is used. This applies to packages as well as to modules.

The behaviour for modules is explained in the other answers. The exact behaviour for packages is described here in detail.

In short, __all__ on package level does approximately the same thing as for modules, except it deals with modules within the package (in contrast to specifying names within the module). So __all__ specifies all modules that shall be loaded and imported into the current namespace when us use from package import *.

The big difference is, that when you omit the declaration of __all__ in a package's __init__.py, the statement from package import * will not import anything at all (with exceptions explained in the documentation, see link above).

On the other hand, if you omit __all__ in a module, the "starred import" will import all names (not starting with an underscore) defined in the module.

How would you make a comma-separated string from a list of strings?

@jmanning2k using a list comprehension has the downside of creating a new temporary list. The better solution would be using itertools.imap which returns an iterator

from itertools import imap
l = [1, "foo", 4 ,"bar"]
",".join(imap(str, l))

VB.NET Empty String Array

Not sure why you'd want to, but the C# way would be

string[] newArray = new string[0];

I'm guessing that VB won't be too dissimilar to this.

If you're building an empty array so you can populate it with values later, you really should consider using

List<string>

and converting it to an array (if you really need it as an array) with

newListOfString.ToArray();

Reading Email using Pop3 in C#

I've successfully used OpenPop.NET to access emails via POP3.

Add alternating row color to SQL Server Reporting services report

for group headers/footers:

=iif(RunningValue(*group on field*,CountDistinct,"*parent group name*") Mod 2,"White","AliceBlue")

You can also use this to “reset” the row color count within each group. I wanted the first detail row in each sub group to start with White and this solution (when used on the detail row) allowed that to happen:

=IIF(RunningValue(Fields![Name].Value, CountDistinct, "NameOfPartnetGroup") Mod 2, "White", "Wheat")

See: http://msdn.microsoft.com/en-us/library/ms159136(v=sql.100).aspx

How do I get the current location of an iframe?

HTA works like a normal windows application.
You write HTML code, and save it as an .hta file.

However, there are, at least, one drawback: The browser can't open an .hta file; it's handled as a normal .exe program. So, if you place a link to an .hta onto your web page, it will open a download dialog, asking of you want to open or save the HTA file. If its not a problem for you, you can click "Open" and it will open a new window (that have no toolbars, so no Back button, neither address bar, neither menubar).

I needed to do something very similar to what you want, but instead of iframes, I used a real frameset.
The main page need to be a .hta file; the other should be a normal .htm page (or .php or whatever).

Here's an example of a HTA page with 2 frames, where the top one have a button and a text field, that contains the second frame URL; the button updates the field:

frameset.hta

<html>
    <head>
        <title>HTA Example</title>
        <HTA:APPLICATION id="frames" border="thin" caption="yes" icon="http://www.google.com/favicon.ico" showintaskbar="yes" singleinstance="no" sysmenu="yes" navigable="yes" contextmenu="no" innerborder="no" scroll="auto" scrollflat="yes" selection="yes" windowstate="normal"></HTA:APPLICATION>
    </head>
    <frameset rows="60px, *">
        <frame src="topo.htm" name="topo" id="topo" application="yes" />
        <frame src="http://www.google.com" name="conteudo" id="conteudo" application="yes" />
    </frameset>
</html>
  • There's an HTA:APPLICATION tag that sets some properties to the file; it's good to have, but it isn't a must.
  • You NEED to place an application="yes" at the frames' tags. It says they belongs to the program too and should have access to all data (if you don't, the frames will still show the error you had before).

topo.htm

<html>
    <head>
        <title>Topo</title>
        <script type="text/javascript">
            function copia_url() {
                campo.value = parent.conteudo.location;
            }
        </script>
    </head>
    <body style="background: lightBlue;" onload="copia_url()">
        <input type="button" value="Copiar URL" onclick="copia_url()" />
        <input type="text" size="120" id="campo" />
    </body>
</html>
  • You should notice that I didn't used any getElement function to fetch the field; on HTA file, all elements that have an ID becomes instantly an object

I hope this help you, and others that get to this question. It solved my problem, that looks like to be the same as you have.

You can found more information here: http://www.irt.org/articles/js191/index.htm

Enjoy =]

Differences in string compare methods in C#

Here are the rules for how these functions work:

stringValue.CompareTo(otherStringValue)

  1. null comes before a string
  2. it uses CultureInfo.CurrentCulture.CompareInfo.Compare, which means it will use a culture-dependent comparison. This might mean that ß will compare equal to SS in Germany, or similar

stringValue.Equals(otherStringValue)

  1. null is not considered equal to anything
  2. unless you specify a StringComparison option, it will use what looks like a direct ordinal equality check, i.e. ß is not the same as SS, in any language or culture

stringValue == otherStringValue

  1. Is not the same as stringValue.Equals().
  2. The == operator calls the static Equals(string a, string b) method (which in turn goes to an internal EqualsHelper to do the comparison.
  3. Calling .Equals() on a null string gets null reference exception, while on == does not.

Object.ReferenceEquals(stringValue, otherStringValue)

Just checks that references are the same, i.e. it isn't just two strings with the same contents, you're comparing a string object with itself.


Note that with the options above that use method calls, there are overloads with more options to specify how to compare.

My advice if you just want to check for equality is to make up your mind whether you want to use a culture-dependent comparison or not, and then use .CompareTo or .Equals, depending on the choice.

Extending the User model with custom fields in Django

The below one is another approach to extend an User. I feel it is more clear,easy,readable then above two approaches.

http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/

Using above approach:

  1. you don't need to use user.get_profile().newattribute to access the additional information related to the user
  2. you can just directly access additional new attributes via user.newattribute

Changing the default title of confirm() in JavaScript?

Yes, this is impossible to modify the title of it. If you still want to have your own title, you can try to use other pop-up windows instead.

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

I claim no credit for the answer because I found it after some searching:

What I didn't know is that PostgreSQL allows you to define your own aggregate functions with CREATE AGGREGATE

This post on the PostgreSQL list shows how trivial it is to create a function to do what's required:

CREATE AGGREGATE textcat_all(
  basetype    = text,
  sfunc       = textcat,
  stype       = text,
  initcond    = ''
);

SELECT company_id, textcat_all(employee || ', ')
FROM mytable
GROUP BY company_id;

How SID is different from Service name in Oracle tnsnames.ora

what is a SID and Service name

please look into oracle's documentation at https://docs.oracle.com/cd/B19306_01/network.102/b14212/concepts.htm

In case if the above link is not accessable in future, At the time time of writing this answer, the above link will direct you to, "Database Service and Database Instance Identification" topic in Connectivity Concepts chapter of "Database Net Services Administrator's Guide". This guide is published by oracle as part of "Oracle Database Online Documentation, 10g Release 2 (10.2)"

When I have to use one or another? Why do I need two of them?

Consider below mapping in a RAC Environment,

SID      SERVICE_NAME
bob1    bob
bob2    bob
bob3    bob
bob4    bob

if load balancing is configured, the listener will 'balance' the workload across all four SIDs. Even if load balancing is configured, you can connect to bob1 all the time if you want to by using the SID instead of SERVICE_NAME.

Please refer, https://community.oracle.com/thread/4049517

How to convert a date String to a Date or Calendar object?

The DateFormat class has a parse method.

See DateFormat for more information.

How do I style (css) radio buttons and labels?

The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.

Getting the Label Near the Radio Button

I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float: territory):

  • Use <br />s to split the options apart and some CSS to vertically align them:
<style type='text/css'>
    .input input
    {
        width: 20px;
    }
</style>
<div class="input radio">
    <fieldset>
        <legend>What color is the sky?</legend>
        <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1"  />
        <label for="SubmitQuestion1">A strange radient green.</label>
        <br />
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2"  />
        <label for="SubmitQuestion2">A dark gloomy orange</label>
        <br />
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3"  />
        <label for="SubmitQuestion3">A perfect glittering blue</label>
    </fieldset>
</div>

Applying a Style to the Currently Selected Label + Radio Button

Styling the <label> is why you'll need to resort to Javascript. A library like jQuery is perfect for this:

<style type='text/css'>
    .input label.focused
    {
        background-color: #EEEEEE;
        font-style: italic;
    }
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
    $(document).ready(function() {
        $('.input :radio').focus(updateSelectedStyle);
        $('.input :radio').blur(updateSelectedStyle);
        $('.input :radio').change(updateSelectedStyle);
    })

    function updateSelectedStyle() {
        $('.input :radio').removeClass('focused').next().removeClass('focused');
        $('.input :radio:checked').addClass('focused').next().addClass('focused');
    }
</script>

The focus and blur hooks are needed to make this work in IE.

How to find the mime type of a file in python?

There are 3 different libraries that wraps libmagic.

2 of them are available on pypi (so pip install will work):

  • filemagic
  • python-magic

And another, similar to python-magic is available directly in the latest libmagic sources, and it is the one you probably have in your linux distribution.

In Debian the package python-magic is about this one and it is used as toivotuo said and it is not obsoleted as Simon Zimmermann said (IMHO).

It seems to me another take (by the original author of libmagic).

Too bad is not available directly on pypi.

Can I write native iPhone apps using Python?

Yes you can. You write your code in tinypy (which is restricted Python), then use tinypy to convert it to C++, and finally compile this with XCode into a native iPhone app. Phil Hassey has published a game called Elephants! using this approach. Here are more details,

http://www.philhassey.com/blog/2009/12/23/elephants-is-free-on-the-app-store/

Comparing two byte arrays in .NET

The short answer is this:

    public bool Compare(byte[] b1, byte[] b2)
    {
        return Encoding.ASCII.GetString(b1) == Encoding.ASCII.GetString(b2);
    }

In such a way you can use the optimized .NET string compare to make a byte array compare without the need to write unsafe code. This is how it is done in the background:

private unsafe static bool EqualsHelper(String strA, String strB)
{
    Contract.Requires(strA != null);
    Contract.Requires(strB != null);
    Contract.Requires(strA.Length == strB.Length);

    int length = strA.Length;

    fixed (char* ap = &strA.m_firstChar) fixed (char* bp = &strB.m_firstChar)
    {
        char* a = ap;
        char* b = bp;

        // Unroll the loop

        #if AMD64
            // For the AMD64 bit platform we unroll by 12 and
            // check three qwords at a time. This is less code
            // than the 32 bit case and is shorter
            // pathlength.

            while (length >= 12)
            {
                if (*(long*)a     != *(long*)b)     return false;
                if (*(long*)(a+4) != *(long*)(b+4)) return false;
                if (*(long*)(a+8) != *(long*)(b+8)) return false;
                a += 12; b += 12; length -= 12;
            }
       #else
           while (length >= 10)
           {
               if (*(int*)a != *(int*)b) return false;
               if (*(int*)(a+2) != *(int*)(b+2)) return false;
               if (*(int*)(a+4) != *(int*)(b+4)) return false;
               if (*(int*)(a+6) != *(int*)(b+6)) return false;
               if (*(int*)(a+8) != *(int*)(b+8)) return false;
               a += 10; b += 10; length -= 10;
           }
       #endif

        // This depends on the fact that the String objects are
        // always zero terminated and that the terminating zero is not included
        // in the length. For odd string sizes, the last compare will include
        // the zero terminator.
        while (length > 0)
        {
            if (*(int*)a != *(int*)b) break;
            a += 2; b += 2; length -= 2;
        }

        return (length <= 0);
    }
}

T-SQL stored procedure that accepts multiple Id values

One method you might want to consider if you're going to be working with the values a lot is to write them to a temporary table first. Then you just join on it like normal.

This way, you're only parsing once.

It's easiest to use one of the 'Split' UDFs, but so many people have posted examples of those, I figured I'd go a different route ;)

This example will create a temporary table for you to join on (#tmpDept) and fill it with the department id's that you passed in. I'm assuming you're separating them with commas, but you can -- of course -- change it to whatever you want.

IF OBJECT_ID('tempdb..#tmpDept', 'U') IS NOT NULL
BEGIN
    DROP TABLE #tmpDept
END

SET @DepartmentIDs=REPLACE(@DepartmentIDs,' ','')

CREATE TABLE #tmpDept (DeptID INT)
DECLARE @DeptID INT
IF IsNumeric(@DepartmentIDs)=1
BEGIN
    SET @DeptID=@DepartmentIDs
    INSERT INTO #tmpDept (DeptID) SELECT @DeptID
END
ELSE
BEGIN
        WHILE CHARINDEX(',',@DepartmentIDs)>0
        BEGIN
            SET @DeptID=LEFT(@DepartmentIDs,CHARINDEX(',',@DepartmentIDs)-1)
            SET @DepartmentIDs=RIGHT(@DepartmentIDs,LEN(@DepartmentIDs)-CHARINDEX(',',@DepartmentIDs))
            INSERT INTO #tmpDept (DeptID) SELECT @DeptID
        END
END

This will allow you to pass in one department id, multiple id's with commas in between them, or even multiple id's with commas and spaces between them.

So if you did something like:

SELECT Dept.Name 
FROM Departments 
JOIN #tmpDept ON Departments.DepartmentID=#tmpDept.DeptID
ORDER BY Dept.Name

You would see the names of all of the department IDs that you passed in...

Again, this can be simplified by using a function to populate the temporary table... I mainly did it without one just to kill some boredom :-P

-- Kevin Fairchild

How do I calculate a trendline for a graph?

Thanks to all for your help - I was off this issue for a couple of days and just came back to it - was able to cobble this together - not the most elegant code, but it works for my purposes - thought I'd share if anyone else encounters this issue:

public class Statistics
{
    public Trendline CalculateLinearRegression(int[] values)
    {
        var yAxisValues = new List<int>();
        var xAxisValues = new List<int>();

        for (int i = 0; i < values.Length; i++)
        {
            yAxisValues.Add(values[i]);
            xAxisValues.Add(i + 1);
        }

        return new Trendline(yAxisValues, xAxisValues);
    }
}

public class Trendline
{
    private readonly IList<int> xAxisValues;
    private readonly IList<int> yAxisValues;
    private int count;
    private int xAxisValuesSum;
    private int xxSum;
    private int xySum;
    private int yAxisValuesSum;

    public Trendline(IList<int> yAxisValues, IList<int> xAxisValues)
    {
        this.yAxisValues = yAxisValues;
        this.xAxisValues = xAxisValues;

        this.Initialize();
    }

    public int Slope { get; private set; }
    public int Intercept { get; private set; }
    public int Start { get; private set; }
    public int End { get; private set; }

    private void Initialize()
    {
        this.count = this.yAxisValues.Count;
        this.yAxisValuesSum = this.yAxisValues.Sum();
        this.xAxisValuesSum = this.xAxisValues.Sum();
        this.xxSum = 0;
        this.xySum = 0;

        for (int i = 0; i < this.count; i++)
        {
            this.xySum += (this.xAxisValues[i]*this.yAxisValues[i]);
            this.xxSum += (this.xAxisValues[i]*this.xAxisValues[i]);
        }

        this.Slope = this.CalculateSlope();
        this.Intercept = this.CalculateIntercept();
        this.Start = this.CalculateStart();
        this.End = this.CalculateEnd();
    }

    private int CalculateSlope()
    {
        try
        {
            return ((this.count*this.xySum) - (this.xAxisValuesSum*this.yAxisValuesSum))/((this.count*this.xxSum) - (this.xAxisValuesSum*this.xAxisValuesSum));
        }
        catch (DivideByZeroException)
        {
            return 0;
        }
    }

    private int CalculateIntercept()
    {
        return (this.yAxisValuesSum - (this.Slope*this.xAxisValuesSum))/this.count;
    }

    private int CalculateStart()
    {
        return (this.Slope*this.xAxisValues.First()) + this.Intercept;
    }

    private int CalculateEnd()
    {
        return (this.Slope*this.xAxisValues.Last()) + this.Intercept;
    }
}

What are some resources for getting started in operating system development?

There are good resources for operating system fundamentals in books. Since there isn't much call to create new OS's from scratch you won't find a ton of hobbyist type information on the internet.

I recommend the standard text book, "Modern Operating Systems" by Tanenbaum. You may also be able to find "Operating System Elements" by Calingaert useful - it's a thin overview of a book which give a rough sketch of what an OS is from a designer's standpoint.

If you have any interest in real time systems (and you should at least understand the differences and reasons for real time OS's) then I'd also recommend "MicroC/OS-II" by Labrosse.

Edit:

Can you specify what you mean by "more technical"? These books give pseudo code implementation details, but are you looking for an example OS, or code snippets for a particular machine/language?

-Adam

Easy way to write contents of a Java InputStream to an OutputStream

Using Java7 and try-with-resources, comes with a simplified and readable version.

try(InputStream inputStream = new FileInputStream("C:\\mov.mp4");
    OutputStream outputStream = new FileOutputStream("D:\\mov.mp4")) {

    byte[] buffer = new byte[10*1024];

    for (int length; (length = inputStream.read(buffer)) != -1; ) {
        outputStream.write(buffer, 0, length);
    }
} catch (FileNotFoundException exception) {
    exception.printStackTrace();
} catch (IOException ioException) {
    ioException.printStackTrace();
}

Algorithm to randomly generate an aesthetically-pleasing color palette

It's going to be hard to get what you want algorithmically - people have been studying color theory for a long time, and they don't even know all the rules.

However, there are some rules which you can use to cull bad color combinations (ie, there are rules for clashing colors, and choosing complementary colors).

I'd recommend you visit your library's art section and check out books on color theory to gain a better understanding of what is a good color before you try to make one - it appears you might not even know why certain combinations work and others don't.

-Adam

How do you get the index of the current iteration of a foreach loop?

Better to use keyword continue safe construction like this

int i=-1;
foreach (Object o in collection)
{
    ++i;
    //...
    continue; //<--- safe to call, index will be increased
    //...
}

How to get the last day of the month?

In the code below 'get_last_day_of_month(dt)' will give you this, with date in string format like 'YYYY-MM-DD'.

import datetime

def DateTime( d ):
    return datetime.datetime.strptime( d, '%Y-%m-%d').date()

def RelativeDate( start, num_days ):
    d = DateTime( start )
    return str( d + datetime.timedelta( days = num_days ) )

def get_first_day_of_month( dt ):
    return dt[:-2] + '01'

def get_last_day_of_month( dt ):
    fd = get_first_day_of_month( dt )
    fd_next_month = get_first_day_of_month( RelativeDate( fd, 31 ) )
    return RelativeDate( fd_next_month, -1 )

Best way to get identity of inserted row?

After Your Insert Statement you need to add this. And Make sure about the table name where data is inserting.You will get current row no where row affected just now by your insert statement.

IDENT_CURRENT('tableName')

How do I call ::CreateProcess in c++ to launch a Windows executable?

Something like this:

STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
    WaitForSingleObject(processInfo.hProcess, INFINITE);
    CloseHandle(processInfo.hProcess);
    CloseHandle(processInfo.hThread);
}

How do you rotate a two dimensional array?

C# code to rotate [n,m] 2D arrays 90 deg right

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MatrixProject
{
    // mattrix class

    class Matrix{
        private int rows;
        private int cols;
        private int[,] matrix;

        public Matrix(int n){
            this.rows = n;
            this.cols = n;
            this.matrix = new int[this.rows,this.cols];

        }

        public Matrix(int n,int m){
            this.rows = n;
            this.cols = m;

            this.matrix = new int[this.rows,this.cols];
        }

        public void Show()
        {
            for (var i = 0; i < this.rows; i++)
            {
                for (var j = 0; j < this.cols; j++) {
                    Console.Write("{0,3}", this.matrix[i, j]);
                }
                Console.WriteLine();
            }                
        }

        public void ReadElements()
        {
           for (var i = 0; i < this.rows; i++)
                for (var j = 0; j < this.cols; j++)
                {
                    Console.Write("element[{0},{1}]=",i,j);
                    this.matrix[i, j] = Convert.ToInt32(Console.ReadLine());
                }            
        }


        // rotate [n,m] 2D array by 90 deg right
        public void Rotate90DegRight()
        {

            // create a mirror of current matrix
            int[,] mirror = this.matrix;

            // create a new matrix
            this.matrix = new int[this.cols, this.rows];

            for (int i = 0; i < this.rows; i++)
            {
                for (int j = 0; j < this.cols; j++)
                {
                    this.matrix[j, this.rows - i - 1] = mirror[i, j];
                }
            }

            // replace cols count with rows count
            int tmp = this.rows;
            this.rows = this.cols;
            this.cols = tmp;           
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Matrix myMatrix = new Matrix(3,4);
            Console.WriteLine("Enter matrix elements:");
            myMatrix.ReadElements();
            Console.WriteLine("Matrix elements are:");
            myMatrix.Show();
            myMatrix.Rotate90DegRight();
            Console.WriteLine("Matrix rotated at 90 deg are:");
            myMatrix.Show();
            Console.ReadLine();
        }
    }
}

Result:

    Enter matrix elements:
    element[0,0]=1
    element[0,1]=2
    element[0,2]=3
    element[0,3]=4
    element[1,0]=5
    element[1,1]=6
    element[1,2]=7
    element[1,3]=8
    element[2,0]=9
    element[2,1]=10
    element[2,2]=11
    element[2,3]=12
    Matrix elements are:
      1  2  3  4
      5  6  7  8
      9 10 11 12
    Matrix rotated at 90 deg are:
      9  5  1
     10  6  2
     11  7  3
     12  8  4

How do you get the footer to stay at the bottom of a Web page?

A similar solution to @gcedo but without the need of adding an intermediate content in order to push the footer down. We can simply add margin-top:auto to the footer and it will be pushed to the bottom of the page regardless his height or the height of the content above.

_x000D_
_x000D_
body {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  min-height: 100vh;_x000D_
  margin:0;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  padding: 50px;_x000D_
  background: red;_x000D_
}_x000D_
_x000D_
.footer {_x000D_
  margin-top: auto;_x000D_
  padding:10px;_x000D_
  background: green;_x000D_
}
_x000D_
<div class="content">_x000D_
  some content here_x000D_
</div>_x000D_
<footer class="footer">_x000D_
  some content_x000D_
</footer>
_x000D_
_x000D_
_x000D_

function declaration isn't a prototype

Try:

extern int testlib(void);

How do I handle newlines in JSON?

You could just escape your string on the server when writing the value of the JSON field and unescape it when retrieving the value in the client browser, for instance.

The JavaScript implementation of all major browsers have the unescape command.

Example:

On the server:

response.write "{""field1"":""" & escape(RS_Temp("textField")) & """}"

In the browser:

document.getElementById("text1").value = unescape(jsonObject.field1)

How do I get the difference between two Dates in JavaScript?

If you don't care about the time component, you can use .getDate() and .setDate() to just set the date part.

So to set your end date to 2 weeks after your start date, do something like this:

function GetEndDate(startDate)
{
    var endDate = new Date(startDate.getTime());
    endDate.setDate(endDate.getDate()+14);
    return endDate;
}

To return the difference (in days) between two dates, do this:

function GetDateDiff(startDate, endDate)
{
    return endDate.getDate() - startDate.getDate();
}

Finally, let's modify the first function so it can take the value returned by 2nd as a parameter:

function GetEndDate(startDate, days)
{
    var endDate = new Date(startDate.getTime());
    endDate.setDate(endDate.getDate() + days);
    return endDate;
}

How do I download code using SVN/Tortoise from Google Code?

If you are behind a firewall you will have to configure the Tortoise client to connect to it. Right click somewhere in your window, select "TortoiseSVN", select "settings", and then select "network" on the left side of the panel. Fill out all the required fields. Good luck.

How do you properly use namespaces in C++?

Note that a namespace in C++ really is just a name space. They don't provide any of the encapsulation that packages do in Java, so you probably won't use them as much.

Use of var keyword in C#

None, except that you don't have to write the type name twice. http://msdn.microsoft.com/en-us/library/bb383973.aspx

How can I add reflection to a C++ application?

The RareCpp library makes for fairly easy and intuitive reflection - all field/type information is designed to either be available in arrays or to feel like array access. It's written for C++17 and works with Visual Studios, g++, and Clang. The library is header only, meaning you need only copy "Reflect.h" into your project to use it.

Reflected structs or classes need the REFLECT macro, where you supply the name of the class you're reflecting and the names of the fields.

class FuelTank {
    public:
        float capacity;
        float currentLevel;
        float tickMarks[2];

    REFLECT(FuelTank, capacity, currentLevel, tickMarks)
};

That's all there is, no additional code is needed to setup reflection. Optionally you can supply superclasses (in the parenthesis of the first argument) and field annotations (in the parenthesis preceeding the field you want to annotate) to be able to traverse superclasses or add additional compile-time information to a field (such as Json::Ignore).

Looping through fields can be as simple as...

for ( size_t i=0; i<FuelTank::Class::TotalFields; i++ )
    std::cout << FuelTank::Class::Fields[i].name << std::endl;

You can loop through an object instance to access field values (which you can read or modify) and field type information...

FuelTank::Class::ForEachField(fuelTank, [&](auto & field, auto & value) {
    using Type = typename std::remove_reference<decltype(value)>::type;
    std::cout << TypeToStr<Type>() << " " << field.name << ": " << value << std::endl;
});

A JSON Library is built on top of RandomAccessReflection which auto identifies appropriate JSON output representations for reading or writing, and can recursively traverse any reflected fields, as well as arrays and STL containers.

struct MyOtherObject { int myOtherInt; REFLECT(MyOtherObject, myOtherInt) };
struct MyObject
{
    int myInt;
    std::string myString;
    MyOtherObject myOtherObject;
    std::vector<int> myIntCollection;

    REFLECT(MyObject, myInt, myString, myOtherObject, myIntCollection)
};

int main()
{
    MyObject myObject = {};
    std::cout << "Enter MyObject:" << std::endl;
    std::cin >> Json::in(myObject);
    std::cout << std::endl << std::endl << "You entered:" << std::endl;
    std::cout << Json::pretty(myObject);
}

The above could be ran like so...

Enter MyObject:
{
  "myInt": 1337, "myString": "stringy", "myIntCollection": [2,4,6],
  "myOtherObject": {
    "myOtherInt": 9001
  }
}


You entered:
{
  "myInt": 1337,
  "myString": "stringy",
  "myOtherObject": {
    "myOtherInt": 9001
  },
  "myIntCollection": [ 2, 4, 6 ]
}

See also...

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

  1. Delete the temp test directory located here C:\Users(User)\AppData\Local\Temp\VisualStudioTestExplorerExtensions\

  2. Set all projects to x64 in Visual Studio

  3. Set the default processor architecture to x64(Test/TestSettings/Default Processor Architecture).

Make sure to clean build the solution file.Hope this helps!

Checking if a list is empty with LINQ

Ok, so what about this one?

public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
{
    return !enumerable.GetEnumerator().MoveNext();
}

EDIT: I've just realized that someone has sketched this solution already. It was mentioned that the Any() method will do this, but why not do it yourself? Regards

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

Too easy without any complication:

  1. Add using System.Linq.Dynamic; at the top.
  2. Use vehicles = vehicles.AsQueryable().OrderBy("Make ASC, Year DESC").ToList();

Java and SQLite

I found your question while searching for information with SQLite and Java. Just thought I'd add my answer which I also posted on my blog.

I have been coding in Java for a while now. I have also known about SQLite but never used it… Well I have used it through other applications but never in an app that I coded. So I needed it for a project this week and it's so simple use!

I found a Java JDBC driver for SQLite. Just add the JAR file to your classpath and import java.sql.*

His test app will create a database file, send some SQL commands to create a table, store some data in the table, and read it back and display on console. It will create the test.db file in the root directory of the project. You can run this example with java -cp .:sqlitejdbc-v056.jar Test.

package com.rungeek.sqlite;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Test {
    public static void main(String[] args) throws Exception {
        Class.forName("org.sqlite.JDBC");
        Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
        Statement stat = conn.createStatement();
        stat.executeUpdate("drop table if exists people;");
        stat.executeUpdate("create table people (name, occupation);");
        PreparedStatement prep = conn.prepareStatement(
            "insert into people values (?, ?);");

        prep.setString(1, "Gandhi");
        prep.setString(2, "politics");
        prep.addBatch();
        prep.setString(1, "Turing");
        prep.setString(2, "computers");
        prep.addBatch();
        prep.setString(1, "Wittgenstein");
        prep.setString(2, "smartypants");
        prep.addBatch();

        conn.setAutoCommit(false);
        prep.executeBatch();
        conn.setAutoCommit(true);

        ResultSet rs = stat.executeQuery("select * from people;");
        while (rs.next()) {
            System.out.println("name = " + rs.getString("name"));
            System.out.println("job = " + rs.getString("occupation"));
        }
        rs.close();
        conn.close();
    }
  }

WCF Service Returning "Method Not Allowed"

I ran into this exact same issue today. I had installed IIS, but did not have the activate WCF Services Enabled under .net framework 4.6.

enter image description here

How to generate a random alpha-numeric string

public static String getRandomString(int length) {
    char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST".toCharArray();

    StringBuilder sb = new StringBuilder();
    Random random = new Random();
    for (int i = 0; i < length; i++) {
        char c = chars[random.nextInt(chars.length)];
        sb.append(c);
    }
    String randomStr = sb.toString();

    return randomStr;
}

Find in Files: Search all code in Team Foundation Server

We have set up a solution for Team Foundation Server Source Control (not SourceSafe as you mention) similar to what Grant suggests; scheduled TF Get, Search Server Express. However the IFilter used for C# files (text) was not giving the results we wanted, so we convert source files to .htm files. We can now add additional meta-data to the files such as:

  • Author (we define it as the person that last checked in the file)
  • Color coding (on our todo-list)
  • Number of changes indicating potential design problems (on our todo-list)
  • Integrate with the VSTS IDE like Koders SmartSearch feature
  • etc.

We would however prefer a protocolhandler for TFS Source Control, and a dedicated source code IFilter for a much more targeted solution.

How to Automatically Start a Download in PHP?

Send the following headers before outputting the file:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");

@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)

Execute a large SQL script (with GO commands)

To avoid third parties, regexes, memory overheads and fast work with large scripts I created my own stream-based parser. It

  • checks syntax before
  • can recognize comments with -- or /**/

    -- some commented text
     /*
    drop table Users;
    GO
       */
    
  • can recognize string literals with ' or "

    set @s =
        'create table foo(...);
        GO
        create index ...';
    
  • preserves LF and CR formatting
  • preserves comments block in object bodies (stored procedures, views etc.)
  • and other constructions such as

          gO -- commented text
    

How to use

    try
    {
        using (SqlConnection connection = new SqlConnection("Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=DATABASE-NAME;Data Source=SERVER-NAME"))
        {
            connection.Open();

            int rowsAffected = SqlStatementReader.ExecuteSqlFile(
                "C:\\target-sql-script.sql",
                connection,
                // Don't forget to use the correct file encoding!!!
                Encoding.Default,
                // Indefinitely (sec)
                0
            );
        }
    }
    // implement your handlers
    catch (SqlStatementReader.SqlBadSyntaxException) { }
    catch (SqlException) { }
    catch (Exception) { }

Stream-based SQL script reader

class SqlStatementReader
{
    public class SqlBadSyntaxException : Exception
    {
        public SqlBadSyntaxException(string description) : base(description) { }
        public SqlBadSyntaxException(string description, int line) : base(OnBase(description, line, null)) { }
        public SqlBadSyntaxException(string description, int line, string filePath) : base(OnBase(description, line, filePath)) { }
        private static string OnBase(string description, int line, string filePath)
        {
            if (filePath == null)
                return string.Format("Line: {0}. {1}", line, description);
            else
                return string.Format("File: {0}\r\nLine: {1}. {2}", filePath, line, description);
        }
    }

    enum SqlScriptChunkTypes
    {
        InstructionOrUnquotedIdentifier = 0,
        BracketIdentifier = 1,
        QuotIdentifierOrLiteral = 2,
        DblQuotIdentifierOrLiteral = 3,
        CommentLine = 4,
        CommentMultiline = 5,
    }

    StreamReader _sr = null;
    string _filePath = null;
    int _lineStart = 1;
    int _lineEnd = 1;
    bool _isNextChar = false;
    char _nextChar = '\0';

    public SqlStatementReader(StreamReader sr)
    {
        if (sr == null)
            throw new ArgumentNullException("StreamReader can't be null.");

        if (sr.BaseStream is FileStream)
            _filePath = ((FileStream)sr.BaseStream).Name;

        _sr = sr;
    }

    public SqlStatementReader(StreamReader sr, string filePath)
    {
        if (sr == null)
            throw new ArgumentNullException("StreamReader can't be null.");

        _sr = sr;
        _filePath = filePath;
    }

    public int LineStart { get { return _lineStart; } }
    public int LineEnd { get { return _lineEnd == 1 ? _lineEnd : _lineEnd - 1; } }

    public void LightSyntaxCheck()
    {
        while (ReadStatementInternal(true) != null) ;
    }

    public string ReadStatement()
    {
        for (string s = ReadStatementInternal(false); s != null; s = ReadStatementInternal(false))
        {
            // skip empty
            for (int i = 0; i < s.Length; i++)
            {
                switch (s[i])
                {
                    case ' ': continue;
                    case '\t': continue;
                    case '\r': continue;
                    case '\n': continue;
                    default:
                        return s;
                }
            }
        }
        return null;
    }

    string ReadStatementInternal(bool syntaxCheck)
    {
        if (_isNextChar == false && _sr.EndOfStream)
            return null;

        StringBuilder allLines = new StringBuilder();
        StringBuilder line = new StringBuilder();
        SqlScriptChunkTypes nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
        SqlScriptChunkTypes currentChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
        char ch = '\0';
        int lineCounter = 0;
        int nextLine = 0;
        int currentLine = 0;
        bool nextCharHandled = false;
        bool foundGO;
        int go = 1;

        while (ReadChar(out ch))
        {
            if (nextCharHandled == false)
            {
                currentChunk = nextChunk;
                currentLine = nextLine;

                switch (currentChunk)
                {
                    case SqlScriptChunkTypes.InstructionOrUnquotedIdentifier:

                        if (ch == '[')
                        {
                            currentChunk = nextChunk = SqlScriptChunkTypes.BracketIdentifier;
                            currentLine = nextLine = lineCounter;
                        }
                        else if (ch == '"')
                        {
                            currentChunk = nextChunk = SqlScriptChunkTypes.DblQuotIdentifierOrLiteral;
                            currentLine = nextLine = lineCounter;
                        }
                        else if (ch == '\'')
                        {
                            currentChunk = nextChunk = SqlScriptChunkTypes.QuotIdentifierOrLiteral;
                            currentLine = nextLine = lineCounter;
                        }
                        else if (ch == '-' && (_isNextChar && _nextChar == '-'))
                        {
                            nextCharHandled = true;
                            currentChunk = nextChunk = SqlScriptChunkTypes.CommentLine;
                            currentLine = nextLine = lineCounter;
                        }
                        else if (ch == '/' && (_isNextChar && _nextChar == '*'))
                        {
                            nextCharHandled = true;
                            currentChunk = nextChunk = SqlScriptChunkTypes.CommentMultiline;
                            currentLine = nextLine = lineCounter;
                        }
                        else if (ch == ']')
                        {
                            throw new SqlBadSyntaxException("Incorrect syntax near ']'.", _lineEnd + lineCounter, _filePath);
                        }
                        else if (ch == '*' && (_isNextChar && _nextChar == '/'))
                        {
                            throw new SqlBadSyntaxException("Incorrect syntax near '*'.", _lineEnd + lineCounter, _filePath);
                        }
                        break;

                    case SqlScriptChunkTypes.CommentLine:

                        if (ch == '\r' && (_isNextChar && _nextChar == '\n'))
                        {
                            nextCharHandled = true;
                            currentChunk = nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
                            currentLine = nextLine = lineCounter;
                        }
                        else if (ch == '\n' || ch == '\r')
                        {
                            currentChunk = nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
                            currentLine = nextLine = lineCounter;
                        }
                        break;

                    case SqlScriptChunkTypes.CommentMultiline:

                        if (ch == '*' && (_isNextChar && _nextChar == '/'))
                        {
                            nextCharHandled = true;
                            nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
                            nextLine = lineCounter;
                        }
                        else if (ch == '/' && (_isNextChar && _nextChar == '*'))
                        {
                            throw new SqlBadSyntaxException("Missing end comment mark '*/'.", _lineEnd + currentLine, _filePath);
                        }
                        break;

                    case SqlScriptChunkTypes.BracketIdentifier:

                        if (ch == ']')
                        {
                            nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
                            nextLine = lineCounter;
                        }
                        break;

                    case SqlScriptChunkTypes.DblQuotIdentifierOrLiteral:

                        if (ch == '"')
                        {
                            if (_isNextChar && _nextChar == '"')
                            {
                                nextCharHandled = true;
                            }
                            else
                            {
                                nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
                                nextLine = lineCounter;
                            }
                        }
                        break;

                    case SqlScriptChunkTypes.QuotIdentifierOrLiteral:

                        if (ch == '\'')
                        {
                            if (_isNextChar && _nextChar == '\'')
                            {
                                nextCharHandled = true;
                            }
                            else
                            {
                                nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
                                nextLine = lineCounter;
                            }
                        }
                        break;
                }
            }
            else
                nextCharHandled = false;

            foundGO = false;
            if (currentChunk == SqlScriptChunkTypes.InstructionOrUnquotedIdentifier || go >= 5 || (go == 4 && currentChunk == SqlScriptChunkTypes.CommentLine))
            {
                // go = 0 - break, 1 - begin of the string, 2 - spaces after begin of the string, 3 - G or g, 4 - O or o, 5 - spaces after GO, 6 - line comment after valid GO
                switch (go)
                {
                    case 0:
                        if (ch == '\r' || ch == '\n')
                            go = 1;
                        break;
                    case 1:
                        if (ch == ' ' || ch == '\t')
                            go = 2;
                        else if (ch == 'G' || ch == 'g')
                            go = 3;
                        else if (ch != '\n' && ch != '\r')
                            go = 0;
                        break;
                    case 2:
                        if (ch == 'G' || ch == 'g')
                            go = 3;
                        else if (ch == '\n' || ch == '\r')
                            go = 1;
                        else if (ch != ' ' && ch != '\t')
                            go = 0;
                        break;
                    case 3:
                        if (ch == 'O' || ch == 'o')
                            go = 4;
                        else if (ch == '\n' || ch == '\r')
                            go = 1;
                        else
                            go = 0;
                        break;
                    case 4:
                        if (ch == '\r' && (_isNextChar && _nextChar == '\n'))
                            go = 5;
                        else if (ch == '\n' || ch == '\r')
                            foundGO = true;
                        else if (ch == ' ' || ch == '\t')
                            go = 5;
                        else if (ch == '-' && (_isNextChar && _nextChar == '-'))
                            go = 6;
                        else
                            go = 0;
                        break;
                    case 5:
                        if (ch == '\r' && (_isNextChar && _nextChar == '\n'))
                            go = 5;
                        else if (ch == '\n' || ch == '\r')
                            foundGO = true;
                        else if (ch == '-' && (_isNextChar && _nextChar == '-'))
                            go = 6;
                        else if (ch != ' ' && ch != '\t')
                            throw new SqlBadSyntaxException("Incorrect syntax was encountered while parsing go.", _lineEnd + lineCounter, _filePath);
                        break;
                    case 6:
                        if (ch == '\r' && (_isNextChar && _nextChar == '\n'))
                            go = 6;
                        else if (ch == '\n' || ch == '\r')
                            foundGO = true;
                        break;
                    default:
                        go = 0;
                        break;
                }
            }
            else
                go = 0;

            if (foundGO)
            {
                if (ch == '\r' || ch == '\n')
                {
                    ++lineCounter;
                }
                // clear GO
                string s = line.Append(ch).ToString();
                for (int i = 0; i < s.Length; i++)
                {
                    switch (s[i])
                    {
                        case ' ': continue;
                        case '\t': continue;
                        case '\r': continue;
                        case '\n': continue;
                        default:
                            _lineStart = _lineEnd;
                            _lineEnd += lineCounter;
                            return allLines.Append(s.Substring(0, i)).ToString();
                    }
                }
                return string.Empty;
            }

            // accumulate by string
            if (ch == '\r' && (_isNextChar == false || _nextChar != '\n'))
            {
                ++lineCounter;
                if (syntaxCheck == false)
                    allLines.Append(line.Append('\r').ToString());
                line.Clear();
            }
            else if (ch == '\n')
            {
                ++lineCounter;
                if (syntaxCheck == false)
                    allLines.Append(line.Append('\n').ToString());
                line.Clear();
            }
            else
            {
                if (syntaxCheck == false)
                    line.Append(ch);
            }
        }

        // this is the end of the stream, return it without GO, if GO exists
        switch (currentChunk)
        {
            case SqlScriptChunkTypes.InstructionOrUnquotedIdentifier:
            case SqlScriptChunkTypes.CommentLine:
                break;
            case SqlScriptChunkTypes.CommentMultiline:
                if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)
                    throw new SqlBadSyntaxException("Missing end comment mark '*/'.", _lineEnd + currentLine, _filePath);
                break;
            case SqlScriptChunkTypes.BracketIdentifier:
                if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)
                    throw new SqlBadSyntaxException("Unclosed quotation mark [.", _lineEnd + currentLine, _filePath);
                break;
            case SqlScriptChunkTypes.DblQuotIdentifierOrLiteral:
                if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)
                    throw new SqlBadSyntaxException("Unclosed quotation mark \".", _lineEnd + currentLine, _filePath);
                break;
            case SqlScriptChunkTypes.QuotIdentifierOrLiteral:
                if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)
                    throw new SqlBadSyntaxException("Unclosed quotation mark '.", _lineEnd + currentLine, _filePath);
                break;
        }

        if (go >= 4)
        {
            string s = line.ToString();
            for (int i = 0; i < s.Length; i++)
            {
                switch (s[i])
                {
                    case ' ': continue;
                    case '\t': continue;
                    case '\r': continue;
                    case '\n': continue;
                    default:
                        _lineStart = _lineEnd;
                        _lineEnd += lineCounter + 1;
                        return allLines.Append(s.Substring(0, i)).ToString();
                }
            }
        }

        _lineStart = _lineEnd;
        _lineEnd += lineCounter + 1;
        return allLines.Append(line.ToString()).ToString();
    }

    bool ReadChar(out char ch)
    {
        if (_isNextChar)
        {
            ch = _nextChar;
            if (_sr.EndOfStream)
                _isNextChar = false;
            else
                _nextChar = Convert.ToChar(_sr.Read());
            return true;
        }
        else if (_sr.EndOfStream == false)
        {
            ch = Convert.ToChar(_sr.Read());
            if (_sr.EndOfStream == false)
            {
                _isNextChar = true;
                _nextChar = Convert.ToChar(_sr.Read());
            }
            return true;
        }
        else
        {
            ch = '\0';
            return false;
        }
    }

    public static int ExecuteSqlFile(string filePath, SqlConnection connection, Encoding fileEncoding, int commandTimeout)
    {
        int rowsAffected = 0;
        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            // Simple syntax check (you can comment out these two lines below)
            new SqlStatementReader(new StreamReader(fs, fileEncoding)).LightSyntaxCheck();
            fs.Seek(0L, SeekOrigin.Begin);

            // Read statements without GO
            SqlStatementReader rd = new SqlStatementReader(new StreamReader(fs, fileEncoding));
            string stmt;
            while ((stmt = rd.ReadStatement()) != null)
            {
                using (SqlCommand cmd = connection.CreateCommand())
                {
                    cmd.CommandText = stmt;
                    cmd.CommandTimeout = commandTimeout;
                    int i = cmd.ExecuteNonQuery();
                    if (i > 0)
                        rowsAffected += i;
                }
            }
        }
        return rowsAffected;
    }
}

How should I cast in VB.NET?

At one time, I remember seeing the MSDN library state to use CStr() because it was faster. I do not know if this is true though.

What is the best way to give a C# auto-property an initial value?

In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.

Since C# 6.0, you can specify initial value in-line. The syntax is:

public int X { get; set; } = x; // C# 6 or higher

DefaultValueAttribute is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).

At compile time DefaultValueAttribute will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property).

Example of attributes that impact the IL are ThreadStaticAttribute, CallerMemberNameAttribute, ...

How do I size a UITextView to its content?

This no longer works on iOS 7 or above

There is actually a very easy way to do resizing of the UITextView to its correct height of the content. It can be done using the UITextView contentSize.

CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;

One thing to note is that the correct contentSize is only available after the UITextView has been added to the view with addSubview. Prior to that it is equal to frame.size

This will not work if auto layout is ON. With auto layout, the general approach is to use the sizeThatFits method and update the constant value on a height constraint.

CGSize sizeThatShouldFitTheContent = [_textView sizeThatFits:_textView.frame.size];
heightConstraint.constant = sizeThatShouldFitTheContent.height;

heightConstraint is a layout constraint that you typically setup via a IBOutlet by linking the property to the height constraint created in a storyboard.


Just to add to this amazing answer, 2014, if you:

[self.textView sizeToFit];

there is a difference in behaviour with the iPhone6+ only:

enter image description here

With the 6+ only (not the 5s or 6) it does add "one more blank line" to the UITextView. The "RL solution" fixes this perfectly:

CGRect _f = self.mainPostText.frame;
_f.size.height = self.mainPostText.contentSize.height;
self.mainPostText.frame = _f;

It fixes the "extra line" problem on 6+.

How to show all shared libraries used by executables in Linux?

Check shared library dependencies of a program executable

To find out what libraries a particular executable depends on, you can use ldd command. This command invokes dynamic linker to find out library dependencies of an executable.

> $ ldd /path/to/program

Note that it is NOT recommended to run ldd with any untrusted third-party executable because some versions of ldd may directly invoke the executable to identify its library dependencies, which can be security risk.

Instead, a safer way to show library dependencies of an unknown application binary is to use the following command.

$ objdump -p /path/to/program | grep NEEDED

for more info

Comparing two collections for equality irrespective of the order of items in them

A duplicate post of sorts, but check out my solution for comparing collections. It's pretty simple:

This will perform an equality comparison regardless of order:

var list1 = new[] { "Bill", "Bob", "Sally" };
var list2 = new[] { "Bob", "Bill", "Sally" };
bool isequal = list1.Compare(list2).IsSame;

This will check to see if items were added / removed:

var list1 = new[] { "Billy", "Bob" };
var list2 = new[] { "Bob", "Sally" };
var diff = list1.Compare(list2);
var onlyinlist1 = diff.Removed; //Billy
var onlyinlist2 = diff.Added;   //Sally
var inbothlists = diff.Equal;   //Bob

This will see what items in the dictionary changed:

var original = new Dictionary<int, string>() { { 1, "a" }, { 2, "b" } };
var changed = new Dictionary<int, string>() { { 1, "aaa" }, { 2, "b" } };
var diff = original.Compare(changed, (x, y) => x.Value == y.Value, (x, y) => x.Value == y.Value);
foreach (var item in diff.Different)
  Console.Write("{0} changed to {1}", item.Key.Value, item.Value.Value);
//Will output: a changed to aaa

Original post here.

How to pass password to scp?

Use sshpass:

sshpass -p "password" scp -r [email protected]:/some/remote/path /some/local/path

or so the password does not show in the bash history

sshpass -f "/path/to/passwordfile" scp -r [email protected]:/some/remote/path /some/local/path

The above copies contents of path from the remote host to your local.

Install :

  • ubuntu/debian
    • apt install sshpass
  • centos/fedora
    • yum install sshpass
  • mac w/ macports
    • port install sshpass
  • mac w/ brew
    • brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb

Really killing a process in Windows

taskkill /im myprocess.exe /f

The "/f" is for "force". If you know the PID, then you can specify that, as in:

taskkill /pid 1234 /f

Lots of other options are possible, just type taskkill /? for all of them. The "/t" option kills a process and any child processes; that may be useful to you.

Count a list of cells with the same background color

The worksheet formula, =CELL("color",D3) returns 1 if the cell is formatted with color for negative values (else returns 0).

You can solve this with a bit of VBA. Insert this into a VBA code module:

Function CellColor(xlRange As Excel.Range)
    CellColor = xlRange.Cells(1, 1).Interior.ColorIndex
End Function

Then use the function =CellColor(D3) to display the .ColorIndex of D3

What is the difference between UNION and UNION ALL?

UNION merges the contents of two structurally-compatible tables into a single combined table.

  • Difference:

The difference between UNION and UNION ALL is that UNION will omit duplicate records whereas UNION ALL will include duplicate records.

Union Result set is sorted in ascending order whereas UNION ALL Result set is not sorted

UNION performs a DISTINCT on its Result set so it will eliminate any duplicate rows. Whereas UNION ALL won't remove duplicates and therefore it is faster than UNION.*

Note: The performance of UNION ALL will typically be better than UNION, since UNION requires the server to do the additional work of removing any duplicates. So, in cases where it is certain that there will not be any duplicates, or where having duplicates is not a problem, use of UNION ALL would be recommended for performance reasons.

How do we control web page caching, across all browsers?

Not sure if my answer sounds simple and stupid, and perhaps it has already been known to you since long time ago, but since preventing someone from using browser back button to view your historical pages is one of your goals, you can use:

window.location.replace("https://www.example.com/page-not-to-be-viewed-in-browser-history-back-button.html");

Of course, this may not be possible to be implemented across the entire site, but at least for some critical pages, you can do that. Hope this helps.

Git ignore file for Xcode projects

I recommend using joe to generate a .gitignore file.

For an iOS project run the following command:

$ joe g osx,xcode > .gitignore

It will generate this .gitignore:

.DS_Store
.AppleDouble
.LSOverride

Icon
._*

.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns

.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

build/
DerivedData

*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata

*.xccheckout
*.moved-aside
*.xcuserstate

How do I export (and then import) a Subversion repository?

Basically, there are plenty of ways to accomplish the task. The topic is covered in depth in SVNBook | Migrating Repository Data Elsewhere, so I suggest reading the book's section.

Here is a brief description of your options:

  • It depends on your environment, but there is a great chance that you can simply copy the repository to the new server and it will work. You have to revise repository hook scripts after copying the repo to ensure that they are working as you expect.

  • You can use svnadmin dump and svnadmin load commands to, ehm, generate full dump and then load it to another repository on another server. You will need to svnadmin create a new clean repository to load the dump into it. Keep in mind that the approach deals with repository history only and does not move hook scripts and repository configuration files! As well, you must have read filesystem access to the original repository to dump it.

  • Since Subversion 1.7, svnrdump tool is available. Generally speaking, it mimics svnadmin dump and svnadmin load functionality, but operates remotely. You are not required to have read / write filesystem access to original and target repositories as tool operates remotely like Subversion client, e.g. over HTTPS protocol. So you need to have read access to original repository and read / write to the target one.

  • Another option is to use svnadmin hotcopy command. The command is mostly used for backup purpose, it creates full copy of the repository including configuration and hook scripts. You can move hotcopied repository to another server then.

How do I create a MessageBox in C#?

This is some of the things you can put into a message box. Enjoy
MessageBox.Show("Enter the text for the message box",
"Enter the name of the message box",
(Enter the button names e.g. MessageBoxButtons.YesNo),
(Enter the icon e.g. MessageBoxIcon.Question),
(Enter the default button e.g. MessageBoxDefaultButton.Button1)

More information can be found here

How can I make an EXE file from a Python program?

See a short list of python packaging tools on FreeHackers.org.

How do I write a for loop in bash

Try the bash built-in help:


$ help for

for: for NAME [in WORDS ... ;] do COMMANDS; done
    The `for' loop executes a sequence of commands for each member in a
    list of items.  If `in WORDS ...;' is not present, then `in "$@"' is
    assumed.  For each element in WORDS, NAME is set to that element, and
    the COMMANDS are executed.
for ((: for (( exp1; exp2; exp3 )); do COMMANDS; done
    Equivalent to
        (( EXP1 ))
        while (( EXP2 )); do
            COMMANDS
            (( EXP3 ))
        done
    EXP1, EXP2, and EXP3 are arithmetic expressions.  If any expression is
    omitted, it behaves as if it evaluates to 1.


Prefer composition over inheritance?

This rule is a complete nonsense. Why?

The reason is that in every case it is possible to tell whether to use composition or inheritance. This is determined by the answer to a question: "IS something A something else" or "HAS something A something else".

You cannot "prefer" to make something to be something else or to have something else. Strict logical rules apply.

Also there are no "contrived examples" because in every situation an answer to this question can be given.

If you cannot answer this question there is something else wrong. This includes overlapping responsibilities of classess which are usually the result of wrong use of interfaces, less often by rewriting same code in different classess.

To avoid this situations I also recommend to use good names for classes , that fully resemble their responsibilities.

How do I implement a callback in PHP?

For those who don't care about breaking compatibility with PHP < 5.4, I'd suggest using type hinting to make a cleaner implementation.

function call_with_hello_and_append_world( callable $callback )
{
     // No need to check $closure because of the type hint
     return $callback( "hello" )."world";
}

function append_space( $string )
{
     return $string." ";
}

$output1 = call_with_hello_and_append_world( function( $string ) { return $string." "; } );
var_dump( $output1 ); // string(11) "hello world"

$output2 = call_with_hello_and_append_world( "append_space" );
var_dump( $output2 ); // string(11) "hello world"

$old_lambda = create_function( '$string', 'return $string." ";' );
$output3 = call_with_hello_and_append_world( $old_lambda );
var_dump( $output3 ); // string(11) "hello world"

How do I list loaded plugins in Vim?

:help local-additions

Lists local plugins added.

How do I create a foreign key in SQL Server?

Like you, I don't usually create foreign keys by hand, but if for some reason I need the script to do so I usually create it using ms sql server management studio and before saving then changes, I select Table Designer | Generate Change Script

How do I position one image on top of another in HTML?

Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.

Getting the ID of the element that fired an event

I'm working with

jQuery Autocomplete

I tried looking for an event as described above, but when the request function fires it doesn't seem to be available. I used this.element.attr("id") to get the element's ID instead, and it seems to work fine.

How can you find out which process is listening on a TCP or UDP port on Windows?

To find out which specific process (PID) is using which port:

netstat -anon | findstr 1234

Where 1234 is the PID of your process. [Go to Task Manager → Services/Processes tab to find out the PID of your application.]

Generating (pseudo)random alpha-numeric strings

Simple guys .... but remember each byte is random between 0 and 255 which for a random string will be fine. Also remember you'll have two characters to represent each byte.

$str = bin2hex(random_bytes(32));  // 64 character string returned

Select N random elements from a List<T> in C#

You can use this but the ordering will happen on client side

 .AsEnumerable().OrderBy(n => Guid.NewGuid()).Take(5);

How do you set, clear, and toggle a single bit?

Let suppose few things first
num = 55 Integer to perform bitwise operations (set, get, clear, toggle).
n = 4 0 based bit position to perform bitwise operations.

How to get a bit?

  1. To get the nth bit of num right shift num, n times. Then perform bitwise AND & with 1.
bit = (num >> n) & 1;

How it works?

       0011 0111 (55 in decimal)
    >>         4 (right shift 4 times)
-----------------
       0000 0011
     & 0000 0001 (1 in decimal)
-----------------
    => 0000 0001 (final result)

How to set a bit?

  1. To set a particular bit of number. Left shift 1 n times. Then perform bitwise OR | operation with num.
num |= (1 << n);    // Equivalent to; num = (1 << n) | num;

How it works?

       0000 0001 (1 in decimal)
    <<         4 (left shift 4 times)
-----------------
       0001 0000
     | 0011 0111 (55 in decimal)
-----------------
    => 0001 0000 (final result)

How to clear a bit?

  1. Left shift 1, n times i.e. 1 << n.
  2. Perform bitwise complement with the above result. So that the nth bit becomes unset and rest of bit becomes set i.e. ~ (1 << n).
  3. Finally, perform bitwise AND & operation with the above result and num. The above three steps together can be written as num & (~ (1 << n));

Steps to clear a bit

num &= (~(1 << n));    // Equivalent to; num = num & (~(1 << n));

How it works?

       0000 0001 (1 in decimal)
    <<         4 (left shift 4 times)
-----------------
     ~ 0001 0000
-----------------
       1110 1111
     & 0011 0111 (55 in decimal)
-----------------
    => 0010 0111 (final result)

How to toggle a bit?

To toggle a bit we use bitwise XOR ^ operator. Bitwise XOR operator evaluates to 1 if corresponding bit of both operands are different, otherwise evaluates to 0.

Which means to toggle a bit, we need to perform XOR operation with the bit you want to toggle and 1.

num ^= (1 << n);    // Equivalent to; num = num ^ (1 << n);

How it works?

  • If the bit to toggle is 0 then, 0 ^ 1 => 1.
  • If the bit to toggle is 1 then, 1 ^ 1 => 0.
       0000 0001 (1 in decimal)
    <<         4 (left shift 4 times)
-----------------
       0001 0000
     ^ 0011 0111 (55 in decimal)
-----------------
    => 0010 0111 (final result)

Recommended reading - Bitwise operator exercises

round() doesn't seem to be rounding properly

What about:

round(n,1)+epsilon

Objective-C for Windows

Check out WinObjC:

https://github.com/Microsoft/WinObjC

It's an official, open-source project by Microsoft that integrates with Visual Studio + Windows.

How do you clear the SQL Server transaction log?

Use the DBCC ShrinkFile ({logicalLogName}, TRUNCATEONLY) command. If this is a test database and you are trying to save/reclaim space, this will help.

Remember though that TX logs do have a sort of minimum/steady state size that they will grow up to. Depending upon your recovery model you may not be able to shrink the log - if in FULL and you aren't issuing TX log backups the log can't be shrunk - it will grow forever. If you don't need TX log backups, switch your recovery model to Simple.

And remember, never ever under any circumstances delete the log (LDF) file! You will pretty much have instant database corruption. Cooked! Done! Lost data! If left "unrepaired" the main MDF file could become corrupt permanently.

Never ever delete the transaction log - you will lose data! Part of your data is in the TX Log (regardless of recovery model)... if you detach and "rename" the TX log file that effectively deletes part of your database.

For those that have deleted the TX Log you may want to run a few checkdb commands and fix the corruption before you lose more data.

Check out Paul Randal's blog posts on this very topic, bad advice.

Also in general do not use shrinkfile on the MDF files as it can severely fragment your data. Check out his Bad Advice section for more info ("Why you should not shrink your data files")

Check out Paul's website - he covers these very questions. Last month he walked through many of these issues in his Myth A Day series.

Can I run a 64-bit VMware image on a 32-bit machine?

If you have 32-bit hardware, no, you cannot run a 64-bit guest OS. "VMware software does not emulate an instruction set for different hardware not physically present".

However, QEMU can emulate a 64-bit processor, so you could convert the VMWare machine and run it with this

From this 2008-era blog post (mirrored by archive.org):

$ cd /path/to/vmware/guestos
$ for i in \`ls *[0-9].vmdk\`; do qemu-img convert -f vmdk $i -O raw {i/vmdk/raw};done
$ cat *.raw >> guestos.img

To run it,

qemu -m 256 -hda guestos.img

The downside? Most of us runs VMware without preallocation space for the virtual disk. So, when we make a conversion from VMware to QEMU, the raw file will be the total space WITH preallocation. I am still testing with -f qcow format will it solve the problem or not. Such as:

for i in `ls *[0-9].vmdk`; do qemu-img convert -f vmdk $i -O qcow ${i/vmdk/qcow}; done && cat *.qcow >> debian.img