Programs & Examples On #Init

May refer to Linux Init - the parent of all processes, which primary role is to create processes from a script stored in the file /etc/inittab. Or abbreviation of initialization - giving variables a "starting" value.

How to run a command as a specific user in an init script?

If you have start-stop-daemon

start-stop-daemon --start --quiet -u username -g usergroup --exec command ...

How to return a value from __init__ in Python?

Well, if you don't care about the object instance anymore ... you can just replace it!

class MuaHaHa():
def __init__(self, ret):
    self=ret

print MuaHaHa('foo')=='foo'

What is the use of the init() usage in JavaScript?

JavaScript doesn't have a built-in init() function, that is, it's not a part of the language. But it's not uncommon (in a lot of languages) for individual programmers to create their own init() function for initialisation stuff.

A particular init() function may be used to initialise the whole webpage, in which case it would probably be called from document.ready or onload processing, or it may be to initialise a particular type of object, or...well, you name it.

What any given init() does specifically is really up to whatever the person who wrote it needed it to do. Some types of code don't need any initialisation.

function init() {
  // initialisation stuff here
}

// elsewhere in code
init();

When is the init() function run?

Take for example a framework or a library you're designing for other users, these users eventually will have a main function in their code in order to execute their app. If the user directly imports a sub-package of your library's project then the init of that sub-package will be called(once) first of all. The same for the root package of the library, etc...

There are many times when you may want a code block to be executed without the existence of a main func, directly or not.

If you, as the developer of the imaginary library, import your library's sub-package that has an init function, it will be called first and once, you don't have a main func but you need to make sure that some variables, or a table, will be initialized before the calls of other functions.

A good thing to remember and not to worry about, is that: the init always execute once per application.

init execution happens:

  1. right before the init function of the "caller" package,
  2. before the, optionally, main func,
  3. but after the package-level variables, var = [...] or cost = [...],

When you import a package it will run all of its init functions, by order.

I'll will give a very good example of an init function. It will add mime types to a standard go's library named mime and a package-level function will use the mime standard package directly to get the custom mime types that are already be initialized at its init function:

package mime

import (
    "mime"
    "path/filepath"
)

var types = map[string]string{
    ".3dm":       "x-world/x-3dmf",
    ".3dmf":      "x-world/x-3dmf",
    ".7z":        "application/x-7z-compressed",
    ".a":         "application/octet-stream",
    ".aab":       "application/x-authorware-bin",
    ".aam":       "application/x-authorware-map",
    ".aas":       "application/x-authorware-seg",
    ".abc":       "text/vndabc",
    ".ace":       "application/x-ace-compressed",
    ".acgi":      "text/html",
    ".afl":       "video/animaflex",
    ".ai":        "application/postscript",
    ".aif":       "audio/aiff",
    ".aifc":      "audio/aiff",
    ".aiff":      "audio/aiff",
    ".aim":       "application/x-aim",
    ".aip":       "text/x-audiosoft-intra",
    ".alz":       "application/x-alz-compressed",
    ".ani":       "application/x-navi-animation",
    ".aos":       "application/x-nokia-9000-communicator-add-on-software",
    ".aps":       "application/mime",
    ".apk":       "application/vnd.android.package-archive",
    ".arc":       "application/x-arc-compressed",
    ".arj":       "application/arj",
    ".art":       "image/x-jg",
    ".asf":       "video/x-ms-asf",
    ".asm":       "text/x-asm",
    ".asp":       "text/asp",
    ".asx":       "application/x-mplayer2",
    ".au":        "audio/basic",
    ".avi":       "video/x-msvideo",
    ".avs":       "video/avs-video",
    ".bcpio":     "application/x-bcpio",
    ".bin":       "application/mac-binary",
    ".bmp":       "image/bmp",
    ".boo":       "application/book",
    ".book":      "application/book",
    ".boz":       "application/x-bzip2",
    ".bsh":       "application/x-bsh",
    ".bz2":       "application/x-bzip2",
    ".bz":        "application/x-bzip",
    ".c++":       "text/plain",
    ".c":         "text/x-c",
    ".cab":       "application/vnd.ms-cab-compressed",
    ".cat":       "application/vndms-pkiseccat",
    ".cc":        "text/x-c",
    ".ccad":      "application/clariscad",
    ".cco":       "application/x-cocoa",
    ".cdf":       "application/cdf",
    ".cer":       "application/pkix-cert",
    ".cha":       "application/x-chat",
    ".chat":      "application/x-chat",
    ".chrt":      "application/vnd.kde.kchart",
    ".class":     "application/java",
    ".com":       "text/plain",
    ".conf":      "text/plain",
    ".cpio":      "application/x-cpio",
    ".cpp":       "text/x-c",
    ".cpt":       "application/mac-compactpro",
    ".crl":       "application/pkcs-crl",
    ".crt":       "application/pkix-cert",
    ".crx":       "application/x-chrome-extension",
    ".csh":       "text/x-scriptcsh",
    ".css":       "text/css",
    ".csv":       "text/csv",
    ".cxx":       "text/plain",
    ".dar":       "application/x-dar",
    ".dcr":       "application/x-director",
    ".deb":       "application/x-debian-package",
    ".deepv":     "application/x-deepv",
    ".def":       "text/plain",
    ".der":       "application/x-x509-ca-cert",
    ".dif":       "video/x-dv",
    ".dir":       "application/x-director",
    ".divx":      "video/divx",
    ".dl":        "video/dl",
    ".dmg":       "application/x-apple-diskimage",
    ".doc":       "application/msword",
    ".dot":       "application/msword",
    ".dp":        "application/commonground",
    ".drw":       "application/drafting",
    ".dump":      "application/octet-stream",
    ".dv":        "video/x-dv",
    ".dvi":       "application/x-dvi",
    ".dwf":       "drawing/x-dwf=(old)",
    ".dwg":       "application/acad",
    ".dxf":       "application/dxf",
    ".dxr":       "application/x-director",
    ".el":        "text/x-scriptelisp",
    ".elc":       "application/x-bytecodeelisp=(compiled=elisp)",
    ".eml":       "message/rfc822",
    ".env":       "application/x-envoy",
    ".eps":       "application/postscript",
    ".es":        "application/x-esrehber",
    ".etx":       "text/x-setext",
    ".evy":       "application/envoy",
    ".exe":       "application/octet-stream",
    ".f77":       "text/x-fortran",
    ".f90":       "text/x-fortran",
    ".f":         "text/x-fortran",
    ".fdf":       "application/vndfdf",
    ".fif":       "application/fractals",
    ".fli":       "video/fli",
    ".flo":       "image/florian",
    ".flv":       "video/x-flv",
    ".flx":       "text/vndfmiflexstor",
    ".fmf":       "video/x-atomic3d-feature",
    ".for":       "text/x-fortran",
    ".fpx":       "image/vndfpx",
    ".frl":       "application/freeloader",
    ".funk":      "audio/make",
    ".g3":        "image/g3fax",
    ".g":         "text/plain",
    ".gif":       "image/gif",
    ".gl":        "video/gl",
    ".gsd":       "audio/x-gsm",
    ".gsm":       "audio/x-gsm",
    ".gsp":       "application/x-gsp",
    ".gss":       "application/x-gss",
    ".gtar":      "application/x-gtar",
    ".gz":        "application/x-compressed",
    ".gzip":      "application/x-gzip",
    ".h":         "text/x-h",
    ".hdf":       "application/x-hdf",
    ".help":      "application/x-helpfile",
    ".hgl":       "application/vndhp-hpgl",
    ".hh":        "text/x-h",
    ".hlb":       "text/x-script",
    ".hlp":       "application/hlp",
    ".hpg":       "application/vndhp-hpgl",
    ".hpgl":      "application/vndhp-hpgl",
    ".hqx":       "application/binhex",
    ".hta":       "application/hta",
    ".htc":       "text/x-component",
    ".htm":       "text/html",
    ".html":      "text/html",
    ".htmls":     "text/html",
    ".htt":       "text/webviewhtml",
    ".htx":       "text/html",
    ".ice":       "x-conference/x-cooltalk",
    ".ico":       "image/x-icon",
    ".ics":       "text/calendar",
    ".icz":       "text/calendar",
    ".idc":       "text/plain",
    ".ief":       "image/ief",
    ".iefs":      "image/ief",
    ".iges":      "application/iges",
    ".igs":       "application/iges",
    ".ima":       "application/x-ima",
    ".imap":      "application/x-httpd-imap",
    ".inf":       "application/inf",
    ".ins":       "application/x-internett-signup",
    ".ip":        "application/x-ip2",
    ".isu":       "video/x-isvideo",
    ".it":        "audio/it",
    ".iv":        "application/x-inventor",
    ".ivr":       "i-world/i-vrml",
    ".ivy":       "application/x-livescreen",
    ".jam":       "audio/x-jam",
    ".jav":       "text/x-java-source",
    ".java":      "text/x-java-source",
    ".jcm":       "application/x-java-commerce",
    ".jfif-tbnl": "image/jpeg",
    ".jfif":      "image/jpeg",
    ".jnlp":      "application/x-java-jnlp-file",
    ".jpe":       "image/jpeg",
    ".jpeg":      "image/jpeg",
    ".jpg":       "image/jpeg",
    ".jps":       "image/x-jps",
    ".js":        "application/javascript",
    ".json":      "application/json",
    ".jut":       "image/jutvision",
    ".kar":       "audio/midi",
    ".karbon":    "application/vnd.kde.karbon",
    ".kfo":       "application/vnd.kde.kformula",
    ".flw":       "application/vnd.kde.kivio",
    ".kml":       "application/vnd.google-earth.kml+xml",
    ".kmz":       "application/vnd.google-earth.kmz",
    ".kon":       "application/vnd.kde.kontour",
    ".kpr":       "application/vnd.kde.kpresenter",
    ".kpt":       "application/vnd.kde.kpresenter",
    ".ksp":       "application/vnd.kde.kspread",
    ".kwd":       "application/vnd.kde.kword",
    ".kwt":       "application/vnd.kde.kword",
    ".ksh":       "text/x-scriptksh",
    ".la":        "audio/nspaudio",
    ".lam":       "audio/x-liveaudio",
    ".latex":     "application/x-latex",
    ".lha":       "application/lha",
    ".lhx":       "application/octet-stream",
    ".list":      "text/plain",
    ".lma":       "audio/nspaudio",
    ".log":       "text/plain",
    ".lsp":       "text/x-scriptlisp",
    ".lst":       "text/plain",
    ".lsx":       "text/x-la-asf",
    ".ltx":       "application/x-latex",
    ".lzh":       "application/octet-stream",
    ".lzx":       "application/lzx",
    ".m1v":       "video/mpeg",
    ".m2a":       "audio/mpeg",
    ".m2v":       "video/mpeg",
    ".m3u":       "audio/x-mpegurl",
    ".m":         "text/x-m",
    ".man":       "application/x-troff-man",
    ".manifest":  "text/cache-manifest",
    ".map":       "application/x-navimap",
    ".mar":       "text/plain",
    ".mbd":       "application/mbedlet",
    ".mc$":       "application/x-magic-cap-package-10",
    ".mcd":       "application/mcad",
    ".mcf":       "text/mcf",
    ".mcp":       "application/netmc",
    ".me":        "application/x-troff-me",
    ".mht":       "message/rfc822",
    ".mhtml":     "message/rfc822",
    ".mid":       "application/x-midi",
    ".midi":      "application/x-midi",
    ".mif":       "application/x-frame",
    ".mime":      "message/rfc822",
    ".mjf":       "audio/x-vndaudioexplosionmjuicemediafile",
    ".mjpg":      "video/x-motion-jpeg",
    ".mm":        "application/base64",
    ".mme":       "application/base64",
    ".mod":       "audio/mod",
    ".moov":      "video/quicktime",
    ".mov":       "video/quicktime",
    ".movie":     "video/x-sgi-movie",
    ".mp2":       "audio/mpeg",
    ".mp3":       "audio/mpeg3",
    ".mp4":       "video/mp4",
    ".mpa":       "audio/mpeg",
    ".mpc":       "application/x-project",
    ".mpe":       "video/mpeg",
    ".mpeg":      "video/mpeg",
    ".mpg":       "video/mpeg",
    ".mpga":      "audio/mpeg",
    ".mpp":       "application/vndms-project",
    ".mpt":       "application/x-project",
    ".mpv":       "application/x-project",
    ".mpx":       "application/x-project",
    ".mrc":       "application/marc",
    ".ms":        "application/x-troff-ms",
    ".mv":        "video/x-sgi-movie",
    ".my":        "audio/make",
    ".mzz":       "application/x-vndaudioexplosionmzz",
    ".nap":       "image/naplps",
    ".naplps":    "image/naplps",
    ".nc":        "application/x-netcdf",
    ".ncm":       "application/vndnokiaconfiguration-message",
    ".nif":       "image/x-niff",
    ".niff":      "image/x-niff",
    ".nix":       "application/x-mix-transfer",
    ".nsc":       "application/x-conference",
    ".nvd":       "application/x-navidoc",
    ".o":         "application/octet-stream",
    ".oda":       "application/oda",
    ".odb":       "application/vnd.oasis.opendocument.database",
    ".odc":       "application/vnd.oasis.opendocument.chart",
    ".odf":       "application/vnd.oasis.opendocument.formula",
    ".odg":       "application/vnd.oasis.opendocument.graphics",
    ".odi":       "application/vnd.oasis.opendocument.image",
    ".odm":       "application/vnd.oasis.opendocument.text-master",
    ".odp":       "application/vnd.oasis.opendocument.presentation",
    ".ods":       "application/vnd.oasis.opendocument.spreadsheet",
    ".odt":       "application/vnd.oasis.opendocument.text",
    ".oga":       "audio/ogg",
    ".ogg":       "audio/ogg",
    ".ogv":       "video/ogg",
    ".omc":       "application/x-omc",
    ".omcd":      "application/x-omcdatamaker",
    ".omcr":      "application/x-omcregerator",
    ".otc":       "application/vnd.oasis.opendocument.chart-template",
    ".otf":       "application/vnd.oasis.opendocument.formula-template",
    ".otg":       "application/vnd.oasis.opendocument.graphics-template",
    ".oth":       "application/vnd.oasis.opendocument.text-web",
    ".oti":       "application/vnd.oasis.opendocument.image-template",
    ".otm":       "application/vnd.oasis.opendocument.text-master",
    ".otp":       "application/vnd.oasis.opendocument.presentation-template",
    ".ots":       "application/vnd.oasis.opendocument.spreadsheet-template",
    ".ott":       "application/vnd.oasis.opendocument.text-template",
    ".p10":       "application/pkcs10",
    ".p12":       "application/pkcs-12",
    ".p7a":       "application/x-pkcs7-signature",
    ".p7c":       "application/pkcs7-mime",
    ".p7m":       "application/pkcs7-mime",
    ".p7r":       "application/x-pkcs7-certreqresp",
    ".p7s":       "application/pkcs7-signature",
    ".p":         "text/x-pascal",
    ".part":      "application/pro_eng",
    ".pas":       "text/pascal",
    ".pbm":       "image/x-portable-bitmap",
    ".pcl":       "application/vndhp-pcl",
    ".pct":       "image/x-pict",
    ".pcx":       "image/x-pcx",
    ".pdb":       "chemical/x-pdb",
    ".pdf":       "application/pdf",
    ".pfunk":     "audio/make",
    ".pgm":       "image/x-portable-graymap",
    ".pic":       "image/pict",
    ".pict":      "image/pict",
    ".pkg":       "application/x-newton-compatible-pkg",
    ".pko":       "application/vndms-pkipko",
    ".pl":        "text/x-scriptperl",
    ".plx":       "application/x-pixclscript",
    ".pm4":       "application/x-pagemaker",
    ".pm5":       "application/x-pagemaker",
    ".pm":        "text/x-scriptperl-module",
    ".png":       "image/png",
    ".pnm":       "application/x-portable-anymap",
    ".pot":       "application/mspowerpoint",
    ".pov":       "model/x-pov",
    ".ppa":       "application/vndms-powerpoint",
    ".ppm":       "image/x-portable-pixmap",
    ".pps":       "application/mspowerpoint",
    ".ppt":       "application/mspowerpoint",
    ".ppz":       "application/mspowerpoint",
    ".pre":       "application/x-freelance",
    ".prt":       "application/pro_eng",
    ".ps":        "application/postscript",
    ".psd":       "application/octet-stream",
    ".pvu":       "paleovu/x-pv",
    ".pwz":       "application/vndms-powerpoint",
    ".py":        "text/x-scriptphyton",
    ".pyc":       "application/x-bytecodepython",
    ".qcp":       "audio/vndqcelp",
    ".qd3":       "x-world/x-3dmf",
    ".qd3d":      "x-world/x-3dmf",
    ".qif":       "image/x-quicktime",
    ".qt":        "video/quicktime",
    ".qtc":       "video/x-qtc",
    ".qti":       "image/x-quicktime",
    ".qtif":      "image/x-quicktime",
    ".ra":        "audio/x-pn-realaudio",
    ".ram":       "audio/x-pn-realaudio",
    ".rar":       "application/x-rar-compressed",
    ".ras":       "application/x-cmu-raster",
    ".rast":      "image/cmu-raster",
    ".rexx":      "text/x-scriptrexx",
    ".rf":        "image/vndrn-realflash",
    ".rgb":       "image/x-rgb",
    ".rm":        "application/vndrn-realmedia",
    ".rmi":       "audio/mid",
    ".rmm":       "audio/x-pn-realaudio",
    ".rmp":       "audio/x-pn-realaudio",
    ".rng":       "application/ringing-tones",
    ".rnx":       "application/vndrn-realplayer",
    ".roff":      "application/x-troff",
    ".rp":        "image/vndrn-realpix",
    ".rpm":       "audio/x-pn-realaudio-plugin",
    ".rt":        "text/vndrn-realtext",
    ".rtf":       "text/richtext",
    ".rtx":       "text/richtext",
    ".rv":        "video/vndrn-realvideo",
    ".s":         "text/x-asm",
    ".s3m":       "audio/s3m",
    ".s7z":       "application/x-7z-compressed",
    ".saveme":    "application/octet-stream",
    ".sbk":       "application/x-tbook",
    ".scm":       "text/x-scriptscheme",
    ".sdml":      "text/plain",
    ".sdp":       "application/sdp",
    ".sdr":       "application/sounder",
    ".sea":       "application/sea",
    ".set":       "application/set",
    ".sgm":       "text/x-sgml",
    ".sgml":      "text/x-sgml",
    ".sh":        "text/x-scriptsh",
    ".shar":      "application/x-bsh",
    ".shtml":     "text/x-server-parsed-html",
    ".sid":       "audio/x-psid",
    ".skd":       "application/x-koan",
    ".skm":       "application/x-koan",
    ".skp":       "application/x-koan",
    ".skt":       "application/x-koan",
    ".sit":       "application/x-stuffit",
    ".sitx":      "application/x-stuffitx",
    ".sl":        "application/x-seelogo",
    ".smi":       "application/smil",
    ".smil":      "application/smil",
    ".snd":       "audio/basic",
    ".sol":       "application/solids",
    ".spc":       "text/x-speech",
    ".spl":       "application/futuresplash",
    ".spr":       "application/x-sprite",
    ".sprite":    "application/x-sprite",
    ".spx":       "audio/ogg",
    ".src":       "application/x-wais-source",
    ".ssi":       "text/x-server-parsed-html",
    ".ssm":       "application/streamingmedia",
    ".sst":       "application/vndms-pkicertstore",
    ".step":      "application/step",
    ".stl":       "application/sla",
    ".stp":       "application/step",
    ".sv4cpio":   "application/x-sv4cpio",
    ".sv4crc":    "application/x-sv4crc",
    ".svf":       "image/vnddwg",
    ".svg":       "image/svg+xml",
    ".svr":       "application/x-world",
    ".swf":       "application/x-shockwave-flash",
    ".t":         "application/x-troff",
    ".talk":      "text/x-speech",
    ".tar":       "application/x-tar",
    ".tbk":       "application/toolbook",
    ".tcl":       "text/x-scripttcl",
    ".tcsh":      "text/x-scripttcsh",
    ".tex":       "application/x-tex",
    ".texi":      "application/x-texinfo",
    ".texinfo":   "application/x-texinfo",
    ".text":      "text/plain",
    ".tgz":       "application/gnutar",
    ".tif":       "image/tiff",
    ".tiff":      "image/tiff",
    ".tr":        "application/x-troff",
    ".tsi":       "audio/tsp-audio",
    ".tsp":       "application/dsptype",
    ".tsv":       "text/tab-separated-values",
    ".turbot":    "image/florian",
    ".txt":       "text/plain",
    ".uil":       "text/x-uil",
    ".uni":       "text/uri-list",
    ".unis":      "text/uri-list",
    ".unv":       "application/i-deas",
    ".uri":       "text/uri-list",
    ".uris":      "text/uri-list",
    ".ustar":     "application/x-ustar",
    ".uu":        "text/x-uuencode",
    ".uue":       "text/x-uuencode",
    ".vcd":       "application/x-cdlink",
    ".vcf":       "text/x-vcard",
    ".vcard":     "text/x-vcard",
    ".vcs":       "text/x-vcalendar",
    ".vda":       "application/vda",
    ".vdo":       "video/vdo",
    ".vew":       "application/groupwise",
    ".viv":       "video/vivo",
    ".vivo":      "video/vivo",
    ".vmd":       "application/vocaltec-media-desc",
    ".vmf":       "application/vocaltec-media-file",
    ".voc":       "audio/voc",
    ".vos":       "video/vosaic",
    ".vox":       "audio/voxware",
    ".vqe":       "audio/x-twinvq-plugin",
    ".vqf":       "audio/x-twinvq",
    ".vql":       "audio/x-twinvq-plugin",
    ".vrml":      "application/x-vrml",
    ".vrt":       "x-world/x-vrt",
    ".vsd":       "application/x-visio",
    ".vst":       "application/x-visio",
    ".vsw":       "application/x-visio",
    ".w60":       "application/wordperfect60",
    ".w61":       "application/wordperfect61",
    ".w6w":       "application/msword",
    ".wav":       "audio/wav",
    ".wb1":       "application/x-qpro",
    ".wbmp":      "image/vnd.wap.wbmp",
    ".web":       "application/vndxara",
    ".wiz":       "application/msword",
    ".wk1":       "application/x-123",
    ".wmf":       "windows/metafile",
    ".wml":       "text/vnd.wap.wml",
    ".wmlc":      "application/vnd.wap.wmlc",
    ".wmls":      "text/vnd.wap.wmlscript",
    ".wmlsc":     "application/vnd.wap.wmlscriptc",
    ".word":      "application/msword",
    ".wp5":       "application/wordperfect",
    ".wp6":       "application/wordperfect",
    ".wp":        "application/wordperfect",
    ".wpd":       "application/wordperfect",
    ".wq1":       "application/x-lotus",
    ".wri":       "application/mswrite",
    ".wrl":       "application/x-world",
    ".wrz":       "model/vrml",
    ".wsc":       "text/scriplet",
    ".wsrc":      "application/x-wais-source",
    ".wtk":       "application/x-wintalk",
    ".x-png":     "image/png",
    ".xbm":       "image/x-xbitmap",
    ".xdr":       "video/x-amt-demorun",
    ".xgz":       "xgl/drawing",
    ".xif":       "image/vndxiff",
    ".xl":        "application/excel",
    ".xla":       "application/excel",
    ".xlb":       "application/excel",
    ".xlc":       "application/excel",
    ".xld":       "application/excel",
    ".xlk":       "application/excel",
    ".xll":       "application/excel",
    ".xlm":       "application/excel",
    ".xls":       "application/excel",
    ".xlt":       "application/excel",
    ".xlv":       "application/excel",
    ".xlw":       "application/excel",
    ".xm":        "audio/xm",
    ".xml":       "text/xml",
    ".xmz":       "xgl/movie",
    ".xpix":      "application/x-vndls-xpix",
    ".xpm":       "image/x-xpixmap",
    ".xsr":       "video/x-amt-showrun",
    ".xwd":       "image/x-xwd",
    ".xyz":       "chemical/x-pdb",
    ".z":         "application/x-compress",
    ".zip":       "application/zip",
    ".zoo":       "application/octet-stream",
    ".zsh":       "text/x-scriptzsh",
    ".docx":      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    ".docm":      "application/vnd.ms-word.document.macroEnabled.12",
    ".dotx":      "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
    ".dotm":      "application/vnd.ms-word.template.macroEnabled.12",
    ".xlsx":      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    ".xlsm":      "application/vnd.ms-excel.sheet.macroEnabled.12",
    ".xltx":      "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
    ".xltm":      "application/vnd.ms-excel.template.macroEnabled.12",
    ".xlsb":      "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
    ".xlam":      "application/vnd.ms-excel.addin.macroEnabled.12",
    ".pptx":      "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    ".pptm":      "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
    ".ppsx":      "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
    ".ppsm":      "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
    ".potx":      "application/vnd.openxmlformats-officedocument.presentationml.template",
    ".potm":      "application/vnd.ms-powerpoint.template.macroEnabled.12",
    ".ppam":      "application/vnd.ms-powerpoint.addin.macroEnabled.12",
    ".sldx":      "application/vnd.openxmlformats-officedocument.presentationml.slide",
    ".sldm":      "application/vnd.ms-powerpoint.slide.macroEnabled.12",
    ".thmx":      "application/vnd.ms-officetheme",
    ".onetoc":    "application/onenote",
    ".onetoc2":   "application/onenote",
    ".onetmp":    "application/onenote",
    ".onepkg":    "application/onenote",
    ".xpi":       "application/x-xpinstall",
}

func init() {
    for ext, typ := range types {
        // skip errors
        mime.AddExtensionType(ext, typ)
    }
}

// typeByExtension returns the MIME type associated with the file extension ext.
// The extension ext should begin with a leading dot, as in ".html".
// When ext has no associated type, typeByExtension returns "".
//
// Extensions are looked up first case-sensitively, then case-insensitively.
//
// The built-in table is small but on unix it is augmented by the local
// system's mime.types file(s) if available under one or more of these
// names:
//
//   /etc/mime.types
//   /etc/apache2/mime.types
//   /etc/apache/mime.types
//
// On Windows, MIME types are extracted from the registry.
//
// Text types have the charset parameter set to "utf-8" by default.
func TypeByExtension(fullfilename string) string {
    ext := filepath.Ext(fullfilename)
    typ := mime.TypeByExtension(ext)

    // mime.TypeByExtension returns as text/plain; | charset=utf-8 the static .js (not always)
    if ext == ".js" && (typ == "text/plain" || typ == "text/plain; charset=utf-8") {

        if ext == ".js" {
            typ = "application/javascript"
        }
    }
    return typ
}

Hope that helped you and other users, don't hesitate to post again if you have more questions!

Inheritance and init method in Python

When you override the init you have also to call the init of the parent class

super(Num2, self).__init__(num)

Understanding Python super() with __init__() methods

How to fix "Attempted relative import in non-package" even with __init__.py

Old thread. I found out that adding an __all__= ['submodule', ...] to the __init__.py file and then using the from <CURRENT_MODULE> import * in the target works fine.

why should I make a copy of a data frame in pandas

This expands on Paul's answer. In Pandas, indexing a DataFrame returns a reference to the initial DataFrame. Thus, changing the subset will change the initial DataFrame. Thus, you'd want to use the copy if you want to make sure the initial DataFrame shouldn't change. Consider the following code:

df = DataFrame({'x': [1,2]})
df_sub = df[0:1]
df_sub.x = -1
print(df)

You'll get:

x
0 -1
1  2

In contrast, the following leaves df unchanged:

df_sub_copy = df[0:1].copy()
df_sub_copy.x = -1

How can I use Html.Action?

You should look at the documentation for the Action method; it's explained well. For your case, this should work:

@Html.Action("GetOptions", new { pk="00", rk="00" });

The controllerName parameter will default to the controller from which Html.Action is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:

@Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });

Pandas aggregate count distinct

Just adding to the answers already given, the solution using the string "nunique" seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M

%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s

%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s

%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s

Java Refuses to Start - Could not reserve enough space for object heap

Running a 32-bit OS is a mistake; you should definitely upgrade at the earliest convenience.

I don't know whether Java requires its heap to be in a single contiguous chunk, but if it does, asking for 1.8G of heap on a 32-bit box sounds like a tall order. You're assuming that there is a chunk of address space, almost half of it, free at JVM startup time.

Depending on what other libraries are loaded at the time, there may not be. Libraries can allocate memory anywhere they like, so it could fragment your address space sufficiently that 1.8G is not available in one chunk.

There is only about 3G address space max available on Linux 32-bit anyway. Libraries and the JVM itself uses some to start with.

Find the number of employees in each department - SQL Oracle

Please try:

select count(*) as count,dept.DNAME 
from emp 
inner join dept on emp.DEPTNO = dept.DEPTNO 
group by dept.DNAME

List of Timezone IDs for use with FindTimeZoneById() in C#?

And if you'd like a HTML select with the Windows time zones in:

<select>
<option value="Morocco Standard Time">(GMT) Casablanca</option>
<option value="GMT Standard Time">(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London</option>
<option value="Greenwich Standard Time">(GMT) Monrovia, Reykjavik</option>
<option value="W. Europe Standard Time">(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna</option>
<option value="Central Europe Standard Time">(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague</option>
<option value="Romance Standard Time">(GMT+01:00) Brussels, Copenhagen, Madrid, Paris</option>
<option value="Central European Standard Time">(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb</option>
<option value="W. Central Africa Standard Time">(GMT+01:00) West Central Africa</option>
<option value="Jordan Standard Time">(GMT+02:00) Amman</option>
<option value="GTB Standard Time">(GMT+02:00) Athens, Bucharest, Istanbul</option>
<option value="Middle East Standard Time">(GMT+02:00) Beirut</option>
<option value="Egypt Standard Time">(GMT+02:00) Cairo</option>
<option value="South Africa Standard Time">(GMT+02:00) Harare, Pretoria</option>
<option value="FLE Standard Time">(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius</option>
<option value="Israel Standard Time">(GMT+02:00) Jerusalem</option>
<option value="E. Europe Standard Time">(GMT+02:00) Minsk</option>
<option value="Namibia Standard Time">(GMT+02:00) Windhoek</option>
<option value="Arabic Standard Time">(GMT+03:00) Baghdad</option>
<option value="Arab Standard Time">(GMT+03:00) Kuwait, Riyadh</option>
<option value="Russian Standard Time">(GMT+03:00) Moscow, St. Petersburg, Volgograd</option>
<option value="E. Africa Standard Time">(GMT+03:00) Nairobi</option>
<option value="Georgian Standard Time">(GMT+03:00) Tbilisi</option>
<option value="Iran Standard Time">(GMT+03:30) Tehran</option>
<option value="Arabian Standard Time">(GMT+04:00) Abu Dhabi, Muscat</option>
<option value="Azerbaijan Standard Time">(GMT+04:00) Baku</option>
<option value="Mauritius Standard Time">(GMT+04:00) Port Louis</option>
<option value="Caucasus Standard Time">(GMT+04:00) Yerevan</option>
<option value="Afghanistan Standard Time">(GMT+04:30) Kabul</option>
<option value="Ekaterinburg Standard Time">(GMT+05:00) Ekaterinburg</option>
<option value="Pakistan Standard Time">(GMT+05:00) Islamabad, Karachi</option>
<option value="West Asia Standard Time">(GMT+05:00) Tashkent</option>
<option value="India Standard Time">(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi</option>
<option value="Sri Lanka Standard Time">(GMT+05:30) Sri Jayawardenepura</option>
<option value="Nepal Standard Time">(GMT+05:45) Kathmandu</option>
<option value="N. Central Asia Standard Time">(GMT+06:00) Almaty, Novosibirsk</option>
<option value="Central Asia Standard Time">(GMT+06:00) Astana, Dhaka</option>
<option value="Myanmar Standard Time">(GMT+06:30) Yangon (Rangoon)</option>
<option value="SE Asia Standard Time">(GMT+07:00) Bangkok, Hanoi, Jakarta</option>
<option value="North Asia Standard Time">(GMT+07:00) Krasnoyarsk</option>
<option value="China Standard Time">(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi</option>
<option value="North Asia East Standard Time">(GMT+08:00) Irkutsk, Ulaan Bataar</option>
<option value="Singapore Standard Time">(GMT+08:00) Kuala Lumpur, Singapore</option>
<option value="W. Australia Standard Time">(GMT+08:00) Perth</option>
<option value="Taipei Standard Time">(GMT+08:00) Taipei</option>
<option value="Tokyo Standard Time">(GMT+09:00) Osaka, Sapporo, Tokyo</option>
<option value="Korea Standard Time">(GMT+09:00) Seoul</option>
<option value="Yakutsk Standard Time">(GMT+09:00) Yakutsk</option>
<option value="Cen. Australia Standard Time">(GMT+09:30) Adelaide</option>
<option value="AUS Central Standard Time">(GMT+09:30) Darwin</option>
<option value="E. Australia Standard Time">(GMT+10:00) Brisbane</option>
<option value="AUS Eastern Standard Time">(GMT+10:00) Canberra, Melbourne, Sydney</option>
<option value="West Pacific Standard Time">(GMT+10:00) Guam, Port Moresby</option>
<option value="Tasmania Standard Time">(GMT+10:00) Hobart</option>
<option value="Vladivostok Standard Time">(GMT+10:00) Vladivostok</option>
<option value="Central Pacific Standard Time">(GMT+11:00) Magadan, Solomon Is., New Caledonia</option>
<option value="New Zealand Standard Time">(GMT+12:00) Auckland, Wellington</option>
<option value="Fiji Standard Time">(GMT+12:00) Fiji, Kamchatka, Marshall Is.</option>
<option value="Tonga Standard Time">(GMT+13:00) Nuku'alofa</option>
<option value="Azores Standard Time">(GMT-01:00) Azores</option>
<option value="Cape Verde Standard Time">(GMT-01:00) Cape Verde Is.</option>
<option value="Mid-Atlantic Standard Time">(GMT-02:00) Mid-Atlantic</option>
<option value="E. South America Standard Time">(GMT-03:00) Brasilia</option>
<option value="Argentina Standard Time">(GMT-03:00) Buenos Aires</option>
<option value="SA Eastern Standard Time">(GMT-03:00) Georgetown</option>
<option value="Greenland Standard Time">(GMT-03:00) Greenland</option>
<option value="Montevideo Standard Time">(GMT-03:00) Montevideo</option>
<option value="Newfoundland Standard Time">(GMT-03:30) Newfoundland</option>
<option value="Atlantic Standard Time">(GMT-04:00) Atlantic Time (Canada)</option>
<option value="SA Western Standard Time">(GMT-04:00) La Paz</option>
<option value="Central Brazilian Standard Time">(GMT-04:00) Manaus</option>
<option value="Pacific SA Standard Time">(GMT-04:00) Santiago</option>
<option value="Venezuela Standard Time">(GMT-04:30) Caracas</option>
<option value="SA Pacific Standard Time">(GMT-05:00) Bogota, Lima, Quito, Rio Branco</option>
<option value="Eastern Standard Time">(GMT-05:00) Eastern Time (US & Canada)</option>
<option value="US Eastern Standard Time">(GMT-05:00) Indiana (East)</option>
<option value="Central America Standard Time">(GMT-06:00) Central America</option>
<option value="Central Standard Time">(GMT-06:00) Central Time (US & Canada)</option>
<option value="Central Standard Time (Mexico)">(GMT-06:00) Guadalajara, Mexico City, Monterrey</option>
<option value="Canada Central Standard Time">(GMT-06:00) Saskatchewan</option>
<option value="US Mountain Standard Time">(GMT-07:00) Arizona</option>
<option value="Mountain Standard Time (Mexico)">(GMT-07:00) Chihuahua, La Paz, Mazatlan</option>
<option value="Mountain Standard Time">(GMT-07:00) Mountain Time (US & Canada)</option>
<option value="Pacific Standard Time">(GMT-08:00) Pacific Time (US & Canada)</option>
<option value="Pacific Standard Time (Mexico)">(GMT-08:00) Tijuana, Baja California</option>
<option value="Alaskan Standard Time">(GMT-09:00) Alaska</option>
<option value="Hawaiian Standard Time">(GMT-10:00) Hawaii</option>
<option value="Samoa Standard Time">(GMT-11:00) Midway Island, Samoa</option>
<option value="Dateline Standard Time">(GMT-12:00) International Date Line West</option>
</select>

And if you'd like to use it in C#.NET MVC in a Razor view:

var timezones = new List<SelectListItem> { 
new SelectListItem() { Value="", Text="Select timezone...", Selected = false },
new SelectListItem() { Value="Morocco Standard Time", Text="(GMT) Casablanca", Selected = false },
new SelectListItem() { Value="GMT Standard Time", Text="(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London", Selected = false },
new SelectListItem() { Value="Greenwich Standard Time", Text="(GMT) Monrovia, Reykjavik", Selected = false },
new SelectListItem() { Value="W. Europe Standard Time", Text="(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna", Selected = false },
new SelectListItem() { Value="Central Europe Standard Time", Text="(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague", Selected = false },
new SelectListItem() { Value="Romance Standard Time", Text="(GMT+01:00) Brussels, Copenhagen, Madrid, Paris", Selected = false },
new SelectListItem() { Value="Central European Standard Time", Text="(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb", Selected = false },
new SelectListItem() { Value="W. Central Africa Standard Time", Text="(GMT+01:00) West Central Africa", Selected = false },
new SelectListItem() { Value="Jordan Standard Time", Text="(GMT+02:00) Amman", Selected = false },
new SelectListItem() { Value="GTB Standard Time", Text="(GMT+02:00) Athens, Bucharest, Istanbul", Selected = false },
new SelectListItem() { Value="Middle East Standard Time", Text="(GMT+02:00) Beirut", Selected = false },
new SelectListItem() { Value="Egypt Standard Time", Text="(GMT+02:00) Cairo", Selected = false },
new SelectListItem() { Value="South Africa Standard Time", Text="(GMT+02:00) Harare, Pretoria", Selected = false },
new SelectListItem() { Value="FLE Standard Time", Text="(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius", Selected = false },
new SelectListItem() { Value="Israel Standard Time", Text="(GMT+02:00) Jerusalem", Selected = false },
new SelectListItem() { Value="E. Europe Standard Time", Text="(GMT+02:00) Minsk", Selected = false },
new SelectListItem() { Value="Namibia Standard Time", Text="(GMT+02:00) Windhoek", Selected = false },
new SelectListItem() { Value="Arabic Standard Time", Text="(GMT+03:00) Baghdad", Selected = false },
new SelectListItem() { Value="Arab Standard Time", Text="(GMT+03:00) Kuwait, Riyadh", Selected = false },
new SelectListItem() { Value="Russian Standard Time", Text="(GMT+03:00) Moscow, St. Petersburg, Volgograd", Selected = false },
new SelectListItem() { Value="E. Africa Standard Time", Text="(GMT+03:00) Nairobi", Selected = false },
new SelectListItem() { Value="Georgian Standard Time", Text="(GMT+03:00) Tbilisi", Selected = false },
new SelectListItem() { Value="Iran Standard Time", Text="(GMT+03:30) Tehran", Selected = false },
new SelectListItem() { Value="Arabian Standard Time", Text="(GMT+04:00) Abu Dhabi, Muscat", Selected = false },
new SelectListItem() { Value="Azerbaijan Standard Time", Text="(GMT+04:00) Baku", Selected = false },
new SelectListItem() { Value="Mauritius Standard Time", Text="(GMT+04:00) Port Louis", Selected = false },
new SelectListItem() { Value="Caucasus Standard Time", Text="(GMT+04:00) Yerevan", Selected = false },
new SelectListItem() { Value="Afghanistan Standard Time", Text="(GMT+04:30) Kabul", Selected = false },
new SelectListItem() { Value="Ekaterinburg Standard Time", Text="(GMT+05:00) Ekaterinburg", Selected = false },
new SelectListItem() { Value="Pakistan Standard Time", Text="(GMT+05:00) Islamabad, Karachi", Selected = false },
new SelectListItem() { Value="West Asia Standard Time", Text="(GMT+05:00) Tashkent", Selected = false },
new SelectListItem() { Value="India Standard Time", Text="(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi", Selected = false },
new SelectListItem() { Value="Sri Lanka Standard Time", Text="(GMT+05:30) Sri Jayawardenepura", Selected = false },
new SelectListItem() { Value="Nepal Standard Time", Text="(GMT+05:45) Kathmandu", Selected = false },
new SelectListItem() { Value="N. Central Asia Standard Time", Text="(GMT+06:00) Almaty, Novosibirsk", Selected = false },
new SelectListItem() { Value="Central Asia Standard Time", Text="(GMT+06:00) Astana, Dhaka", Selected = false },
new SelectListItem() { Value="Myanmar Standard Time", Text="(GMT+06:30) Yangon (Rangoon)", Selected = false },
new SelectListItem() { Value="SE Asia Standard Time", Text="(GMT+07:00) Bangkok, Hanoi, Jakarta", Selected = false },
new SelectListItem() { Value="North Asia Standard Time", Text="(GMT+07:00) Krasnoyarsk", Selected = false },
new SelectListItem() { Value="China Standard Time", Text="(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi", Selected = false },
new SelectListItem() { Value="North Asia East Standard Time", Text="(GMT+08:00) Irkutsk, Ulaan Bataar", Selected = false },
new SelectListItem() { Value="Singapore Standard Time", Text="(GMT+08:00) Kuala Lumpur, Singapore", Selected = false },
new SelectListItem() { Value="W. Australia Standard Time", Text="(GMT+08:00) Perth", Selected = false },
new SelectListItem() { Value="Taipei Standard Time", Text="(GMT+08:00) Taipei", Selected = false },
new SelectListItem() { Value="Tokyo Standard Time", Text="(GMT+09:00) Osaka, Sapporo, Tokyo", Selected = false },
new SelectListItem() { Value="Korea Standard Time", Text="(GMT+09:00) Seoul", Selected = false },
new SelectListItem() { Value="Yakutsk Standard Time", Text="(GMT+09:00) Yakutsk", Selected = false },
new SelectListItem() { Value="Cen. Australia Standard Time", Text="(GMT+09:30) Adelaide", Selected = false },
new SelectListItem() { Value="AUS Central Standard Time", Text="(GMT+09:30) Darwin", Selected = false },
new SelectListItem() { Value="E. Australia Standard Time", Text="(GMT+10:00) Brisbane", Selected = false },
new SelectListItem() { Value="AUS Eastern Standard Time", Text="(GMT+10:00) Canberra, Melbourne, Sydney", Selected = false },
new SelectListItem() { Value="West Pacific Standard Time", Text="(GMT+10:00) Guam, Port Moresby", Selected = false },
new SelectListItem() { Value="Tasmania Standard Time", Text="(GMT+10:00) Hobart", Selected = false },
new SelectListItem() { Value="Vladivostok Standard Time", Text="(GMT+10:00) Vladivostok", Selected = false },
new SelectListItem() { Value="Central Pacific Standard Time", Text="(GMT+11:00) Magadan, Solomon Is., New Caledonia", Selected = false },
new SelectListItem() { Value="New Zealand Standard Time", Text="(GMT+12:00) Auckland, Wellington", Selected = false },
new SelectListItem() { Value="Fiji Standard Time", Text="(GMT+12:00) Fiji, Kamchatka, Marshall Is.", Selected = false },
new SelectListItem() { Value="Tonga Standard Time", Text="(GMT+13:00) Nuku'alofa", Selected = false },
new SelectListItem() { Value="Azores Standard Time", Text="(GMT-01:00) Azores", Selected = false },
new SelectListItem() { Value="Cape Verde Standard Time", Text="(GMT-01:00) Cape Verde Is.", Selected = false },
new SelectListItem() { Value="Mid-Atlantic Standard Time", Text="(GMT-02:00) Mid-Atlantic", Selected = false },
new SelectListItem() { Value="E. South America Standard Time", Text="(GMT-03:00) Brasilia", Selected = false },
new SelectListItem() { Value="Argentina Standard Time", Text="(GMT-03:00) Buenos Aires", Selected = false },
new SelectListItem() { Value="SA Eastern Standard Time", Text="(GMT-03:00) Georgetown", Selected = false },
new SelectListItem() { Value="Greenland Standard Time", Text="(GMT-03:00) Greenland", Selected = false },
new SelectListItem() { Value="Montevideo Standard Time", Text="(GMT-03:00) Montevideo", Selected = false },
new SelectListItem() { Value="Newfoundland Standard Time", Text="(GMT-03:30) Newfoundland", Selected = false },
new SelectListItem() { Value="Atlantic Standard Time", Text="(GMT-04:00) Atlantic Time (Canada)", Selected = false },
new SelectListItem() { Value="SA Western Standard Time", Text="(GMT-04:00) La Paz", Selected = false },
new SelectListItem() { Value="Central Brazilian Standard Time", Text="(GMT-04:00) Manaus", Selected = false },
new SelectListItem() { Value="Pacific SA Standard Time", Text="(GMT-04:00) Santiago", Selected = false },
new SelectListItem() { Value="Venezuela Standard Time", Text="(GMT-04:30) Caracas", Selected = false },
new SelectListItem() { Value="SA Pacific Standard Time", Text="(GMT-05:00) Bogota, Lima, Quito, Rio Branco", Selected = false },
new SelectListItem() { Value="Eastern Standard Time", Text="(GMT-05:00) Eastern Time (US & Canada)", Selected = false },
new SelectListItem() { Value="US Eastern Standard Time", Text="(GMT-05:00) Indiana (East)", Selected = false },
new SelectListItem() { Value="Central America Standard Time", Text="(GMT-06:00) Central America", Selected = false },
new SelectListItem() { Value="Central Standard Time", Text="(GMT-06:00) Central Time (US & Canada)", Selected = false },
new SelectListItem() { Value="Central Standard Time (Mexico)", Text="(GMT-06:00) Guadalajara, Mexico City, Monterrey", Selected = false },
new SelectListItem() { Value="Canada Central Standard Time", Text="(GMT-06:00) Saskatchewan", Selected = false },
new SelectListItem() { Value="US Mountain Standard Time", Text="(GMT-07:00) Arizona", Selected = false },
new SelectListItem() { Value="Mountain Standard Time (Mexico)", Text="(GMT-07:00) Chihuahua, La Paz, Mazatlan", Selected = false },
new SelectListItem() { Value="Mountain Standard Time", Text="(GMT-07:00) Mountain Time (US & Canada)", Selected = false },
new SelectListItem() { Value="Pacific Standard Time", Text="(GMT-08:00) Pacific Time (US & Canada)", Selected = false },
new SelectListItem() { Value="Pacific Standard Time (Mexico)", Text="(GMT-08:00) Tijuana, Baja California", Selected = false },
new SelectListItem() { Value="Alaskan Standard Time", Text="(GMT-09:00) Alaska", Selected = false },
new SelectListItem() { Value="Hawaiian Standard Time", Text="(GMT-10:00) Hawaii", Selected = false },
new SelectListItem() { Value="Samoa Standard Time", Text="(GMT-11:00) Midway Island, Samoa", Selected = false },
new SelectListItem() { Value="Dateline Standard Time", Text="(GMT-12:00) International Date Line West", Selected = false }
}

Although for Razor you can of course just generate the options by looping through TimeZoneInfo.GetSystemTimeZones()

Call an overridden method from super class in typescript

The key is calling the parent's method using super.methodName();

class A {
    // A protected method
    protected doStuff()
    {
        alert("Called from A");
    }

    // Expose the protected method as a public function
    public callDoStuff()
    {
        this.doStuff();
    }
}

class B extends A {

    // Override the protected method
    protected doStuff()
    {
        // If we want we can still explicitly call the initial method
        super.doStuff();
        alert("Called from B");
    }
}

var a = new A();
a.callDoStuff(); // Will only alert "Called from A"

var b = new B()
b.callDoStuff(); // Will alert "Called from A" then "Called from B"

Try it here

C# - using List<T>.Find() with custom objects

It's easy, just use list.Find(x => x.name == "stringNameOfObjectToFind");

HTML / CSS table with GRIDLINES

<table border="1"></table>

should do the trick.

Real escape string and PDO

Use prepared statements. Those keep the data and syntax apart, which removes the need for escaping MySQL data. See e.g. this tutorial.

Selecting pandas column by location

You could use label based using .loc or index based using .iloc method to do column-slicing including column ranges:

In [50]: import pandas as pd

In [51]: import numpy as np

In [52]: df = pd.DataFrame(np.random.rand(4,4), columns = list('abcd'))

In [53]: df
Out[53]: 
          a         b         c         d
0  0.806811  0.187630  0.978159  0.317261
1  0.738792  0.862661  0.580592  0.010177
2  0.224633  0.342579  0.214512  0.375147
3  0.875262  0.151867  0.071244  0.893735

In [54]: df.loc[:, ["a", "b", "d"]] ### Selective columns based slicing
Out[54]: 
          a         b         d
0  0.806811  0.187630  0.317261
1  0.738792  0.862661  0.010177
2  0.224633  0.342579  0.375147
3  0.875262  0.151867  0.893735

In [55]: df.loc[:, "a":"c"] ### Selective label based column ranges slicing
Out[55]: 
          a         b         c
0  0.806811  0.187630  0.978159
1  0.738792  0.862661  0.580592
2  0.224633  0.342579  0.214512
3  0.875262  0.151867  0.071244

In [56]: df.iloc[:, 0:3] ### Selective index based column ranges slicing
Out[56]: 
          a         b         c
0  0.806811  0.187630  0.978159
1  0.738792  0.862661  0.580592
2  0.224633  0.342579  0.214512
3  0.875262  0.151867  0.071244

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

how to completely clear localstorage

localStorage.clear();

how to completely clear sessionstorage

sessionStorage.clear();

[...] Cookies ?

var cookies = document.cookie;

for (var i = 0; i < cookies.split(";").length; ++i)
{
    var myCookie = cookies[i];
    var pos = myCookie.indexOf("=");
    var name = pos > -1 ? myCookie.substr(0, pos) : myCookie;
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}

is there any way to get the value back after clear these ?

No, there isn't. But you shouldn't rely on this if this is related to a security question.

How Do I Make Glyphicons Bigger? (Change Size?)

try to use heading, no need extra css

<h1 class="glyphicon glyphicon-plus"></h1>

How can I disable an <option> in a <select> based on its value in JavaScript?

Set an id to the option then use get element by id and disable it when x value has been selected..

example

<body>
      <select class="pull-right text-muted small" 
                 name="driveCapacity" id=driveCapacity onchange="checkRPM()">
      <option value="4000.0" id="4000">4TB</option>
      <option value="900.0" id="900">900GB</option>
      <option value="300.0" id ="300">300GB</option>
    </select>
    </body>
<script>
var perfType = document.getElementById("driveRPM").value;
if(perfType == "7200"){         
        document.getElementById("driveCapacity").value = "4000.0";
        document.getElementById("4000").disabled = false;           
    }else{          
        document.getElementById("4000").disabled = true;            
    }    
</script>

CSS Box Shadow Bottom Only

You can use two elements, one inside the other, and give the outer one overflow: hidden and a width equal to the inner element together with a bottom padding so that the shadow on all the other sides are "cut off"

#outer {
    width: 100px;
    overflow: hidden;
    padding-bottom: 10px;
}

#outer > div {
    width: 100px;
    height: 100px;
    background: orange;

    -moz-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
    -webkit-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
    box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
}

Alternatively, float the outer element to cause it to shrink to the size of the inner element. See: http://jsfiddle.net/QJPd5/1/

Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10)

right click on the installation file then navigate to the detail tab, you see the original file name there, rename the installation file to the value of the original file name, then start installation again.

What are the git concepts of HEAD, master, origin?

While this doesn't directly answer the question, there is great book available for free which will help you learn the basics called ProGit. If you would prefer the dead-wood version to a collection of bits you can purchase it from Amazon.

What is the best method of handling currency/money?

I am using it on this way:

number_to_currency(amount, unit: '€', precision: 2, format: "%u %n")

Of course that the currency symbol, precision, format and so on depends on each currency.

Python 3.6 install win32api?

Information provided by @Gord

As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

pip install pywin32

If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

pip install pywin32==xxx

This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.


Probably now undesirable solutions but certainly still valid as of September 2019

There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/

The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


EDIT

Since I posted my answer there are other alternatives to downloading the win32api module.

It is now available to download through pip using this command;

pip install pypiwin32

Also it can be installed from this GitHub repository as provided in comments by @Heath

Docker Compose wait for container X before starting Y

Not recommended for serious deployments, but here is essentially a "wait x seconds" command.

With docker-compose version 3.4 a start_period instruction has been added to healthcheck. This means we can do the following:

docker-compose.yml:

version: "3.4"
services:
  # your server docker container
  zmq_server:
    build:
      context: ./server_router_router
      dockerfile: Dockerfile

  # container that has to wait
  zmq_client:
    build:
      context: ./client_dealer/
      dockerfile: Dockerfile
    depends_on:
      - zmq_server
    healthcheck:
      test: "sh status.sh"
      start_period: 5s

status.sh:

#!/bin/sh

exit 0

What happens here is that the healthcheck is invoked after 5 seconds. This calls the status.sh script, which always returns "No problem". We just made zmq_client container wait 5 seconds before starting!

Note: It's important that you have version: "3.4". If the .4 is not there, docker-compose complains.

Plot two histograms on single chart with matplotlib

Here you have a working example:

import random
import numpy
from matplotlib import pyplot

x = [random.gauss(3,1) for _ in range(400)]
y = [random.gauss(4,2) for _ in range(400)]

bins = numpy.linspace(-10, 10, 100)

pyplot.hist(x, bins, alpha=0.5, label='x')
pyplot.hist(y, bins, alpha=0.5, label='y')
pyplot.legend(loc='upper right')
pyplot.show()

enter image description here

Entity Framework and SQL Server View

Due to the above mentioned problems, I prefer table value functions.

If you have this:

CREATE VIEW [dbo].[MyView] AS SELECT A, B FROM dbo.Something

create this:

CREATE FUNCTION MyFunction() RETURNS TABLE AS RETURN (SELECT * FROM [dbo].[MyView])

Then you simply import the function rather than the view.

jQuery Ajax simple call

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    });
}

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
    .success(function(data){
               // treat the READUSERS data returned
   })
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");
  });

RegEx for Javascript to allow only alphanumeric

Question is old, but it's never too late to answer

$(document).ready(function() {
  //prevent paste
  var usern_paste = document.getElementById('yourid');
  usern_paste.onpaste = e => e.preventDefault();

  //prevent copy
  var usern_drop = document.getElementById('yourid');
  usern_drop.ondrop = e => e.preventDefault();
});

$('#yourid').keypress(function (e) {
  var regex = new RegExp("^[a-zA-Z0-9\s]");
  var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
  if (regex.test(str)) {
      return true;
  }
  e.preventDefault();
  return false;
});

Can't find the 'libpq-fe.h header when trying to install pg gem

A more general answer for any Debian-based distribution (which includes Ubuntu) is the following. First, install the apt-file package running as root:

apt-get install apt-file

This allows you to search for packages containing a file. Then, update its database using

apt-file update

(this can be run as normal user). Then, look for the missing header using:

apt-file search libpq-fe.h

On my machine, this gives:

libpq-dev: /usr/include/postgresql/libpq-fe.h
postgres-xc-server-dev: /usr/include/postgres-xc/server/gtm/libpq-fe.h

There you go !

PHP - Getting the index of a element from a array

an array does not contain index when elements are associative. An array in php can contain mixed values like this:

$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");   
print_r($var);

Gives you:

Array
(
    [0] => apple
    [1] => banana
    [foo] => grape
    [2] => carrot
    [bar] => donkey
)

What are you trying to achieve since you need the index value in an associative array?

Can I do Model->where('id', ARRAY) multiple where conditions?

You can use whereIn which accepts an array as second paramter.

DB:table('table')
   ->whereIn('column', [value, value, value])
   ->get()

You can chain where multiple times.

DB:table('table')->where('column', 'operator', 'value')
    ->where('column', 'operator', 'value')
    ->where('column', 'operator', 'value')
    ->get();

This will use AND operator. if you need OR you can use orWhere method.

For advanced where statements

DB::table('table')
    ->where('column', 'operator', 'value')
    ->orWhere(function($query)
    {
        $query->where('column', 'operator', 'value')
            ->where('column', 'operator', 'value');
    })
    ->get();

How do the major C# DI/IoC frameworks compare?

While a comprehensive answer to this question takes up hundreds of pages of my book, here's a quick comparison chart that I'm still working on:

A table explaining difference between several DICs

Format an Integer using Java String Format

Use %03d in the format specifier for the integer. The 0 means that the number will be zero-filled if it is less than three (in this case) digits.

See the Formatter docs for other modifiers.

How can I copy a Python string?

Copying a string can be done two ways either copy the location a = "a" b = a or you can clone which means b wont get affected when a is changed which is done by a = 'a' b = a[:]

Bash script to run php script

If you have PHP installed as a command line tool (try issuing php to the terminal and see if it works), your shebang (#!) line needs to look like this:

#!/usr/bin/php

Put that at the top of your script, make it executable (chmod +x myscript.php), and make a Cron job to execute that script (same way you'd execute a bash script).

You can also use php myscript.php.

Get type name without full namespace

Try this to get type parameters for generic types:

public static string CSharpName(this Type type)
{
    var sb = new StringBuilder();
    var name = type.Name;
    if (!type.IsGenericType) return name;
    sb.Append(name.Substring(0, name.IndexOf('`')));
    sb.Append("<");
    sb.Append(string.Join(", ", type.GetGenericArguments()
                                    .Select(t => t.CSharpName())));
    sb.Append(">");
    return sb.ToString();
}

Maybe not the best solution (due to the recursion), but it works. Outputs look like:

Dictionary<String, Object>

How to remove blank lines from a Unix file

Use grep to match any line that has nothing between the start anchor (^) and the end anchor ($):

grep -v '^$' infile.txt > outfile.txt

If you want to remove lines with only whitespace, you can still use grep. I am using Perl regular expressions in this example, but here are other ways:

grep -P -v '^\s*$' infile.txt > outfile.txt

or, without Perl regular expressions:

grep -v '^[[:space:]]*$' infile.txt > outfile.txt

getting only name of the class Class.getName()

Here is the Groovy way of accessing object properties:

this.class.simpleName    # returns the simple name of the current class

Is SQL syntax case sensitive?

I don't think SQL Server is case-sensitive, at least not by default.

When I'm querying manually via Management Studio, I mess up case all the time and it cheerfully accepts it:

select cOL1, col2 FrOM taBLeName WheRE ...

How exactly does the android:onClick XML attribute differ from setOnClickListener?

Suppose, You want to add click event like this main.xml

<Button
    android:id="@+id/btn_register"
    android:layout_margin="1dp"
    android:layout_marginLeft="3dp"
    android:layout_marginTop="10dp"
    android:layout_weight="2"
    android:onClick="register"
    android:text="Register"
    android:textColor="#000000"/>

In java file, you have to write a method like this method.

public void register(View view) {
}

Invoke a second script with arguments from a script

I tried the accepted solution of using the Invoke-Expression cmdlet but it didn't work for me because my arguments had spaces on them. I tried to parse the arguments and escape the spaces but I couldn't properly make it work and also it was really a dirty work around in my opinion. So after some experimenting, my take on the problem is this:

function Invoke-Script
{
    param
    (
        [Parameter(Mandatory = $true)]
        [string]
        $Script,

        [Parameter(Mandatory = $false)]
        [object[]]
        $ArgumentList
    )

    $ScriptBlock = [Scriptblock]::Create((Get-Content $Script -Raw))
    Invoke-Command -NoNewScope -ArgumentList $ArgumentList -ScriptBlock $ScriptBlock -Verbose
}

# example usage
Invoke-Script $scriptPath $argumentList

The only drawback of this solution is that you need to make sure that your script doesn't have a "Script" or "ArgumentList" parameter.

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

Create a Game model which extends Eloquent and use this:

Game::take(30)->skip(30)->get();

take() here will get 30 records and skip() here will offset to 30 records.


In recent Laravel versions you can also use:

Game::limit(30)->offset(30)->get();

window.close() doesn't work - Scripts may close only the windows that were opened by it

The windows object has a windows field in which it is cloned and stores the date of the open window, close should be called on this field:

window.open("", '_self').window.close();

How to Diff between local uncommitted changes and origin

If you want to compare files visually you can use:

git difftool

It will start your diff app automatically for each changed file.

PS: If you did not set a diff app, you can do it like in the example below(I use Winmerge):

git config --global merge.tool winmerge
git config --replace --global mergetool.winmerge.cmd "\"C:\Program Files (x86)\WinMerge\WinMergeU.exe\" -e -u -dl \"Base\" -dr \"Mine\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\""
git config --global mergetool.prompt false

How to store file name in database, with other info while uploading image to server using PHP?

Here is the answer for those of you looking like I did all over the web trying to find out how to do this task. Uploading a photo to a server with the file name stored in a mysql database and other form data you want in your Database. Please let me know if it helped.

Firstly the form you need:

    <form method="post" action="addMember.php" enctype="multipart/form-data">
    <p>
              Please Enter the Band Members Name.
            </p>
            <p>
              Band Member or Affiliates Name:
            </p>
            <input type="text" name="nameMember"/>
            <p>
              Please Enter the Band Members Position. Example:Drums.
            </p>
            <p>
              Band Position:
            </p>
            <input type="text" name="bandMember"/>
            <p>
              Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
            </p>
            <p>
              Photo:
            </p>
            <input type="hidden" name="size" value="350000">
            <input type="file" name="photo"> 
            <p>
              Please Enter any other information about the band member here.
            </p>
            <p>
              Other Member Information:
            </p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
            <p>
              Please Enter any other Bands the Member has been in.
            </p>
            <p>
              Other Bands:
            </p>
            <input type="text" name="otherBands" size=30 />
            <br/>
            <br/>
            <input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
          </form>

Then this code processes you data from the form:

   <?php

// This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);

// This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];


// Connects to your Database
mysqli_connect("yourhost", "username", "password") or die(mysqli_error()) ;
mysqli_select_db("dbName") or die(mysqli_error()) ;

// Writes the information to the database
mysqli_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

// Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

// Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

// Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?> 

Code edited from www.about.com

OpenSSL Command to check if a server is presenting a certificate

15841:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:s23_lib.c:188:
...
SSL handshake has read 0 bytes and written 121 bytes

This is a handshake failure. The other side closes the connection without sending any data ("read 0 bytes"). It might be, that the other side does not speak SSL at all. But I've seen similar errors on broken SSL implementation, which do not understand newer SSL version. Try if you get a SSL connection by adding -ssl3 to the command line of s_client.

Setting the correct PATH for Eclipse

For me none worked. I compared my existing eclipse.ini with a new one and started removing options and testing if eclipse worked.

The only option that prevented eclipse from starting was -XX:+UseParallelGC, so I removed it and voilá!

How can I specify system properties in Tomcat configuration on startup?

Generally you shouldn't rely on system properties to configure a webapp - they may be used to configure the container (e.g. Tomcat) but not an application running inside tomcat.

cliff.meyers has already mentioned the way you should rather use for your webapplication. That's the standard way, that also fits your question of being configurable through context.xml or server.xml means.

That said, should you really need system properties or other jvm options (like max memory settings) in tomcat, you should create a file named "bin/setenv.sh" or "bin/setenv.bat". These files do not exist in the standard archive that you download, but if they are present, the content is executed during startup (if you start tomcat via startup.sh/startup.bat). This is a nice way to separate your own settings from the standard tomcat settings and makes updates so much easier. No need to tweak startup.sh or catalina.sh.

(If you execute tomcat as windows servive, you usually use tomcat5w.exe, tomcat6w.exe etc. to configure the registry settings for the service.)

EDIT: Also, another possibility is to go for JNDI Resources.

Passing Variable through JavaScript from one html page to another page

You have a few different options:

  • you can use a SPA router like SammyJS, or Angularjs and ui-router, so your pages are stateful.
  • use sessionStorage to store your state.
  • store the values on the URL hash.

Storing and displaying unicode string (??????) using PHP and MySQL

For Those who are facing difficulty just got to php admin and change collation to utf8_general_ci Select Table go to Operations>> table options>> collations should be there

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

A simple solution is

UUID.randomUUID().toString().replace("-", "")

(Like the existing solutions, only that it avoids the String#replaceAll call. Regular expression replacement is not required here, so String#replace feels more natural, though technically it still is implemented with regular expressions. Given that the generation of the UUID is more costly than the replacement, there should not be a significant difference in runtime.)

Using the UUID class is probably fast enough for most scenarios, though I would expect that some specialized hand-written variant, which does not need the postprocessing, to be faster. Anyway, the bottleneck of the overall computation will normally be the random number generator. In case of the UUID class, it uses SecureRandom.

Which random number generator to use is also a trade-off that depends on the application. If it is security-sensitive, SecureRandom is, in general, the recommendation. Otherwise, ThreadLocalRandom is an alternative (faster than SecureRandom or the old Random, but not cryptographically secure).

Adding blur effect to background in swift

Found another way.. I use apple's UIImage+ImageEffects.

 UIImage *effectImage = [image applyExtraLightEffect];                        
 self.imageView.image = effectImage;

Change the Theme in Jupyter Notebook?

Instead of installing a library inside Jupyter, I would recommend you use the 'Dark Reader' extension in Chrome (you can find 'Dark Reader' extension in other browsers, e.g. Firefox). You can play with it; filter the URL(s) you want to have dark theme, or even how define the Dark theme for yourself. Below are couple of examples:

enter image description here

enter image description here

I hope it helps.

What is the best way to get the minimum or maximum value from an Array of numbers?

You have to loop through the array, no other way to check all elements. Just one correction for the code - if all elements are negative, maxValue will be 0 at the end. You should initialize it with the minimum possible value for integer.
And if you are going to search the array many times it's a good idea to sort it first, than searching is faster (binary search) and minimum and maximum elements are just the first and the last.

How To Raise Property Changed events on a Dependency Property?

I ran into a similar problem where I have a dependency property that I wanted the class to listen to change events to grab related data from a service.

public static readonly DependencyProperty CustomerProperty = 
    DependencyProperty.Register("Customer", typeof(Customer),
        typeof(CustomerDetailView),
        new PropertyMetadata(OnCustomerChangedCallBack));

public Customer Customer {
    get { return (Customer)GetValue(CustomerProperty); }
    set { SetValue(CustomerProperty, value); }
}

private static void OnCustomerChangedCallBack(
        DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    CustomerDetailView c = sender as CustomerDetailView;
    if (c != null) {
        c.OnCustomerChanged();
    }
}

protected virtual void OnCustomerChanged() {
    // Grab related data.
    // Raises INotifyPropertyChanged.PropertyChanged
    OnPropertyChanged("Customer");
}

How to reset the use/password of jenkins on windows?

Read Initial password :

C:\Program Files(x86)\Jenkins\secrets\initialAdminPassword

Default username is 'admin' and the password is the one from initialAdminPassword when you follow the above path.

'Manage Jenkins' --> 'Manage Users' --> Password

Then logout and login to make sure new password works.

Print string and variable contents on the same line in R

The {glue} package offers string interpolation. In the example, {wd} is substituted with the contents of the variable. Complex expressions are also supported.

library(glue)

wd <- getwd()
glue("Current working dir: {wd}")
#> Current working dir: /tmp/RtmpteMv88/reprex46156826ee8c

Created on 2019-05-13 by the reprex package (v0.2.1)

Note how the printed output doesn't contain the [1] artifacts and the " quotes, for which other answers use cat().

How to insert a file in MySQL database?

File size by MySQL type:

  • TINYBLOB 255 bytes = 0.000255 Mb
  • BLOB 65535 bytes = 0.0655 Mb
  • MEDIUMBLOB 16777215 bytes = 16.78 Mb
  • LONGBLOB 4294967295 bytes = 4294.97 Mb = 4.295 Gb

Change WPF window background image in C# code

img.UriSource = new Uri("pack://application:,,,/images/" + fileName, UriKind.Absolute);

How to check if an user is logged in Symfony2 inside a controller?

If you are using security annotation from the SensioFrameworkExtraBundle, you can use a few expressions (that are defined in \Symfony\Component\Security\Core\Authorization\ExpressionLanguageProvider):

  • @Security("is_authenticated()"): to check that the user is authed and not anonymous
  • @Security("is_anonymous()"): to check if the current user is the anonymous user
  • @Security("is_fully_authenticated()"): equivalent to is_granted('IS_AUTHENTICATED_FULLY')
  • @Security("is_remember_me()"): equivalent to is_granted('IS_AUTHENTICATED_REMEMBERED')

Error renaming a column in MySQL

The standard Mysql rename statement is:

ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name 
CHANGE [COLUMN] old_col_name new_col_name column_definition 
[FIRST|AFTER col_name]

for this example:

ALTER TABLE xyz CHANGE manufacurerid manufacturerid datatype(length)

Reference: MYSQL 5.1 ALTER TABLE Syntax

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

List myArrayList  = Collections.synchronizedList(new ArrayList());

//add your elements  
 myArrayList.add();
 myArrayList.add();
 myArrayList.add();

synchronized(myArrayList) {
    Iterator i = myArrayList.iterator(); 
     while (i.hasNext()){
         Object  object = i.next();
     }
 }

How to increase editor font size?

Permanently change the default font size for UI elements

Go to Settings ("Preferences" on Mac) > Appearance & Behavior > Appearance. Tick the checkbox "Override default fonts by (not recommended)". Then change the font size and hit "OK"
enter image description here

For loop example in MySQL

Assume you have one table with name 'table1'. It contain one column 'col1' with varchar type. Query to crate table is give below

CREATE TABLE `table1` (
    `col1` VARCHAR(50) NULL DEFAULT NULL
)

Now if you want to insert number from 1 to 50 in that table then use following stored procedure

DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      DECLARE a INT Default 1 ;
      simple_loop: LOOP         
         insert into table1 values(a);
         SET a=a+1;
         IF a=51 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$

To call that stored procedure use

CALL `ABC`()

getResources().getColor() is deprecated

well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor function. You can get current theme with getTheme().

This will do the trick in fragment, you can replace getActivity() with getBaseContext(), yourContext, etc which hold your current context

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}

*p.s : color is deprecated in M, but drawable is deprecated in L

Access is denied when attaching a database

It is in fact NTFS permissions, and a strange bug in SQL Server. I'm not sure the above bug report is accurate, or may refer to an additional bug.

To resolve this on Windows 7, I ran SQL Server Management Studio normally (not as Administrator). I then attempted to Attach the MDF file. In the process, I used the UI rather than pasting in the path. I noticed that the path was cut off from me. This is because the MS SQL Server (SQLServerMSSQLUser$machinename$SQLEXPRESS) user that the software adds for you does not have permissions to access the folder (in this case a folder deep in my own user folders).

Pasting the path and proceeding results in the above error. So - I gave the MS SQL Server user permissions to read starting from the first directory it was denied from (my user folder). I then immediately cancelled the propagation operation because it can take an eternity, and again applied read permissions to the next subfolder necessary, and let that propagate fully.

Finally, I gave the MS SQL Server user Modify permissions to the .mdf and .ldf files for the db.

I can now Attach to the database files.

How to install PyQt5 on Windows?

easiest way, I think download Eric, unzip go to sources, open python directory, drag the install script into the python icon, not folder, follow prompts

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

for (int i = 0; i < nodeList.getLength(); i++)

change to

for (int i = 0, len = nodeList.getLength(); i < len; i++)

to be more efficient.

The second way of javanna answer may be the best as it tends to use a flatter, predictable memory model.

How to position a CSS triangle using ::after?

Just add position:relative to the parent element .sidebar-resources-categories

http://jsfiddle.net/matthewabrman/5msuY/

explanation: the ::after elements position is based off of it's parent, in your example you probably had a parent element of the .sidebar-res... which had a set height, therefore it rendered just below it. Adding position relative to the .sidebar-res... makes the after elements move to 100% of it's parent which now becomes the .sidebar-res... because it's position is set to relative. I'm not sure how to explain it but it's expected behaviour.

read more on the subject: http://css-tricks.com/absolute-positioning-inside-relative-positioning/

Get the last 4 characters of a string

str = "aaaaabbbb"
newstr = str[-4:]

See : http://codepad.org/S3zjnKoD

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

You can use a pseudo-element to insert that character before each list item:

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  content: '?';_x000D_
}
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

What is the maximum possible length of a query string?

Although officially there is no limit specified by RFC 2616, many security protocols and recommendations state that maxQueryStrings on a server should be set to a maximum character limit of 1024. While the entire URL, including the querystring, should be set to a max of 2048 characters. This is to prevent the Slow HTTP Request DDOS vulnerability on a web server. This typically shows up as a vulnerability on the Qualys Web Application Scanner and other security scanners.

Please see the below example code for Windows IIS Servers with Web.config:

<system.webServer>
<security>
    <requestFiltering>
        <requestLimits maxQueryString="1024" maxUrl="2048">
           <headerLimits>
              <add header="Content-type" sizeLimit="100" />
           </headerLimits>
        </requestLimits>
     </requestFiltering>
</security>
</system.webServer>

This would also work on a server level using machine.config.

Note: Limiting query string and URL length may not completely prevent Slow HTTP Requests DDOS attack but it is one step you can take to prevent it.

How do I rename a local Git branch?

In PhpStorm:

VCS ? Git ? Branches... ? Local Branches ? _your_branch_ ? Rename

How to add an element to a list?

Elements are added to list using append():

>>> data = {'list': [{'a':'1'}]}
>>> data['list'].append({'b':'2'})
>>> data
{'list': [{'a': '1'}, {'b': '2'}]}

If you want to add element to a specific place in a list (i.e. to the beginning), use insert() instead:

>>> data['list'].insert(0, {'b':'2'})
>>> data
{'list': [{'b': '2'}, {'a': '1'}]}

After doing that, you can assemble JSON again from dictionary you modified:

>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'

SQL Inner-join with 3 tables?

SELECT column_Name1,column_name2,......
  From tbl_name1,tbl_name2,tbl_name3
  where tbl_name1.column_name = tbl_name2.column_name 
  and tbl_name2.column_name = tbl_name3.column_name

JAX-WS - Adding SOAP Headers

Adding an object to header we use the examples used here,yet i will complete

  ObjectFactory objectFactory = new ObjectFactory();
        CabeceraCR cabeceraCR =objectFactory.createCabeceraCR();
        cabeceraCR.setUsuario("xxxxx");
        cabeceraCR.setClave("xxxxx");

With object factory we create the object asked to pass on the header. The to add to the header

  WSBindingProvider bp = (WSBindingProvider)wsXXXXXXSoap;
        bp.setOutboundHeaders(
                // Sets a simple string value as a header
                Headers.create(jaxbContext,objectFactory.createCabeceraCR(cabeceraCR))
                );

We used the WSBindingProvider to add the header. The object will have some error if used directly so we use the method

objectFactory.createCabeceraCR(cabeceraCR)

This method will create a JAXBElement like this on the object Factory

  @XmlElementDecl(namespace = "http://www.creditreport.ec/", name = "CabeceraCR")
    public JAXBElement<CabeceraCR> createCabeceraCR(CabeceraCR value) {
        return new JAXBElement<CabeceraCR>(_CabeceraCR_QNAME, CabeceraCR.class, null, value);
    }

And the jaxbContext we obtained like this:

  jaxbContext = (JAXBRIContext) JAXBContext.newInstance(CabeceraCR.class.getPackage().getName());

This will add the object to the header.

Remove a HTML tag but keep the innerHtml

$('b').contents().unwrap();

This selects all <b> elements, then uses .contents() to target the text content of the <b>, then .unwrap() to remove its parent <b> element.


For the greatest performance, always go native:

var b = document.getElementsByTagName('b');

while(b.length) {
    var parent = b[ 0 ].parentNode;
    while( b[ 0 ].firstChild ) {
        parent.insertBefore(  b[ 0 ].firstChild, b[ 0 ] );
    }
     parent.removeChild( b[ 0 ] );
}

This will be much faster than any jQuery solution provided here.

How to Load an Assembly to AppDomain with all references recursively?

On your new AppDomain, try setting an AssemblyResolve event handler. That event gets called when a dependency is missing.

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

I faced same problem and tried all the above solution. Sadly nothing work.

  1. Socket Timeout (Not worked)
  2. User Agent (Not Worked)
  3. SoapClient configuration, cache_wsdl and Keep-Alive etc..

This whole game of headers that we are passing. I solved my problem with adding the compression header property. This actually require when you are expecting response in gzip compressed format.

//set the Headers of Soap Client. 
$client = new SoapClient($wsdlUrl, array(
    'trace' => true, 
    'keep_alive' => true,
    'connection_timeout' => 5000,
    'cache_wsdl' => WSDL_CACHE_NONE,
    'compression'   => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP | SOAP_COMPRESSION_DEFLATE,
));

Hope it helps.

Good luck.

What is HTML5 ARIA?

ARIA stands for Accessible Rich Internet Applications.

WAI-ARIA is an incredibly powerful technology that allows developers to easily describe the purpose, state and other functionality of visually rich user interfaces - in a way that can be understood by Assistive Technology. WAI-ARIA has finally been integrated into the current working draft of the HTML 5 specification.

And if you are wondering what WAI-ARIA is, its the same thing.

Please note the terms WAI-ARIA and ARIA refer to the same thing. However, it is more correct to use WAI-ARIA to acknowledge its origins in WAI.

WAI = Web Accessibility Initiative

From the looks of it, ARIA is used for assistive technologies and mostly screen reading.

Most of your doubts will be cleared if you read this article

http://www.w3.org/TR/aria-in-html/

Genymotion error at start 'Unable to load virtualbox'

Try closing Android Studio/Eclipse if it's open. It worked for me.

Is it possible to reference one CSS rule within another?

You can easily do so with SASS pre-processor by using @extend.

someDiv {
    @extend .opacity;
    @extend .radius;
}

Ohterwise, you could use JavaScript (jQuery) as well:

$('someDiv').addClass('opacity radius')

The easiest is of course to add multiple classes right in the HTML

<div class="opacity radius">

Run JavaScript when an element loses focus

onblur is the opposite of onfocus.

Why is HttpClient BaseAddress not working?

It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress and the relative URI passed to the GetAsync method -- or whichever other method of HttpClient -- only one permutation works. You must place a slash at the end of the BaseAddress, and you must not place a slash at the beginning of your relative URI, as in the following example.

using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
    client.BaseAddress = new Uri("http://something.com/api/");
    var response = await client.GetAsync("resource/7");
}

Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient.

How can I make an "are you sure" prompt in a Windows batchfile?

You want something like:

@echo off
setlocal
:PROMPT
SET /P AREYOUSURE=Are you sure (Y/[N])?
IF /I "%AREYOUSURE%" NEQ "Y" GOTO END

echo ... rest of file ...


:END
endlocal

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

How do I use IValidatableObject?

I implemented a general usage abstract class for validation

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace App.Abstractions
{
    [Serializable]
    abstract public class AEntity
    {
        public int Id { get; set; }

        public IEnumerable<ValidationResult> Validate()
        {
            var vResults = new List<ValidationResult>();

            var vc = new ValidationContext(
                instance: this,
                serviceProvider: null,
                items: null);

            var isValid = Validator.TryValidateObject(
                instance: vc.ObjectInstance,
                validationContext: vc,
                validationResults: vResults,
                validateAllProperties: true);

            /*
            if (true)
            {
                yield return new ValidationResult("Custom Validation","A Property Name string (optional)");
            }
            */

            if (!isValid)
            {
                foreach (var validationResult in vResults)
                {
                    yield return validationResult;
                }
            }

            yield break;
        }


    }
}

Javac is not found

You don't have jdk1.7.0_17 in your PATH - check again. There is only JRE which may not contain 'javac' compiler.

Besides it is best to set JAVA_HOME variable, and then include it in PATH.

How do I POST with multipart form data using fetch?

I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:

curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"

The basic idea is that each part (split by string in boundary with --) has it's own headers (Content-Type in the second part, for example.) The FormData object manages all this for you, so it's a better way to accomplish our goals.

This translates to fetch API like this:

const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')

fetch('http://localhost:5001/api/v0/add', {
  method: 'POST',
  body: formData
})
.then(r => r.json())
.then(data => {
  console.log(data)
})

Loading an image to a <img> from <input file>

As iEamin said in his answer, HTML 5 does now support this. The link he gave, http://www.html5rocks.com/en/tutorials/file/dndfiles/ , is excellent. Here is a minimal sample based on the samples at that site, but see that site for more thorough examples.

Add an onchange event listener to your HTML:

<input type="file" onchange="onFileSelected(event)">

Make an image tag with an id (I'm specifying height=200 to make sure the image isn't too huge onscreen):

<img id="myimage" height="200">

Here is the JavaScript of the onchange event listener. It takes the File object that was passed as event.target.files[0], constructs a FileReader to read its contents, and sets up a new event listener to assign the resulting data: URL to the img tag:

function onFileSelected(event) {
  var selectedFile = event.target.files[0];
  var reader = new FileReader();

  var imgtag = document.getElementById("myimage");
  imgtag.title = selectedFile.name;

  reader.onload = function(event) {
    imgtag.src = event.target.result;
  };

  reader.readAsDataURL(selectedFile);
}

How can I calculate the time between 2 Dates in typescript

It doesn't work because Date - Date relies on exactly the kind of type coercion TypeScript is designed to prevent.

There is a workaround this using the + prefix:

var t = Date.now() - +(new Date("2013-02-20T12:01:04.753Z");

Or, if you prefer not to use Date.now():

var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));

See discussion here.

Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()

Threading Example in Android

Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.

Android code - Main.java

package test12.tt;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Test12Activity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final TextView txt1 = (TextView) findViewById(R.id.sm);

        new Thread(new Runnable() { 
            public void run(){        
            txt1.setText("Thread!!");
            }
        }).start();

    }    
}

Android application xml - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView  
    android:id = "@+id/sm"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"/>

</LinearLayout>

PDO mysql: How to know if insert was successful

Use id as primary key with auto increment

$stmt->execute();
$insertid = $conn->lastInsertId();

incremental id is always bigger than zero even on first record so that means it will always return a true value for id coz bigger than zero means true in PHP

if ($insertid)
   echo "record inserted successfully";
else
   echo "record insertion failed";

python xlrd unsupported format, or corrupt file.

Worked on the same issue , finally done this is top for the question so just putting what i did.

Observation - 1 -The file was not actually XLS i renamed to txt and noticed HTML text in file.

2 - Renamed the file to html and tried reading pd.read_html, Failed.

3- Added as it was not there in txt file, removed style to ensure that table is displaying in browser from local, and WORKED.

Below is the code may help someone..

import pandas as pd
import os
import shutil
import html5lib
import requests
from bs4 import BeautifulSoup
import re
import time

shutil.copy('your.xls','file.html')
shutil.copy('file.html','file.txt')
time.sleep(2)

txt = open('file.txt','r').read()

# Modify the text to ensure the data display in html page, delete style

txt = str(txt).replace('<style> .text { mso-number-format:\@; } </script>','')

# Add head and body if it is not there in HTML text

txt_with_head = '<html><head></head><body>'+txt+'</body></html>'

# Save the file as HTML

html_file = open('output.html','w')
html_file.write(txt_with_head)

# Use beautiful soup to read

url = r"C:\Users\hitesh kumar\PycharmProjects\OEM ML\output.html"
page = open(url)
soup = BeautifulSoup(page.read(), features="lxml")
my_table = soup.find("table",attrs={'border': '1'})

frame = pd.read_html(str(my_table))[0]
print(frame.head())
frame.to_excel('testoutput.xlsx',sheet_name='sheet1', index=False)

Are arrays passed by value or passed by reference in Java?

Kind of a trick realty... Even references are passed by value in Java, hence a change to the reference itself being scoped at the called function level. The compiler and/or JVM will often turn a value type into a reference.

Change Bootstrap input focus blue glow

You can use the .form-control selector to match all inputs. For example to change to red:

.form-control:focus {
  border-color: #FF0000;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(255, 0, 0, 0.6);
}

Put it in your custom css file and load it after bootstrap.css. It will apply to all inputs including textarea, select etc...

How to generate a git patch for a specific commit?

To generate path from a specific commit (not the last commit):

git format-patch -M -C COMMIT_VALUE~1..COMMIT_VALUE

How do I convert 2018-04-10T04:00:00.000Z string to DateTime?

Update: Using DateTimeFormat, introduced in java 8:

The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.

Your input format looks quite standard, except the trailing Z. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". The trailing 'Z' is the interesting part. Usually there's time zone data here, like -0700. So the pattern would be ...Z, i.e. without apostrophes.

The output format is way more simple: "dd-MM-yyyy". Mind the small y -s.

Here is the example code:

DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018

Original answer - with old API SimpleDateFormat

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018

typescript - cloning object

For deep cloning an object that can contain another objects, arrays and so on i use:

const clone = <T>(source: T): T => {
  if (source === null) return source

  if (source instanceof Date) return new Date(source.getTime()) as any

  if (source instanceof Array) return source.map((item: any) => clone<any>(item)) as any

  if (typeof source === 'object' && source !== {}) {
    const clonnedObj = { ...(source as { [key: string]: any }) } as { [key: string]: any }
    Object.keys(clonnedObj).forEach(prop => {
      clonnedObj[prop] = clone<any>(clonnedObj[prop])
    })

    return clonnedObj as T
  }

  return source
}

Use:

const obj = {a: [1,2], b: 's', c: () => { return 'h'; }, d: null, e: {a:['x'] }}
const objClone = clone(obj)

How to get access token from FB.login method in javascript SDK

If you are already connected, simply type this in the javascript console:

FB.getAuthResponse()['accessToken']

Automatically create requirements.txt

If you use virtual environment, pip freeze > requirements.txt just fine. IF NOT, pigar will be a good choice for you.

By the way, I do not ensure it will work with 2.6.

UPDATE:

Pipenv or other tools is recommended for improving your development flow.

For Python 3 use below

pip3 freeze > requirements.txt

Chrome violation : [Violation] Handler took 83ms of runtime

"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript and took 83ms of runtime are alerting you there's probably an opportunity to speed up your script.

("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)

c++ custom compare function for std::sort()

Look here: http://en.cppreference.com/w/cpp/algorithm/sort.

It says:

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
  • comp - comparison function which returns ?true if the first argument is less than the second. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b);

Also, here's an example of how you can use std::sort using a custom C++14 polymorphic lambda:

std::sort(std::begin(container), std::end(container),
          [] (const auto& lhs, const auto& rhs) {
    return lhs.first < rhs.first;
});

for-in statement

TypeScript isn't giving you a gun to shoot yourself in the foot with.

The iterator variable is a string because it is a string, full stop. Observe:

var obj = {};
obj['0'] = 'quote zero quote';
obj[0.0] = 'zero point zero';
obj['[object Object]'] = 'literal string "[object Object]"';
obj[<any>obj] = 'this obj'
obj[<any>undefined] = 'undefined';
obj[<any>"undefined"] = 'the literal string "undefined"';

for(var key in obj) {
    console.log('Type: ' + typeof key);
    console.log(key + ' => ' + obj[key]);
}

How many key/value pairs are in obj now? 6, more or less? No, 3, and all of the keys are strings:

Type: string
0 => zero point zero
Type: string
[object Object] => this obj; 
Type: string
undefined => the literal string "undefined" 

Is there a way to list all resources in AWS

The AWS-provided tools are not useful because they are not comprehensive.

In my own quest to mitigate this problem and pull a list of all of my AWS resources, I found this: https://github.com/JohannesEbke/aws_list_all

I have not tested it yet, but it looks legit.

Change Button color onClick

There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation.

Your code could look like this:

<script>
    var count = 1;
    function setColor(btn, color) {
        var property = document.getElementById(btn);
        if (count == 0) {
            property.style.backgroundColor = "#FFFFFF"
            count = 1;        
        }
        else {
            property.style.backgroundColor = "#7FFF00"
            count = 0;
        }
    }
</script>

Hope this helps.

jQuery UI " $("#datepicker").datepicker is not a function"

This error usually appears when you're missing a file from the jQuery UI set.

Double-check that you have all the files, the jQuery UI files as well as the CSS and images, and that they're in the correctly linked file/directory location on your server.

How to set dialog to show in full screen?

dialog = new Dialog(getActivity(),android.R.style.Theme_Translucent_NoTitleBar);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.loading_screen);
    Window window = dialog.getWindow();
    WindowManager.LayoutParams wlp = window.getAttributes();

    wlp.gravity = Gravity.CENTER;
    wlp.flags &= ~WindowManager.LayoutParams.FLAG_BLUR_BEHIND;
    window.setAttributes(wlp);
    dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    dialog.show();

try this.

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

The reason is that when you use lazy load, the session is closed.

There are two solutions.

  1. Don't use lazy load.

    Set lazy=false in XML or Set @OneToMany(fetch = FetchType.EAGER) In annotation.

  2. Use lazy load.

    Set lazy=true in XML or Set @OneToMany(fetch = FetchType.LAZY) In annotation.

    and add OpenSessionInViewFilter filter in your web.xml

Detail See my post.

https://stackoverflow.com/a/27286187/1808417

How to get the client IP address in PHP

This function should work as expected

function Get_User_Ip()
{
    $IP = false;
    if (getenv('HTTP_CLIENT_IP'))
    {
        $IP = getenv('HTTP_CLIENT_IP');
    }
    else if(getenv('HTTP_X_FORWARDED_FOR'))
    {
        $IP = getenv('HTTP_X_FORWARDED_FOR');
    }
    else if(getenv('HTTP_X_FORWARDED'))
    {
        $IP = getenv('HTTP_X_FORWARDED');
    }
    else if(getenv('HTTP_FORWARDED_FOR'))
    {
        $IP = getenv('HTTP_FORWARDED_FOR');
    }
    else if(getenv('HTTP_FORWARDED'))
    {
        $IP = getenv('HTTP_FORWARDED');
    }
    else if(getenv('REMOTE_ADDR'))
    {
        $IP = getenv('REMOTE_ADDR');
    }

    //If HTTP_X_FORWARDED_FOR == server ip
    if((($IP) && ($IP == getenv('SERVER_ADDR')) && (getenv('REMOTE_ADDR')) || (!filter_var($IP, FILTER_VALIDATE_IP))))
    {
        $IP = getenv('REMOTE_ADDR');
    }

    if($IP)
    {
        if(!filter_var($IP, FILTER_VALIDATE_IP))
        {
            $IP = false;
        }
    }
    else
    {
        $IP = false;
    }
    return $IP;
}

Sending data from HTML form to a Python script in Flask

You need a Flask view that will receive POST data and an HTML form that will send it.

from flask import request

@app.route('/addRegion', methods=['POST'])
def addRegion():
    ...
    return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
    Project file path: <input type="text" name="projectFilePath"><br>
    <input type="submit" value="Submit">
</form>

Is it possible to have a default parameter for a mysql stored procedure?

We worked around this limitation by adding a simple IF statement in the stored procedure. Practically we pass an empty string whenever we want to save the default value in the DB.

CREATE DEFINER=`test`@`%` PROCEDURE `myProc`(IN myVarParam VARCHAR(40))
BEGIN
  IF myVarParam = '' THEN SET myVarParam = 'default-value'; END IF;

  ...your code here...
END

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

I ran into the same problem while I was changing some npm settings. I did a mistake with one npm config set command and this added a line referring to a non-existing directory to C:\Users\{User}\.npmrc. After I deleted that line manually from .npmrc, the problem was gone.

Sort list in C# with LINQ

Well, the simplest way using LINQ would be something like this:

list = list.OrderBy(x => x.AVC ? 0 : 1)
           .ToList();

or

list = list.OrderByDescending(x => x.AVC)
           .ToList();

I believe that the natural ordering of bool values is false < true, but the first form makes it clearer IMO, because everyone knows that 0 < 1.

Note that this won't sort the original list itself - it will create a new list, and assign the reference back to the list variable. If you want to sort in place, you should use the List<T>.Sort method.

How to get all key in JSON object (javascript)

var input = {"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
    Object.keys(input.document.people[i]).forEach(function(key){
        if(keys.indexOf(key) == -1)
        {
            keys.push(key);
        }
    });
}
console.log(keys);

How can I serve static html from spring boot?

I had to add thymeleaf dependency to pom.xml. Without this dependency Spring boot didn't find static resources.

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Differences between hard real-time, soft real-time, and firm real-time?

It's popular to associate some great catastrophe with the definition of hard real-time, but this is not relevant. Any failure to meet a hard real-time constraint simply means that the system is broken. The severity of the outcome when something is labelled "broken" isn't material to the definition.

Firm and soft simply fail to be automatically declared broken on failing to meet a single deadline.

For a fair example of hard real-time, from the page you linked:

Early video game systems such as the Atari 2600 and Cinematronics vector graphics had hard real-time requirements because of the nature of the graphics and timing hardware.

If something in the video generation loop missed just a single deadline then the whole display would glitch, which would be intolerable, even if it was rare. That would be a broken system and you'd take it back to the shop for a refund. So it's hard real-time.

Obviously any system can be subject to situations it cannot handle, so it's necessary to restrict the definition to being within the expected operating conditions -- noting that in safety-critical applications people must plan for terrible conditions ("the coolant has evaporated", "the brakes have failed", but rarely "the sun has exploded").

And lets not forget that sometimes there's an implicit "while anybody is watching" operating condition. If nobody sees you break the rules (or if they did but they die the fire before telling anyone), and nobody can prove that you broke the rules after the fact, then it's kind of the same as if you never broke the rules!

How do I get the offset().top value of an element without using jQuery?

the accepted solution by Patrick Evans doesn't take scrolling into account. i've slightly changed his jsfiddle to demonstrate this:

css: add some random height to make sure we got some space to scroll

body{height:3000px;} 

js: set some scroll position

jQuery(window).scrollTop(100);

as a result the two reported values differ now: http://jsfiddle.net/sNLMe/66/

UPDATE Feb. 14 2015

there is a pull request for jqLite waiting, including its own offset method (taking care of current scroll position). have a look at the source in case you want to implement it yourself: https://github.com/angular/angular.js/pull/3799/files

How to select option in drop down protractorjs e2e tests

static selectDropdownValue(dropDownLocator,dropDownListLocator,dropDownValue){
    let ListVal ='';
    WebLibraryUtils.getElement('xpath',dropDownLocator).click()
      WebLibraryUtils.getElements('xpath',dropDownListLocator).then(function(selectItem){
        if(selectItem.length>0)
        {
            for( let i =0;i<=selectItem.length;i++)
               {
                   if(selectItem[i]==dropDownValue)
                   {
                       console.log(selectItem[i])
                       selectItem[i].click();
                   }
               }            
        }

    })

}

Best way to script remote SSH commands in Batch (Windows)

The -m switch of PuTTY takes a path to a script file as an argument, not a command.

Reference: https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m

So you have to save your command (command_run) to a plain text file (e.g. c:\path\command.txt) and pass that to PuTTY:

putty.exe -ssh user@host -pw password -m c:\path\command.txt

Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).

A command-line syntax is identical, an output redirection added:

plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt

See Using the command-line connection tool Plink.

And with Plink, you can actually provide the command directly on its command-line:

plink.exe -ssh user@host -pw password command > output.txt

Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file

Android Fastboot devices not returning device

TLDR - In addition to the previous responses. There might be a problem with the version of the fastboot command. Try to download the newest one via Android SDK Manager instead of default one available in the OS repository.

There is one more thing you can do to fix this issue. I had the similar problem when trying to flash Nexus Player. All the adb commands we working fine while in normal boot mode. However, after switching to fastboot mode I wasn't able to execute fastboot commands. My device was not visible in the output of the fastboot devices command. I've set the right rules in /etc/udev/rules.d/11-android.rules file. The lsusb command showed that the device has been pluged in.

The soultion was quite simple. I've downloaded the the fastboot via Android Studio's SDK Manager instead of using the default one available in Ubuntu packages.

All you need is sdkmanager. Download the Android SDK Platform Tools and replace the default /usr/bin/fastboot with the new one.

Cannot import keras after installation

Diagnose

If you have pip installed (you should have it until you use Python 3.5), list the installed Python packages, like this:

$ pip list | grep -i keras
Keras (1.1.0)

If you don’t see Keras, it means that the previous installation failed or is incomplete (this lib has this dependancies: numpy (1.11.2), PyYAML (3.12), scipy (0.18.1), six (1.10.0), and Theano (0.8.2).)

Consult the pip.log to see what’s wrong.

You can also display your Python path like this:

$ python3 -c 'import sys, pprint; pprint.pprint(sys.path)'
['',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages']

Make sure the Keras library appears in the /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages path (the path is different on Ubuntu).

If not, try do uninstall it, and retry installation:

$ pip uninstall Keras

Use a virtualenv

It’s a bad idea to use and pollute your system-wide Python. I recommend using a virtualenv (see this guide).

The best usage is to create a virtualenv directory (in your home, for instance), and store your virtualenvs in:

cd virtualenv/
virtualenv -p python3.5 py-keras
source py-keras/bin/activate
pip install -q -U pip setuptools wheel

Then install Keras:

pip install keras

You get:

$ pip list
Keras (1.1.0)
numpy (1.11.2)
pip (8.1.2)
PyYAML (3.12)
scipy (0.18.1)
setuptools (28.3.0)
six (1.10.0)
Theano (0.8.2)
wheel (0.30.0a0)

But, you also need to install extra libraries, like Tensorflow:

$ python -c "import keras"
Using TensorFlow backend.
Traceback (most recent call last):
  ...
ImportError: No module named 'tensorflow'

The installation guide of TesnsorFlow is here: https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation

Get selected element's outer HTML

Note that Josh's solution only works for a single element.

Arguably, "outer" HTML only really makes sense when you have a single element, but there are situations where it makes sense to take a list of HTML elements and turn them into markup.

Extending Josh's solution, this one will handle multiple elements:

(function($) {
  $.fn.outerHTML = function() {
    var $this = $(this);
    if ($this.length>1)
      return $.map($this, function(el){ return $(el).outerHTML(); }).join('');
    return $this.clone().wrap('<div/>').parent().html();
  }
})(jQuery);

Edit: another problem with Josh's solution fixed, see comment above.

Show all tables inside a MySQL database using PHP?

How to get tables

1. SHOW TABLES

mysql> USE test;
Database changed
mysql> SHOW TABLES;
+----------------+
| Tables_in_test |
+----------------+
| t1             |
| t2             |
| t3             |
+----------------+
3 rows in set (0.00 sec)

2. SHOW TABLES IN db_name

mysql> SHOW TABLES IN another_db;
+----------------------+
| Tables_in_another_db |
+----------------------+
| t3                   |
| t4                   |
| t5                   |
+----------------------+
3 rows in set (0.00 sec)

3. Using information schema

mysql> SELECT TABLE_NAME
       FROM information_schema.TABLES
       WHERE TABLE_SCHEMA = 'another_db';
+------------+
| TABLE_NAME |
+------------+
| t3         |
| t4         |
| t5         |
+------------+
3 rows in set (0.02 sec)

to OP

you have fetched just 1 row. fix like this:

while ( $tables = $result->fetch_array())
{
    echo $tmp[0]."<br>";
}

and I think, information_schema would be better than SHOW TABLES

SELECT TABLE_NAME
FROM information_schema.TABLES 
WHERE TABLE_SCHEMA = 'your database name'

while ( $tables = $result->fetch_assoc())
{
    echo $tables['TABLE_NAME']."<br>";
}

Argparse: Required arguments listed under "optional arguments"?

One more time, building off of @RalphyZ

This one doesn't break the exposed API.

from argparse import ArgumentParser, SUPPRESS
# Disable default help
parser = ArgumentParser(add_help=False)
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')

# Add back help 
optional.add_argument(
    '-h',
    '--help',
    action='help',
    default=SUPPRESS,
    help='show this help message and exit'
)
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')

Which will show the same as above and should survive future versions:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
           [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  -h, --help                    show this help message and exit
  --optional_arg OPTIONAL_ARG

Invalid hook call. Hooks can only be called inside of the body of a function component

React linter assumes every method starting with use as hooks and hooks doesn't work inside classes. by renaming const useStyles into anything else that doesn't starts with use like const myStyles you are good to go.

Update:

makeStyles is hook api and you can't use that inside classes. you can use styled components API. see here

Javascript setInterval not working

That's because you should pass a function, not a string:

function funcName() {
    alert("test");
}

setInterval(funcName, 10000);

Your code has two problems:

  • var func = funcName(); calls the function immediately and assigns the return value.
  • Just "func" is invalid even if you use the bad and deprecated eval-like syntax of setInterval. It would be setInterval("func()", 10000) to call the function eval-like.

How to Convert UTC Date To Local time Zone in MySql Select Query

 select convert_tz(now(),@@session.time_zone,'+05:30')

replace '+05:30' with desired timezone. see here - https://stackoverflow.com/a/3984412/2359994

to format into desired time format, eg:

 select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%b %d %Y %h:%i:%s %p') 

you will get similar to this -> Dec 17 2014 10:39:56 AM

Are members of a C++ struct initialized to 0 by default?

No, they are not 0 by default. The simplest way to ensure that all values or defaulted to 0 is to define a constructor

Snapshot() : x(0), y(0) {
}

This ensures that all uses of Snapshot will have initialized values.

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

Apart from very good responses here, you could try this as well if you want to use your sub query as is.

Approach:

1) Select the desired column (Only 1) from your sub query

2) Use where to map the column name

Code:

 SELECT count(distinct dNum)
 FROM myDB.dbo.AQ
 WHERE A_ID in 
   (
    SELECT A_ID 
    FROM (SELECT DISTINCT TOP (0.1) PERCENT A_ID, COUNT(DISTINCT dNum) AS ud 
          FROM         myDB.dbo.AQ
          WHERE     M > 1 and B = 0 
          GROUP BY A_ID ORDER BY ud DESC
         ) a 
   )

Get exit code of a background process

As I see almost all answers use external utilities (mostly ps) to poll the state of the background process. There is a more unixesh solution, catching the SIGCHLD signal. In the signal handler it has to be checked which child process was stopped. It can be done by kill -0 <PID> built-in (universal) or checking the existence of /proc/<PID> directory (Linux specific) or using the jobs built-in ( specific. jobs -l also reports the pid. In this case the 3rd field of the output can be Stopped|Running|Done|Exit . ).

Here is my example.

The launched process is called loop.sh. It accepts -x or a number as an argument. For -x is exits with exit code 1. For a number it waits num*5 seconds. In every 5 seconds it prints its PID.

The launcher process is called launch.sh:

#!/bin/bash

handle_chld() {
    local tmp=()
    for((i=0;i<${#pids[@]};++i)); do
        if [ ! -d /proc/${pids[i]} ]; then
            wait ${pids[i]}
            echo "Stopped ${pids[i]}; exit code: $?"
        else tmp+=(${pids[i]})
        fi
    done
    pids=(${tmp[@]})
}

set -o monitor
trap "handle_chld" CHLD

# Start background processes
./loop.sh 3 &
pids+=($!)
./loop.sh 2 &
pids+=($!)
./loop.sh -x &
pids+=($!)

# Wait until all background processes are stopped
while [ ${#pids[@]} -gt 0 ]; do echo "WAITING FOR: ${pids[@]}"; sleep 2; done
echo STOPPED

For more explanation see: Starting a process from bash script failed

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

How to upsert (update or insert) in SQL Server 2005

You can use @@ROWCOUNT to check whether row should be inserted or updated:

update table1 
set name = 'val2', itemname = 'val3', itemcatName = 'val4', itemQty = 'val5'
where id = 'val1'
if @@ROWCOUNT = 0
insert into table1(id, name, itemname, itemcatName, itemQty)
values('val1', 'val2', 'val3', 'val4', 'val5')

in this case if update fails, the new row will be inserted

How to use particular CSS styles based on screen size / device

Use @media queries. They serve this exact purpose. Here's an example how they work:

@media (max-width: 800px) {
  /* CSS that should be displayed if width is equal to or less than 800px goes here */
}

This would work only on devices whose width is equal to or less than 800px.

Read up more about media queries on the Mozilla Developer Network.

Copy a variable's value into another

Most of the answers here are using built-in methods or using libraries/frameworks. This simple method should work fine:

function copy(x) {
    return JSON.parse( JSON.stringify(x) );
}

// Usage
var a = 'some';
var b = copy(a);
a += 'thing';

console.log(b); // "some"

var c = { x: 1 };
var d = copy(c);
c.x = 2;

console.log(d); // { x: 1 }

TypeError: Converting circular structure to JSON in nodejs

JSON doesn't accept circular objects - objects which reference themselves. JSON.stringify() will throw an error if it comes across one of these.

The request (req) object is circular by nature - Node does that.

In this case, because you just need to log it to the console, you can use the console's native stringifying and avoid using JSON:

console.log("Request data:");
console.log(req);

Automatic login script for a website on windows machine?

I used @qwertyjones's answer to automate logging into Oracle Agile with a public password.

I saved the login page as index.html, edited all the href= and action= fields to have the full URL to the Agile server.

The key <form> line needed to change from

<form autocomplete="off" name="MainForm" method="POST"
 action="j_security_check" 
 onsubmit="return false;" target="_top">

to

<form autocomplete="off" name="MainForm" method="POST"
 action="http://my.company.com:7001/Agile/default/j_security_check"   
 onsubmit="return false;" target="_top">

I also added this snippet to the end of the <body>

<script>
function checkCookiesEnabled(){ return true; }
document.MainForm.j_username.value = "joeuser";
document.MainForm.j_password.value = "abcdef";
submitLoginForm();
</script> 

I had to disable the cookie check by redefining the function that did the check, because I was hosting this from XAMPP and I didn't want to deal with it. The submitLoginForm() call was inspired by inspecting the keyPressEvent() function.

Making an API call in Python with an API that requires a bearer token

Here is full example of implementation in cURL and in Python - for authorization and for making API calls

cURL

1. Authorization

You have received access data like this:

Username: johndoe

Password: zznAQOoWyj8uuAgq

Consumer Key: ggczWttBWlTjXCEtk3Yie_WJGEIa

Consumer Secret: uuzPjjJykiuuLfHkfgSdXLV98Ciga

Which you can call in cURL like this:

curl -k -d "grant_type=password&username=Username&password=Password" \

                    -H "Authorization: Basic Base64(consumer-key:consumer-secret)" \

                       https://somedomain.test.com/token

or for this case it would be:

curl -k -d "grant_type=password&username=johndoe&password=zznAQOoWyj8uuAgq" \

                    -H "Authorization: Basic zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh" \

                      https://somedomain.test.com/token

Answer would be something like:

{
    "access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
    "refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
    "scope": "default",
    "token_type": "Bearer",
    "expires_in": 3600
}

2. Calling API

Here is how you call some API that uses authentication from above. Limit and offset are just examples of 2 parameters that API could implement. You need access_token from above inserted after "Bearer ".So here is how you call some API with authentication data from above:

curl -k -X GET "https://somedomain.test.com/api/Users/Year/2020/Workers?offset=1&limit=100" -H "accept: application/json" -H "Authorization: Bearer zz8d62zz-56zz-34zz-9zzf-azze1b8057f8"

Python

Same thing from above implemented in Python. I've put text in comments so code could be copy-pasted.

# Authorization data

import base64
import requests

username = 'johndoe'
password= 'zznAQOoWyj8uuAgq'
consumer_key = 'ggczWttBWlTjXCEtk3Yie_WJGEIa'
consumer_secret = 'uuzPjjJykiuuLfHkfgSdXLV98Ciga'
consumer_key_secret = consumer_key+":"+consumer_secret
consumer_key_secret_enc = base64.b64encode(consumer_key_secret.encode()).decode()

# Your decoded key will be something like:
#zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh


headersAuth = {
    'Authorization': 'Basic '+ str(consumer_key_secret_enc),
}

data = {
  'grant_type': 'password',
  'username': username,
  'password': password
}

## Authentication request

response = requests.post('https://somedomain.test.com/token', headers=headersAuth, data=data, verify=True)
j = response.json()

# When you print that response you will get dictionary like this:

    {
        "access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
        "refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
        "scope": "default",
        "token_type": "Bearer",
        "expires_in": 3600
    }

# You have to use `access_token` in API calls explained bellow.
# You can get `access_token` with j['access_token'].


# Using authentication to make API calls   

## Define header for making API calls that will hold authentication data

headersAPI = {
    'accept': 'application/json',
    'Authorization': 'Bearer '+j['access_token'],
}

### Usage of parameters defined in your API
params = (
    ('offset', '0'),
    ('limit', '20'),
)

# Making sample API call with authentication and API parameters data

response = requests.get('https://somedomain.test.com/api/Users/Year/2020/Workers', headers=headersAPI, params=params, verify=True)
api_response = response.json()

Setting maxlength of textbox with JavaScript or jQuery

<head>
    <script type="text/javascript">
        function SetMaxLength () {
            var input = document.getElementById ("myInput");
            input.maxLength = 10;
        }
    </script>
</head>
<body>
    <input id="myInput" type="text" size="20" />
</body>

How do you create a yes/no boolean field in SQL server?

You can use the data type bit

Values inserted which are greater than 0 will be stored as '1'

Values inserted which are less than 0 will be stored as '1'

Values inserted as '0' will be stored as '0'

This holds true for MS SQL Server 2012 Express

What is the best way to concatenate two vectors?

If your vectors are sorted*, check out set_union from <algorithm>.

set_union(A.begin(), A.end(), B.begin(), B.end(), AB.begin());

There's a more thorough example in the link

*thanks rlbond

How to perform element-wise multiplication of two lists?

Since you're already using numpy, it makes sense to store your data in a numpy array rather than a list. Once you do this, you get things like element-wise products for free:

In [1]: import numpy as np

In [2]: a = np.array([1,2,3,4])

In [3]: b = np.array([2,3,4,5])

In [4]: a * b
Out[4]: array([ 2,  6, 12, 20])

How to take the nth digit of a number in python

First treat the number like a string

number = 9876543210
number = str(number)

Then to get the first digit:

number[0]

The fourth digit:

number[3]

EDIT:

This will return the digit as a character, not as a number. To convert it back use:

int(number[0])

Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

One workaround is to use Postman with same request url, headers and payload.

It will give response for sure.

How do you search an amazon s3 bucket?

I tried in the following way

aws s3 ls s3://Bucket1/folder1/2019/ --recursive |grep filename.csv

This outputs the actual path where the file exists

2019-04-05 01:18:35     111111 folder1/2019/03/20/filename.csv

Update Git branches from master

You have basically two options:

  1. You merge. That is actually quite simple, and a perfectly local operation:

    git checkout b1
    git merge master
    # repeat for b2 and b3
    

    This leaves the history exactly as it happened: You forked from master, you made changes to all branches, and finally you incorporated the changes from master into all three branches.

    git can handle this situation really well, it is designed for merges happening in all directions, at the same time. You can trust it be able to get all threads together correctly. It simply does not care whether branch b1 merges master, or master merges b1, the merge commit looks all the same to git. The only difference is, which branch ends up pointing to this merge commit.

  2. You rebase. People with an SVN, or similar background find this more intuitive. The commands are analogue to the merge case:

    git checkout b1
    git rebase master
    # repeat for b2 and b3
    

    People like this approach because it retains a linear history in all branches. However, this linear history is a lie, and you should be aware that it is. Consider this commit graph:

    A --- B --- C --- D <-- master
     \
      \-- E --- F --- G <-- b1
    

    The merge results in the true history:

    A --- B --- C --- D <-- master
     \                 \
      \-- E --- F --- G +-- H <-- b1
    

    The rebase, however, gives you this history:

    A --- B --- C --- D <-- master
                       \
                        \-- E' --- F' --- G' <-- b1
    

    The point is, that the commits E', F', and G' never truly existed, and have likely never been tested. They may not even compile. It is actually quite easy to create nonsensical commits via a rebase, especially when the changes in master are important to the development in b1.

    The consequence of this may be, that you can't distinguish which of the three commits E, F, and G actually introduced a regression, diminishing the value of git bisect.

    I am not saying that you shouldn't use git rebase. It has its uses. But whenever you do use it, you need to be aware of the fact that you are lying about history. And you should at least compile test the new commits.

Session 'app': Error Launching activity

I tried all suggested answers. I found out this is a hardware issue on Android N phone with studio 2.3 version. App launches fine on phones below version 7.

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

$http get parameters does not work

The 2nd parameter in the get call is a config object. You want something like this:

$http
    .get('accept.php', {
        params: {
            source: link,
            category_id: category
        }
     })
     .success(function (data,status) {
          $scope.info_show = data
     });

See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail

Java: Convert a String (representing an IP) to InetAddress

From the documentation of InetAddress.getByName(String host):

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

So you can use it.

Writing a string to a cell in excel

try this instead

Set TxtRng = ActiveWorkbook.Sheets("Game").Range("A1")

ADDITION

Maybe the file is corrupt - this has happened to me several times before and the only solution is to copy everything out into a new file.

Please can you try the following:

  • Save a new xlsm file and call it "MyFullyQualified.xlsm"
  • Add a sheet with no protection and call it "mySheet"
  • Add a module to the workbook and add the following procedure

Does this run?

 Sub varchanger()

 With Excel.Application
    .ScreenUpdating = True
    .Calculation = Excel.xlCalculationAutomatic
    .EnableEvents = True
 End With

 On Error GoTo Whoa:

    Dim myBook As Excel.Workbook
    Dim mySheet As Excel.Worksheet
    Dim Rng  As Excel.Range

    Set myBook = Excel.Workbooks("MyFullyQualified.xlsm")
    Set mySheet = myBook.Worksheets("mySheet")
    Set Rng = mySheet.Range("A1")

    'ActiveSheet.Unprotect


    Rng.Value = "SubTotal"

    Excel.Workbooks("MyFullyQualified.xlsm").Worksheets("mySheet").Range("A1").Value = "Asdf"

LetsContinue:
        Exit Sub
Whoa:
        MsgBox Err.Number
        GoTo LetsContinue

End Sub

Load data from txt with pandas

You can use:

data = pd.read_csv('output_list.txt', sep=" ", header=None)
data.columns = ["a", "b", "c", "etc."]

Add sep=" " in your code, leaving a blank space between the quotes. So pandas can detect spaces between values and sort in columns. Data columns is for naming your columns.

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

Jan 2020 Update

@Flimm has explained all the differences very well. Generally, we want to know the difference between all tools because we want to decide what's best for us. So, the next question would be: which one to use? I suggest you choose one of the two official ways to manage virtual environments:

Styling HTML5 input type number

Also you can replace size attribute by a style attribute:
<input type="number" name="numericInput" style="width: 50px;" min="0" max="18" value="0" />

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

None of these options worked for me, in the end it was;

Test > Test Settings > *.testrunconfig

I had to add a new line

<DeploymentItem filename="packages\Newtonsoft.Json.4.5.8\lib\net40\Newtonsoft.Json.dll" />

Make sure the path and version is correct for your setup.

Is it possible to make Font Awesome icons larger than 'fa-5x'?

  1. Just add the font awesome class like this:

    class="fa fa-plus-circle fa-3x"
    

    (You can increase the size as per 5x, 7x, 9x..)

  2. You can also add custom CSS.

How to pass all arguments passed to my bash script to a function of mine?

Use the $@ variable, which expands to all command-line parameters separated by spaces.

abc "$@"

Android camera intent

private static final int TAKE_PICTURE = 1;    
private Uri imageUri;

public void takePhoto(View view) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(photo));
    imageUri = Uri.fromFile(photo);
    startActivityForResult(intent, TAKE_PICTURE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case TAKE_PICTURE:
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImage = imageUri;
            getContentResolver().notifyChange(selectedImage, null);
            ImageView imageView = (ImageView) findViewById(R.id.ImageView);
            ContentResolver cr = getContentResolver();
            Bitmap bitmap;
            try {
                 bitmap = android.provider.MediaStore.Images.Media
                 .getBitmap(cr, selectedImage);

                imageView.setImageBitmap(bitmap);
                Toast.makeText(this, selectedImage.toString(),
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                        .show();
                Log.e("Camera", e.toString());
            }
        }
    }
}

Bind failed: Address already in use

The error usually means that the port you are trying to open is being already used by another application. Try using netstat to see which ports are open and then use an available port.

Also check if you are binding to the right ip address (I am assuming it would be localhost)

Getting a list item by index

you can use index to access list elements

List<string> list1 = new List<string>();
list1[0] //for getting the first element of the list

How to convert a full date to a short date in javascript?

Here you go:

(new Date()).toLocaleDateString('en-US');

That's it !!

you can use it on any date object

let's say.. you have an object called "currentDate"

var currentDate = new Date(); //use your date here
currentDate.toLocaleDateString('en-US'); // "en-US" gives date in US Format - mm/dd/yy

(or)

If you want it in local format then

currentDate.toLocaleDateString(); // gives date in local Format

When should null values of Boolean be used?

For all the good answers above, I'm just going to give a concrete example in Java servlet HttpSession class. Hope this example helps to clarify some question you may still have.

If you need to store and retrieve values for a session, you use setAttribute(String, Object), and getAttribute(String, Object) method. So for a boolean value, you are forced to use the Boolean class if you want to store it in an http session.

HttpSession sess = request.getSession(false);
Boolean isAdmin = (Boolean) sess.getAttribute("admin");
if (! isAdmin) ...

The last line will cause a NullPointerException if the attribute values is not set. (which is the reason led me to this post). So the 3 logic state is here to stay, whether you prefer to use it or not.

What are DDL and DML?

DDL stands for Data Definition Language. DDL is used for defining structure of the table such as create a table or adding a column to table and even drop and truncate table. DML stands for Data Manipulation Language. As the name suggest DML used for manipulating the data of table. There are some commands in DML such as insert and delete.

What is the most effective way to get the index of an iterator of an std::vector?

According to http://www.cplusplus.com/reference/std/iterator/distance/, since vec.begin() is a random access iterator, the distance method uses the - operator.

So the answer is, from a performance point of view, it is the same, but maybe using distance() is easier to understand if anybody would have to read and understand your code.

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

Have you tried using:

(status,output) = commands.getstatusoutput("ps aux")

I thought this had fixed the exact same problem for me. But then my process ended up getting killed instead of failing to spawn, which is even worse..

After some testing I found that this only occurred on older versions of python: it happens with 2.6.5 but not with 2.7.2

My search had led me here python-close_fds-issue, but unsetting closed_fds had not solved the issue. It is still well worth a read.

I found that python was leaking file descriptors by just keeping an eye on it:

watch "ls /proc/$PYTHONPID/fd | wc -l"

Like you, I do want to capture the command's output, and I do want to avoid OOM errors... but it looks like the only way is for people to use a less buggy version of Python. Not ideal...

Converting between datetime, Timestamp and datetime64

This post has been up for 4 years and I still struggled with this conversion problem - so the issue is still active in 2017 in some sense. I was somewhat shocked that the numpy documentation does not readily offer a simple conversion algorithm but that's another story.

I have come across another way to do the conversion that only involves modules numpy and datetime, it does not require pandas to be imported which seems to me to be a lot of code to import for such a simple conversion. I noticed that datetime64.astype(datetime.datetime) will return a datetime.datetime object if the original datetime64 is in micro-second units while other units return an integer timestamp. I use module xarray for data I/O from Netcdf files which uses the datetime64 in nanosecond units making the conversion fail unless you first convert to micro-second units. Here is the example conversion code,

import numpy as np
import datetime

def convert_datetime64_to_datetime( usert: np.datetime64 )->datetime.datetime:
    t = np.datetime64( usert, 'us').astype(datetime.datetime)
return t

Its only tested on my machine, which is Python 3.6 with a recent 2017 Anaconda distribution. I have only looked at scalar conversion and have not checked array based conversions although I'm guessing it will be good. Nor have I looked at the numpy datetime64 source code to see if the operation makes sense or not.

Android Studio with Google Play Services

Open your project build.gradle file and add below line under dependencies module.

dependencies {
    compile 'com.google.android.gms:play-services:7.0.0'
}

The below will be add Google Analytics and Maps if you don't want to integrate full library

dependencies {
    compile 'com.google.android.gms:play-services-analytics:7.0.0'
    compile 'com.google.android.gms:play-services-maps:7.0.0'
}

Is there any native DLL export functions viewer?

DLL Export Viewer by NirSoft can be used to display exported functions in a DLL.

This utility displays the list of all exported functions and their virtual memory addresses for the specified DLL files. You can easily copy the memory address of the desired function, paste it into your debugger, and set a breakpoint for this memory address. When this function is called, the debugger will stop in the beginning of this function.

enter image description here

How can I get last characters of a string

To get the last character of a string, you can use the split('').pop() function.

const myText = "The last character is J";
const lastCharater = myText.split('').pop();
console.log(lastCharater); // J

It's works because when the split('') function has empty('') as parameter, then each character of the string is changed to an element of an array. Thereby we can use the pop() function which returns the last element of that array, which is, the 'J' character.

Can Json.NET serialize / deserialize to / from a stream?

UPDATE: This no longer works in the current version, see below for correct answer (no need to vote down, this is correct on older versions).

Use the JsonTextReader class with a StreamReader or use the JsonSerializer overload that takes a StreamReader directly:

var serializer = new JsonSerializer();
serializer.Deserialize(streamReader);

Create autoincrement key in Java DB using NetBeans IDE

I couldn't get the accepted answer to work using the Netbeans IDE "Create Table" GUI, and I'm on Netbeans 8.2. To get it to working, create the id column with the following options e.g.

enter image description here

and then use 'New Entity Classes from Database' option to generate the entity for the table (I created a simple table called PERSON with an ID column created exactly as above and a NAME column which is simple varchar(255) column). These generated entities leave it to the user to add the auto generated id mechanism.

GENERATION.AUTO seems to try and use sequences which Derby doesn't seem to like (error stating failed to generate sequence/sequence does not exist), GENERATION.SEQUENCE therefore doesn't work either, GENERATION.IDENTITY doesn't work (get error stating ID is null), so that leaves GENERATION.TABLE.

Set your persistence unit's 'Table Generation Strategy' button to Create. This will create tables that don't exist in the DB when your jar is run (loaded?) i.e. the table your PU needs to create in order to store ID increments. In your entity replace the generated annotations above your id field with the following...

enter image description here

I also created a controller for my entity class using 'JPA Controller Classes from Entity Classes' option. I then create a simple main class to test the id was auto generated i.e.

enter image description here

The result is that the PERSON_ID_TABLE is generated correctly and my PERSON table has two PERSON entries in it with correct, auto generated ids.

Laravel Pagination links not including other GET parameters

Include This In Your View Page

 $users->appends(Input::except('page'))

What's the best way to detect a 'touch screen' device using JavaScript?

Although it's only in alpha, the jquery mobile framework is worth checking out. It will normalize these types of events across mobile browsers. Perhaps see what they're doing. I'm assuming jquery-mobile.js is something different than this framework.

How to have multiple conditions for one if statement in python

Darian Moody has a nice solution to this challenge in his blog post:

a = 1
b = 2
c = True

rules = [a == 1,
         b == 2,
         c == True]

if all(rules):
    print("Success!")

The all() method returns True when all elements in the given iterable are true. If not, it returns False.

You can read a little more about it in the python docs here and more information and examples here.

(I also answered the similar question with this info here - How to have multiple conditions for one if statement in python)

Retrieving values from nested JSON Object

Maybe you're not using the latest version of a JSON for Java Library.

json-simple has not been updated for a long time, while JSON-Java was updated 2 month ago.

JSON-Java can be found on GitHub, here is the link to its repo: https://github.com/douglascrockford/JSON-java

After switching the library, you can refer to my sample code down below:

public static void main(String[] args) {
    String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";

    JSONObject jsonObject = new JSONObject(JSON);
    JSONObject getSth = jsonObject.getJSONObject("LanguageLevels");
    Object level = getSth.get("2");

    System.out.println(level);
}

And as JSON-Java open-sourced, you can read the code and its document, they will guide you through.

Hope that it helps.

Change all files and folders permissions of a directory to 644/755

This worked for me:

find /A -type d -exec chmod 0755 {} \;
find /A -type f -exec chmod 0644 {} \;

How to resume Fragment from BackStack if exists

I think this method my solve your problem:

public static void attachFragment ( int fragmentHolderLayoutId, Fragment fragment, Context context, String tag ) {


    FragmentManager manager = ( (AppCompatActivity) context ).getSupportFragmentManager ();
    FragmentTransaction ft = manager.beginTransaction ();

    if (manager.findFragmentByTag ( tag ) == null) { // No fragment in backStack with same tag..
        ft.add ( fragmentHolderLayoutId, fragment, tag );
        ft.addToBackStack ( tag );
        ft.commit ();
    }
    else {
        ft.show ( manager.findFragmentByTag ( tag ) ).commit ();
    }
}

which was originally posted in This Question

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

Asp.net - Add blank item at top of dropdownlist

You could also have a union of the blank select with the select that has content:

select '' value, '' name
union
select value, name from mytable

pull out p-values and r-squared from a linear regression

Use:

(summary(fit))$coefficients[***num***,4]

where num is a number which denotes the row of the coefficients matrix. It will depend on how many features you have in your model and which one you want to pull out the p-value for. For example, if you have only one variable there will be one p-value for the intercept which will be [1,4] and the next one for your actual variable which will be [2,4]. So your num will be 2.

How to get a JavaScript object's class?

In javascript, there are no classes, but I think that you want the constructor name and obj.constructor.toString() will tell you what you need.

WebView and Cookies on Android

From the Android documentation:

The CookieSyncManager is used to synchronize the browser cookie store between RAM and permanent storage. To get the best performance, browser cookies are saved in RAM. A separate thread saves the cookies between, driven by a timer.

To use the CookieSyncManager, the host application has to call the following when the application starts:

CookieSyncManager.createInstance(context)

To set up for sync, the host application has to call

CookieSyncManager.getInstance().startSync()

in Activity.onResume(), and call

 CookieSyncManager.getInstance().stopSync()

in Activity.onPause().

To get instant sync instead of waiting for the timer to trigger, the host can call

CookieSyncManager.getInstance().sync()

The sync interval is 5 minutes, so you will want to force syncs manually anyway, for instance in onPageFinished(WebView, String). Note that even sync() happens asynchronously, so don't do it just as your activity is shutting down.

Finally something like this should work:

// use cookies to remember a logged in status   
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
setContentView(webview);      
webview.loadUrl([MY URL]);

How to select data from 30 days?

For those who could not get DATEADD to work, try this instead: ( NOW( ) - INTERVAL 1 MONTH )

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

Simply difference between Forward(ServletRequest request, ServletResponse response) and sendRedirect(String url) is

forward():

  1. The forward() method is executed in the server side.
  2. The request is transfer to other resource within same server.
  3. It does not depend on the client’s request protocol since the forward () method is provided by the servlet container.
  4. The request is shared by the target resource.
  5. Only one call is consumed in this method.
  6. It can be used within server.
  7. We cannot see forwarded message, it is transparent.
  8. The forward() method is faster than sendRedirect() method.
  9. It is declared in RequestDispatcher interface.

sendRedirect():

  1. The sendRedirect() method is executed in the client side.
  2. The request is transfer to other resource to different server.
  3. The sendRedirect() method is provided under HTTP so it can be used only with HTTP clients.
  4. New request is created for the destination resource.
  5. Two request and response calls are consumed.
  6. It can be used within and outside the server.
  7. We can see redirected address, it is not transparent.
  8. The sendRedirect() method is slower because when new request is created old request object is lost.
  9. It is declared in HttpServletResponse.

T-SQL Cast versus Convert

You should also not use CAST for getting the text of a hash algorithm. CAST(HASHBYTES('...') AS VARCHAR(32)) is not the same as CONVERT(VARCHAR(32), HASHBYTES('...'), 2). Without the last parameter, the result would be the same, but not a readable text. As far as I know, You cannot specify that last parameter in CAST.

MVC 4 @Scripts "does not exist"

Create a new MVC 4 RC internet application and run it. Navigate to Login which uses the same code

 @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

What allows Login.cshtml to work is the the Views\Web.config file (not the app root version) contains

<namespaces>

    <add namespace="System.Web.Optimization"/>

  </namespaces>

Why is your Create view not working and Login is?

How to check if a specified key exists in a given S3 bucket using Java

The right way to do it in SDK V2, without the overload of actually getting the object, is to use S3Client.headObject. Officially backed by AWS Change Log.

Example code:

public boolean exists(String bucket, String key) {
    try {
        HeadObjectResponse headResponse = client
                .headObject(HeadObjectRequest.builder().bucket(bucket).key(key).build());
        return true;
    } catch (NoSuchKeyException e) {
        return false;
    }
}

Android Design Support Library expandable Floating Action Button(FAB) menu

When I tried to create something simillar to inbox floating action button i thought about creating own custom component.

It would be simple frame layout with fixed height (to contain expanded menu) containing FAB button and 3 more placed under the FAB. when you click on FAB you just simply animate other buttons to translate up from under the FAB.

There are some libraries which do that (for example https://github.com/futuresimple/android-floating-action-button), but it's always more fun if you create it by yourself :)

Does MySQL foreign_key_checks affect the entire database?

Actually, there are two foreign_key_checks variables: a global variable and a local (per session) variable. Upon connection, the session variable is initialized to the value of the global variable.
The command SET foreign_key_checks modifies the session variable.
To modify the global variable, use SET GLOBAL foreign_key_checks or SET @@global.foreign_key_checks.

Consult the following manual sections:
http://dev.mysql.com/doc/refman/5.7/en/using-system-variables.html
http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html

Align div with fixed position on the right side

Here's the real solution (with other cool CSS3 stuff):

#fixed-square {
position: fixed;
top: 0;
right: 0;
z-index: 9500;
cursor: pointer;
width: 24px;
padding: 18px 18px 14px;
opacity: 0.618;
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
-webkit-transition: all 0.145s ease-out;
-moz-transition: all 0.145s ease-out;
-ms-transition: all 0.145s ease-out;
transition: all 0.145s ease-out;
}

Note the top:0 and right:0. That's what did it for me.

How do you do a deep copy of an object in .NET?

You can use Nested MemberwiseClone to do a deep copy. Its almost the same speed as copying a value struct, and its an order of magnitude faster than (a) reflection or (b) serialization (as described in other answers on this page).

Note that if you use Nested MemberwiseClone for a deep copy, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code below.

Here is the output of the code showing the relative performance difference (4.77 seconds for deep nested MemberwiseCopy vs. 39.93 seconds for Serialization). Using nested MemberwiseCopy is almost as fast as copying a struct, and copying a struct is pretty darn close to the theoretical maximum speed .NET is capable of, which is probably quite close to the speed of the same thing in C or C++ (but would have to run some equivalent benchmarks to check this claim).

    Demo of shallow and deep copy, using classes and MemberwiseClone:
      Create Bob
        Bob.Age=30, Bob.Purchase.Description=Lamborghini
      Clone Bob >> BobsSon
      Adjust BobsSon details
        BobsSon.Age=2, BobsSon.Purchase.Description=Toy car
      Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:
        Bob.Age=30, Bob.Purchase.Description=Lamborghini
      Elapsed time: 00:00:04.7795670,30000000
    Demo of shallow and deep copy, using structs and value copying:
      Create Bob
        Bob.Age=30, Bob.Purchase.Description=Lamborghini
      Clone Bob >> BobsSon
      Adjust BobsSon details:
        BobsSon.Age=2, BobsSon.Purchase.Description=Toy car
      Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:
        Bob.Age=30, Bob.Purchase.Description=Lamborghini
      Elapsed time: 00:00:01.0875454,30000000
    Demo of deep copy, using class and serialize/deserialize:
      Elapsed time: 00:00:39.9339425,30000000

To understand how to do a deep copy using MemberwiseCopy, here is the demo project:

// Nested MemberwiseClone example. 
// Added to demo how to deep copy a reference class.
[Serializable] // Not required if using MemberwiseClone, only used for speed comparison using serialization.
public class Person
{
    public Person(int age, string description)
    {
        this.Age = age;
        this.Purchase.Description = description;
    }
    [Serializable] // Not required if using MemberwiseClone
    public class PurchaseType
    {
        public string Description;
        public PurchaseType ShallowCopy()
        {
            return (PurchaseType)this.MemberwiseClone();
        }
    }
    public PurchaseType Purchase = new PurchaseType();
    public int Age;
    // Add this if using nested MemberwiseClone.
    // This is a class, which is a reference type, so cloning is more difficult.
    public Person ShallowCopy()
    {
        return (Person)this.MemberwiseClone();
    }
    // Add this if using nested MemberwiseClone.
    // This is a class, which is a reference type, so cloning is more difficult.
    public Person DeepCopy()
    {
            // Clone the root ...
        Person other = (Person) this.MemberwiseClone();
            // ... then clone the nested class.
        other.Purchase = this.Purchase.ShallowCopy();
        return other;
    }
}
// Added to demo how to copy a value struct (this is easy - a deep copy happens by default)
public struct PersonStruct
{
    public PersonStruct(int age, string description)
    {
        this.Age = age;
        this.Purchase.Description = description;
    }
    public struct PurchaseType
    {
        public string Description;
    }
    public PurchaseType Purchase;
    public int Age;
    // This is a struct, which is a value type, so everything is a clone by default.
    public PersonStruct ShallowCopy()
    {
        return (PersonStruct)this;
    }
    // This is a struct, which is a value type, so everything is a clone by default.
    public PersonStruct DeepCopy()
    {
        return (PersonStruct)this;
    }
}
// Added only for a speed comparison.
public class MyDeepCopy
{
    public static T DeepCopy<T>(T obj)
    {
        object result = null;
        using (var ms = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            ms.Position = 0;
            result = (T)formatter.Deserialize(ms);
            ms.Close();
        }
        return (T)result;
    }
}

Then, call the demo from main:

    void MyMain(string[] args)
    {
        {
            Console.Write("Demo of shallow and deep copy, using classes and MemberwiseCopy:\n");
            var Bob = new Person(30, "Lamborghini");
            Console.Write("  Create Bob\n");
            Console.Write("    Bob.Age={0}, Bob.Purchase.Description={1}\n", Bob.Age, Bob.Purchase.Description);
            Console.Write("  Clone Bob >> BobsSon\n");
            var BobsSon = Bob.DeepCopy();
            Console.Write("  Adjust BobsSon details\n");
            BobsSon.Age = 2;
            BobsSon.Purchase.Description = "Toy car";
            Console.Write("    BobsSon.Age={0}, BobsSon.Purchase.Description={1}\n", BobsSon.Age, BobsSon.Purchase.Description);
            Console.Write("  Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n");
            Console.Write("    Bob.Age={0}, Bob.Purchase.Description={1}\n", Bob.Age, Bob.Purchase.Description);
            Debug.Assert(Bob.Age == 30);
            Debug.Assert(Bob.Purchase.Description == "Lamborghini");
            var sw = new Stopwatch();
            sw.Start();
            int total = 0;
            for (int i = 0; i < 100000; i++)
            {
                var n = Bob.DeepCopy();
                total += n.Age;
            }
            Console.Write("  Elapsed time: {0},{1}\n", sw.Elapsed, total);
        }
        {               
            Console.Write("Demo of shallow and deep copy, using structs:\n");
            var Bob = new PersonStruct(30, "Lamborghini");
            Console.Write("  Create Bob\n");
            Console.Write("    Bob.Age={0}, Bob.Purchase.Description={1}\n", Bob.Age, Bob.Purchase.Description);
            Console.Write("  Clone Bob >> BobsSon\n");
            var BobsSon = Bob.DeepCopy();
            Console.Write("  Adjust BobsSon details:\n");
            BobsSon.Age = 2;
            BobsSon.Purchase.Description = "Toy car";
            Console.Write("    BobsSon.Age={0}, BobsSon.Purchase.Description={1}\n", BobsSon.Age, BobsSon.Purchase.Description);
            Console.Write("  Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n");
            Console.Write("    Bob.Age={0}, Bob.Purchase.Description={1}\n", Bob.Age, Bob.Purchase.Description);                
            Debug.Assert(Bob.Age == 30);
            Debug.Assert(Bob.Purchase.Description == "Lamborghini");
            var sw = new Stopwatch();
            sw.Start();
            int total = 0;
            for (int i = 0; i < 100000; i++)
            {
                var n = Bob.DeepCopy();
                total += n.Age;
            }
            Console.Write("  Elapsed time: {0},{1}\n", sw.Elapsed, total);
        }
        {
            Console.Write("Demo of deep copy, using class and serialize/deserialize:\n");
            int total = 0;
            var sw = new Stopwatch();
            sw.Start();
            var Bob = new Person(30, "Lamborghini");
            for (int i = 0; i < 100000; i++)
            {
                var BobsSon = MyDeepCopy.DeepCopy<Person>(Bob);
                total += BobsSon.Age;
            }
            Console.Write("  Elapsed time: {0},{1}\n", sw.Elapsed, total);
        }
        Console.ReadKey();
    }

Again, note that if you use Nested MemberwiseClone for a deep copy, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code above.

Note that when it comes to cloning an object, there is is a big difference between a "struct" and a "class":

  • If you have a "struct", it's a value type so you can just copy it, and the contents will be cloned.
  • If you have a "class", it's a reference type, so if you copy it, all you are doing is copying the pointer to it. To create a true clone, you have to be more creative, and use a method which creates another copy of the original object in memory.
  • Cloning objects incorrectly can lead to very difficult-to-pin-down bugs. In production code, I tend to implement a checksum to double check that the object has been cloned properly, and hasn't been corrupted by another reference to it. This checksum can be switched off in Release mode.
  • I find this method quite useful: often, you only want to clone parts of the object, not the entire thing. It's also essential for any use case where you are modifying objects, then feeding the modified copies into a queue.

Update

It's probably possible to use reflection to recursively walk through the object graph to do a deep copy. WCF uses this technique to serialize an object, including all of its children. The trick is to annotate all of the child objects with an attribute that makes it discoverable. You might lose some performance benefits, however.

Update

Quote on independent speed test (see comments below):

I've run my own speed test using Neil's serialize/deserialize extension method, Contango's Nested MemberwiseClone, Alex Burtsev's reflection-based extension method and AutoMapper, 1 million times each. Serialize-deserialize was slowest, taking 15.7 seconds. Then came AutoMapper, taking 10.1 seconds. Much faster was the reflection-based method which took 2.4 seconds. By far the fastest was Nested MemberwiseClone, taking 0.1 seconds. Comes down to performance versus hassle of adding code to each class to clone it. If performance isn't an issue go with Alex Burtsev's method. – Simon Tewsi

What is exactly the base pointer and stack pointer? To what do they point?

EDIT: For a better description, see x86 Disassembly/Functions and Stack Frames in a WikiBook about x86 assembly. I try to add some info you might be interested in using Visual Studio.

Storing the caller EBP as the first local variable is called a standard stack frame, and this may be used for nearly all calling conventions on Windows. Differences exist whether the caller or callee deallocates the passed parameters, and which parameters are passed in registers, but these are orthogonal to the standard stack frame problem.

Speaking about Windows programs, you might probably use Visual Studio to compile your C++ code. Be aware that Microsoft uses an optimization called Frame Pointer Omission, that makes it nearly impossible to do walk the stack without using the dbghlp library and the PDB file for the executable.

This Frame Pointer Omission means that the compiler does not store the old EBP on a standard place and uses the EBP register for something else, therefore you have hard time finding the caller EIP without knowing how much space the local variables need for a given function. Of course Microsoft provides an API that allows you to do stack-walks even in this case, but looking up the symbol table database in PDB files takes too long for some use cases.

To avoid FPO in your compilation units, you need to avoid using /O2 or need to explicitly add /Oy- to the C++ compilation flags in your projects. You probably link against the C or C++ runtime, which uses FPO in the Release configuration, so you will have hard time to do stack walks without the dbghlp.dll.

How to use NULL or empty string in SQL

SELECT * FROM DBO.AGENDA
WHERE 
  --IF @DT_START IS NULL OR EMPTY
  ( ISNULL( @DT_START,'' ) = '' AND DT_START IS NOT NULL ) -- GET ALL DATE
  OR --ELSE
  ( DT_START >= @DT_START ) --FILTER

-- MORE FILTER

SELECT * FROM DBO.AGENDA
WHERE 
  ( ( ISNULL( @DT_START,'' ) = '' AND DT_START IS NOT NULL ) OR ( DT_START >= @DT_START ) ) 
  AND
  DT_END < GETDATE()

Why is a "GRANT USAGE" created the first time I grant a user privileges?

In addition mysql passwords when not using the IDENTIFIED BY clause, may be blank values, if non-blank, they may be encrypted. But yes USAGE is used to modify an account by granting simple resource limiters such as MAX_QUERIES_PER_HOUR, again this can be specified by also using the WITH clause, in conjuction with GRANT USAGE(no privileges added) or GRANT ALL, you can also specify GRANT USAGE at the global level, database level, table level,etc....

Can media queries resize based on a div element instead of the screen?

The only way I can think that you can accomplish what you want purely with css, is to use a fluid container for your widget. If your container's width is a percentage of the screen then you can use media queries to style depending on your container's width, as you will now know for each screen's dimensions what is your container's dimensions. For example, let's say you decide to make your container's 50% of the screen width. Then for a screen width of 1200px you know that your container is 600px

.myContainer {
  width: 50%;
}

/* you know know that your container is 600px 
 * so you style accordingly
*/
@media (max-width: 1200px) { 
  /* your css for 600px container */
}

How to make a simple modal pop up form using jquery and html?

I came across this question when I was trying similar things.

A very nice and simple sample is presented at w3schools website.

https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title>Bootstrap Example</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <h2>Modal Example</h2>_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        </div>_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Find the version of an installed npm package

If you'd like to check for a particular module installed globally, on *nix systems use:

npm list -g --depth=0 | grep <module_name>

Javascript one line If...else...else if statement

Sure, you can do nested ternary operators but they are hard to read.

var variable = (condition) ? (true block) : ((condition2) ? (true block2) : (else block2))

How can I force clients to refresh JavaScript files?

My colleague just found a reference to that method right after I posted (in reference to css) at http://www.stefanhayden.com/blog/2006/04/03/css-caching-hack/. Good to see that others are using it and it seems to work. I assume at this point that there isn't a better way than find-replace to increment these "version numbers" in all of the script tags?

How do I delay a function call for 5 seconds?

var rotator = function(){
  widget.Rotator.rotate();
  setTimeout(rotator,5000);
};
rotator();

Or:

setInterval(
  function(){ widget.Rotator.rotate() },
  5000
);

Or:

setInterval(
  widget.Rotator.rotate.bind(widget.Rotator),
  5000
);

How to find the 'sizeof' (a pointer pointing to an array)?

For this specific example, yes, there is, IF you use typedefs (see below). Of course, if you do it this way, you're just as well off to use SIZEOF_DAYS, since you know what the pointer is pointing to.

If you have a (void *) pointer, as is returned by malloc() or the like, then, no, there is no way to determine what data structure the pointer is pointing to and thus, no way to determine its size.

#include <stdio.h>

#define NUM_DAYS 5
typedef int days_t[ NUM_DAYS ];
#define SIZEOF_DAYS ( sizeof( days_t ) )

int main() {
    days_t  days;
    days_t *ptr = &days; 

    printf( "SIZEOF_DAYS:  %u\n", SIZEOF_DAYS  );
    printf( "sizeof(days): %u\n", sizeof(days) );
    printf( "sizeof(*ptr): %u\n", sizeof(*ptr) );
    printf( "sizeof(ptr):  %u\n", sizeof(ptr)  );

    return 0;
} 

Output:

SIZEOF_DAYS:  20
sizeof(days): 20
sizeof(*ptr): 20
sizeof(ptr):  4