Programs & Examples On #Hackage

Hackage is the central package archive for open-source software in the Haskell programming language.

Saving binary data as file using JavaScript from a browser

Use FileSaver.js. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it:
     https://github.com/eligrey/FileSaver.js

Minified version is really small at < 2.5KB, gzipped < 1.2KB.

Usage:

/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);

You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
     https://github.com/eligrey/Blob.js

Consider StreamSaver.js if you have files larger than blob's size limitations.

Complete example:

_x000D_
_x000D_
/* Two options_x000D_
 * 1. Get FileSaver.js from here_x000D_
 *     https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
 *     <script src="FileSaver.min.js" />_x000D_
 *_x000D_
 * Or_x000D_
 *_x000D_
 * 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
 *    then a simple implementation of saveAs function can be:_x000D_
 */_x000D_
function saveAs(blob, fileName) {_x000D_
    var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
    var anchorElem = document.createElement("a");_x000D_
    anchorElem.style = "display: none";_x000D_
    anchorElem.href = url;_x000D_
    anchorElem.download = fileName;_x000D_
_x000D_
    document.body.appendChild(anchorElem);_x000D_
    anchorElem.click();_x000D_
_x000D_
    document.body.removeChild(anchorElem);_x000D_
_x000D_
    // On Edge, revokeObjectURL should be called only after_x000D_
    // a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
    setTimeout(function() {_x000D_
        window.URL.revokeObjectURL(url);_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
    // convert base64 string to byte array_x000D_
    var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
    var byteNumbers = new Array(byteCharacters.length);_x000D_
    for (var i = 0; i < byteCharacters.length; i++) {_x000D_
        byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
    }_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
    _x000D_
    // now that we have the byte array, construct the blob from it_x000D_
    var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
    var fileName1 = "cool.gif";_x000D_
    saveAs(blob1, fileName1);_x000D_
_x000D_
    // saving text file_x000D_
    var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
    var fileName2 = "cool.txt";_x000D_
    saveAs(blob2, fileName2);_x000D_
})();
_x000D_
_x000D_
_x000D_


Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js for supporting IE 11).
You can also save from a canvas element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.

Demos: https://eligrey.com/demos/FileSaver.js/

Blog post by author of FileSaver.js: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side

Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers

Note 2: Failed to execute 'atob' on 'Window'

Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
                See http://caniuse.com/#search=blob

Note 4: IE < 10 support (I've not tested this part):
                https://github.com/eligrey/FileSaver.js#ie--10
                https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476

Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html

Note 5: Creating a BLOB from a Base64 string in JavaScript

Note 6: FileSaver.js examples: https://github.com/eligrey/FileSaver.js#examples

SQL Error: ORA-12899: value too large for column

ORA-12899: value too large for column "DJ"."CUSTOMERS"."ADDRESS" (actual: 25, maximum: 2

Tells you what the error is. Address can hold maximum of 20 characters, you are passing 25 characters.

Batch file script to zip files

You're near :)

First, the batch (%%variable) and Windows CMD (%variable) uses different variable naming. Second, i dont figure out how do you use zip from CMD. This is from Linux users i think. Use built-in zip manipulation is not like easy on Win, and even harder with batch scripting.

But you're lucky anyway. I got (extracted to target folder) zip.exe and cygwin1.dll from the cygwin package (3mb filesize both together) and start play with it right now.

Of course, i use CMD for better/faster testing instead batch. Only remember modify the %varname to %%varname before blame me :P

for /d %d in (*) do zip -r %d %d

Explanation: for /d ... that matches any folder inside. Only folder ignoring files. (use for /f to filesmatch) for /d %d in ... the %d tells cmd wich name do you wanna assign to your variable. I put d to match widh d (directory meaning). for /d %d in (*) ... Very important. That suposses that I CD to desired folder, or run from. (*) this will mean all on THIS dir, because we use /d the files are not processed so no need to set a pattern, even if you can get only some folders if you need. You can use absolute paths. Not sure about issues with relatives from batch. for /d %d in (*) do zip -r ... Do ZIP is obvious. (exec zip itself and see the help display to use your custom rules). r- is for recursive, so anyting will be added. for /d %d in (*) do zip -r %d %d The first %d is the zip name. You can try with myzip.zip, but if will fail because if you have 2 or more folders the second cannot gave the name of the first and will not try to overwrite without more params. So, we pass %d to both, wich is the current for iteration folder name zipped into a file with the folder name. Is not neccesary to append ".zip" to name.

Is pretty short than i expected when start to play with.

Delete a database in phpMyAdmin

If you want to delete your database from phpmyAdmin or mySQl. Simply go to SQL command and write command "drop DATABASE databasename;"

Example: drop DATABASE rainbowonlineshopping;

enter image description here

Then click on "Go" Button. Your Database will be deleted and you get information like this

enter image description here

How to detect a route change in Angular?

The answers here are correct for router-deprecated. For the latest version of router:

this.router.changes.forEach(() => {
    // Do whatever in here
});

or

this.router.changes.subscribe(() => {
     // Do whatever in here
});

To see the difference between the two, please check out this SO question.

Edit

For the latest you must do:

this.router.events.subscribe(event: Event => {
    // Handle route change
});

Declaring an unsigned int in Java

For unsigned numbers you can use these classes from Guava library:

They support various operations:

  • plus
  • minus
  • times
  • mod
  • dividedBy

The thing that seems missing at the moment are byte shift operators. If you need those you can use BigInteger from Java.

Change the location of the ~ directory in a Windows install of Git Bash

In my case, all I had to do was add the following User variable on Windows:

Variable name: HOME
Variable value: %USERPROFILE%

How to set a Environment Variable (You can use the User variables for username section if you are not a system administrator)

What's the best mock framework for Java?

The best solution to mocking is to have the machine do all the work with automated specification-based testing. For Java, see ScalaCheck and the Reductio framework included in the Functional Java library. With automated specification-based testing frameworks, you supply a specification of the method under test (a property about it that should be true) and the framework generates tests as well as mock objects, automatically.

For example, the following property tests the Math.sqrt method to see if the square root of any positive number n squared is equal to n.

val propSqrt = forAll { (n: Int) => (n >= 0) ==> scala.Math.sqrt(n*n) == n }

When you call propSqrt.check(), ScalaCheck generates hundreds of integers and checks your property for each, also automatically making sure that the edge cases are covered well.

Even though ScalaCheck is written in Scala, and requires the Scala Compiler, it's easy to test Java code with it. The Reductio framework in Functional Java is a pure Java implementation of the same concepts.

how to change the default positioning of modal in bootstrap?

Add the following css to your html and try changing the top, right, bottom, left values.

.modal {
   position: absolute;
   top: 10px;
   right: 100px;
   bottom: 0;
   left: 0;
   z-index: 10040;
   overflow: auto;
   overflow-y: auto;
}

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

How to detect if a browser is Chrome using jQuery?

Although it is not Jquery , I use jquery myself but for browser detection I have used the script on this page a few times. It detects all major browsers, and then some. The work is pretty much all done for you.

Bootstrap col-md-offset-* not working

Bootstrap 4 offset classes have been removed in Beta 1, but will be restored in Beta 2 - topic reference

Changing git commit message after push (given that no one pulled from remote)

If you want to modify an older commit, not the last one, you will need to use rebase command as explained in here,Github help page , on the Amending the message of older or multiple commit messages section

PHP - Session destroy after closing browser

If you are confused what to do, just refer to the manual of session_destroy() function:

http://php.net/manual/en/function.session-destroy.php

There you can find some more features of session_destroy().

How to set button click effect in Android?

Use RippleDrawable for Material Design state pressed/clicked effect.

In order to achieve this, create ripple item as an .xml under /drawable folder and use it in android:background for any views.

  • Effect for icon pressed/clicked, use circular ripple effect, for example:

    <ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@android:color/darker_gray" />

  • Effect for view clicked with rectangle boundary, we can add ripple over the existing drawable like bellow:

    <?xml version="1.0" encoding="utf-8"?> <ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="#000000"> <item android:drawable="@drawable/your_background_drawable"/> </ripple>

How do I iterate over a range of numbers defined by variables in Bash?

This works fine in bash:

END=5
i=1 ; while [[ $i -le $END ]] ; do
    echo $i
    ((i = i + 1))
done

Python socket receive - incoming packets always have a different size

That's the nature of TCP: the protocol fills up packets (lower layer being IP packets) and sends them. You can have some degree of control over the MTU (Maximum Transfer Unit).

In other words: you must devise a protocol that rides on top of TCP where your "payload delineation" is defined. By "payload delineation" I mean the way you extract the unit of message your protocol supports. This can be as simple as "every NULL terminated strings".

postgres: upgrade a user to be a superuser?

$ su - postgres
$ psql
$ \du; for see the user on db
select the user that do you want be superuser and:
$ ALTER USER "user" with superuser;

Outlets cannot be connected to repeating content iOS

For collectionView :

solution:

From viewcontroller, kindly remove the IBoutlet of colllectionviewcell

. the issue mentions the invalid of your IBOutlet. so remove all subclass which has multi-outlet(invalids) and reconnect it.

The answer is already mentioned in another question for collectionviewcell

Is < faster than <=?

Maybe the author of that unnamed book has read that a > 0 runs faster than a >= 1 and thinks that is true universally.

But it is because a 0 is involved (because CMP can, depending on the architecture, replaced e.g. with OR) and not because of the <.

Finding the next available id in MySQL

One way to do it is to set the index to be auto incrementing. Then your SQL statement simply specifies NULL and then SQL parser does the rest for you.

INSERT INTO foo VALUES (null);

How to work with string fields in a C struct?

I think this solution uses less code and is easy to understand even for newbie.

For string field in struct, you can use pointer and reassigning the string to that pointer will be straightforward and simpler.

Define definition of struct:

typedef struct {
  int number;
  char *name;
  char *address;
  char *birthdate;
  char gender;
} Patient;

Initialize variable with type of that struct:

Patient patient;
patient.number = 12345;
patient.address = "123/123 some road Rd.";
patient.birthdate = "2020/12/12";
patient.gender = "M";

It is that simple. Hope this answer helps many developers.

Print "\n" or newline characters as part of the output on terminal

Another suggestion is to do that way:

string = "abcd\n"
print(string.replace("\n","\\n"))

But be aware that the print function actually print to the terminal the "\n", your terminal interpret that as a newline, that's it. So, my solution just change the newline in \ + n

How to select all checkboxes with jQuery?

$('.checkall').change(function() {
    var checkboxes = $(this).closest('table').find('td').find(':checkbox');
    if($(this).is(':checked')) {
        checkboxes.attr('checked', 'checked');
    } else {
        checkboxes.removeAttr('checked');
    }
});

Errors: Data path ".builders['app-shell']" should have required property 'class'

Your @angular-devkit is incompatible with @angular/cli version, so just install older one like this for example:

npm install @angular-devkit/[email protected] @angular-devkit/[email protected]

Currently running queries in SQL Server

The tool is called the SQL Server Profiler, it's still part of the standard toolset.

Best way to serialize/unserialize objects in JavaScript?

JSON has no functions as data types. You can only serialize strings, numbers, objects, arrays, and booleans (and null)

You could create your own toJson method, only passing the data that really has to be serialized:

Person.prototype.toJson = function() {
    return JSON.stringify({age: this.age});
};

Similar for deserializing:

Person.fromJson = function(json) {
    var data = JSON.parse(json); // Parsing the json string.
    return new Person(data.age);
};

The usage would be:

var serialize = p1.toJson();
var _p1 = Person.fromJson(serialize);
alert("Is old: " + _p1.isOld());

To reduce the amount of work, you could consider to store all the data that needs to be serialized in a special "data" property for each Person instance. For example:

function Person(age) {
    this.data = {
        age: age
    };
    this.isOld = function (){
        return this.data.age > 60 ? true : false;
    }
}

then serializing and deserializing is merely calling JSON.stringify(this.data) and setting the data of an instance would be instance.data = JSON.parse(json).

This would keep the toJson and fromJson methods simple but you'd have to adjust your other functions.


Side note:

You should add the isOld method to the prototype of the function:

Person.prototype.isOld = function() {}

Otherwise, every instance has it's own instance of that function which also increases memory.

Loop through all the resources in a .resx file

Simple read loop use this code

var resx = ResourcesName.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, false, false);

foreach (DictionaryEntry dictionaryEntry in resx)
{
    Console.WriteLine("Key: " + dictionaryEntry.Key);
    Console.WriteLine("Val: " + dictionaryEntry.Value);
}

How do I drop a foreign key in SQL Server?

First check of existence of the constraint then drop it.

if exists (select 1 from sys.objects where name = 'Company_CountryID_FK' and type='F')
begin
alter table company drop constraint  Company_CountryID_FK
end

Get current URL with jQuery?

You'll want to use JavaScript's built-in window.location object.

Is it acceptable and safe to run pip install under sudo?

Use a virtual environment:

$ virtualenv myenv
.. some output ..
$ source myenv/bin/activate
(myenv) $ pip install what-i-want

You only use sudo or elevated permissions when you want to install stuff for the global, system-wide Python installation.

It is best to use a virtual environment which isolates packages for you. That way you can play around without polluting the global python install.

As a bonus, virtualenv does not need elevated permissions.

Convert date field into text in Excel

You don't need to convert the original entry - you can use TEXT function in the concatenation formula, e.g. with date in A1 use a formula like this

="Today is "&TEXT(A1,"dd-mm-yyyy")

You can change the "dd-mm-yyyy" part as required

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Since you're using PHP, you will probably need to use the CURLOPT_PORT option, like so:

curl_setopt($ch, CURLOPT_PORT, 11740);

Bear in mind, you may face problems with SELinux:

Unable to make php curl request with port number

How to strip HTML tags with jQuery?

Use the .text() function:

var text = $("<p> example ive got a string</P>").text();

Update: As Brilliand points out below, if the input string does not contain any tags and you are unlucky enough, it might be treated as a CSS selector. So this version is more robust:

var text = $("<div/>").html("<p> example ive got a string</P>").text();

Kill some processes by .exe file name

public void EndTask(string taskname)
{
      string processName = taskname.Replace(".exe", "");

      foreach (Process process in Process.GetProcessesByName(processName))
      {
          process.Kill();
      }
}

//EndTask("notepad");

Summary: no matter if the name contains .exe, the process will end. You don't need to "leave off .exe from process name", It works 100%.

How to len(generator())

You can use reduce.

For Python 3:

>>> import functools
>>> def gen():
...     yield 1
...     yield 2
...     yield 3
...
>>> functools.reduce(lambda x,y: x + 1, gen(), 0)

In Python 2, reduce is in the global namespace so the import is unnecessary.

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

Blank HTML SELECT without blank item in dropdown list

Simply using

<option value="" selected disabled>Please select an option...</option>

will work anywhere without script and allow you to instruct the user at the same time.

How do I embed PHP code in JavaScript?

If your whole JavaScript code gets processed by PHP, then you can do it just like that.

If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.

For example, in your index.php (or wherever you specify your layout), you'd do something like this:

<script type="text/javascript">
    var my_var = <?php echo json_encode($my_var); ?>;
</script>

You could then use my_var in your JavaScript files.

This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.

Elasticsearch: Failed to connect to localhost port 9200 - Connection refused

Change the network.bind to 0.0.0.0 and http:port to 9200. The bind address 0.0.0.0 means all IPv4 addresses on the local machine. If a host has two IP addresses, 192.168.1.1 and 10.1.2.1, and a server running on the host listens on 0.0.0.0, it will be reachable at both of those IPs.

how to make a countdown timer in java

You can create a countdown timer using applet, below is the code,

   import java.applet.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.Timer; // not java.util.Timer
   import java.text.NumberFormat;
   import java.net.*;



/**
    * An applet that counts down from a specified time. When it reaches 00:00,
    * it optionally plays a sound and optionally moves the browser to a new page.
    * Place the mouse over the applet to pause the count; move it off to resume.
    * This class demonstrates most applet methods and features.
    **/

public class Countdown extends JApplet implements ActionListener, MouseListener
{
long remaining; // How many milliseconds remain in the countdown.
long lastUpdate; // When count was last updated
JLabel label; // Displays the count
Timer timer; // Updates the count every second
NumberFormat format; // Format minutes:seconds with leading zeros
Image image; // Image to display along with the time
AudioClip sound; // Sound to play when we reach 00:00

// Called when the applet is first loaded
public void init() {
    // Figure out how long to count for by reading the "minutes" parameter
    // defined in a <param> tag inside the <applet> tag. Convert to ms.
    String minutes = getParameter("minutes");
    if (minutes != null) remaining = Integer.parseInt(minutes) * 60000;
    else remaining = 600000; // 10 minutes by default

    // Create a JLabel to display remaining time, and set some properties.
    label = new JLabel();
    label.setHorizontalAlignment(SwingConstants.CENTER );
    label.setOpaque(true); // So label draws the background color

    // Read some parameters for this JLabel object
    String font = getParameter("font");
    String foreground = getParameter("foreground");
    String background = getParameter("background");
    String imageURL = getParameter("image");

    // Set label properties based on those parameters
    if (font != null) label.setFont(Font.decode(font));
    if (foreground != null) label.setForeground(Color.decode(foreground));
    if (background != null) label.setBackground(Color.decode(background));
    if (imageURL != null) {
        // Load the image, and save it so we can release it later
        image = getImage(getDocumentBase(), imageURL);
        // Now display the image in the JLabel.
        label.setIcon(new ImageIcon(image));
    }

    // Now add the label to the applet. Like JFrame and JDialog, JApplet
    // has a content pane that you add children to
    getContentPane().add(label, BorderLayout.CENTER);

    // Get an optional AudioClip to play when the count expires
    String soundURL = getParameter("sound");
    if (soundURL != null) sound=getAudioClip(getDocumentBase(), soundURL);

    // Obtain a NumberFormat object to convert number of minutes and
    // seconds to strings. Set it up to produce a leading 0 if necessary
    format = NumberFormat.getNumberInstance();
    format.setMinimumIntegerDigits(2); // pad with 0 if necessary

    // Specify a MouseListener to handle mouse events in the applet.
    // Note that the applet implements this interface itself
    addMouseListener(this);

    // Create a timer to call the actionPerformed() method immediately,
    // and then every 1000 milliseconds. Note we don't start the timer yet.
    timer = new Timer(1000, this);
    timer.setInitialDelay(0); // First timer is immediate.
}

// Free up any resources we hold; called when the applet is done
public void destroy() { if (image != null) image.flush(); }

// The browser calls this to start the applet running
// The resume() method is defined below.
public void start() { resume(); } // Start displaying updates

// The browser calls this to stop the applet. It may be restarted later.
// The pause() method is defined below
public void stop() { pause(); } // Stop displaying updates

// Return information about the applet
public String getAppletInfo() {
    return "Countdown applet Copyright (c) 2003 by David Flanagan";
}

// Return information about the applet parameters
public String[][] getParameterInfo() { return parameterInfo; }

// This is the parameter information. One array of strings for each
// parameter. The elements are parameter name, type, and description.
static String[][] parameterInfo = {
    {"minutes", "number", "time, in minutes, to countdown from"},
    {"font", "font", "optional font for the time display"},
    {"foreground", "color", "optional foreground color for the time"},
    {"background", "color", "optional background color"},
    {"image", "image URL", "optional image to display next to countdown"},
    {"sound", "sound URL", "optional sound to play when we reach 00:00"},
    {"newpage", "document URL", "URL to load when timer expires"},
};

// Start or resume the countdown
void resume() {
    // Restore the time we're counting down from and restart the timer.
    lastUpdate = System.currentTimeMillis();
    timer.start(); // Start the timer
}

// Pause the countdown
void pause() {
    // Subtract elapsed time from the remaining time and stop timing
    long now = System.currentTimeMillis();
    remaining -= (now - lastUpdate);
    timer.stop(); // Stop the timer
}

// Update the displayed time. This method is called from actionPerformed()
// which is itself invoked by the timer.
void updateDisplay() {
    long now = System.currentTimeMillis(); // current time in ms
    long elapsed = now - lastUpdate; // ms elapsed since last update
    remaining -= elapsed; // adjust remaining time
    lastUpdate = now; // remember this update time

    // Convert remaining milliseconds to mm:ss format and display
    if (remaining < 0) remaining = 0;
    int minutes = (int)(remaining/60000);
    int seconds = (int)((remaining)/1000);
    label.setText(format.format(minutes) + ":" + format.format(seconds));

    // If we've completed the countdown beep and display new page
    if (remaining == 0) {
        // Stop updating now.
        timer.stop();
        // If we have an alarm sound clip, play it now.
        if (sound != null) sound.play();
        // If there is a newpage URL specified, make the browser
        // load that page now.
        String newpage = getParameter("newpage");
        if (newpage != null) {
            try {
                URL url = new URL(getDocumentBase(), newpage);
                getAppletContext().showDocument(url);
            }
            catch(MalformedURLException ex) {      showStatus(ex.toString()); }
        }
    }
}

// This method implements the ActionListener interface.
// It is invoked once a second by the Timer object
// and updates the JLabel to display minutes and seconds remaining.
public void actionPerformed(ActionEvent e) { updateDisplay(); }

// The methods below implement the MouseListener interface. We use
// two of them to pause the countdown when the mouse hovers over the timer.
// Note that we also display a message in the statusline
public void mouseEntered(MouseEvent e) {
    pause(); // pause countdown
    showStatus("Paused"); // display statusline message
}
public void mouseExited(MouseEvent e) {
    resume(); // resume countdown
    showStatus(""); // clear statusline
}
// These MouseListener methods are unused.
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
} 

PHP Warning: PHP Startup: ????????: Unable to initialize module

This is just describing why I had this issue in case someone finds it helpful.

My problem was that I had upgraded php with homebrew and had forced at some point the variable PHP_INI_SCAN_DIR in my profile or bashrc file so it was pointing to the old php version. Removed that line and fixed.

How to parse a String containing XML in Java and retrieve the value of the root node?

You could do this with JAXB (an implementation is included in Java SE 6).

import java.io.StringReader;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        String xmlString = "<message>HELLO!</message> ";
        JAXBContext jc = JAXBContext.newInstance(String.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource xmlSource = new StreamSource(new StringReader(xmlString));
        JAXBElement<String> je = unmarshaller.unmarshal(xmlSource, String.class);
        System.out.println(je.getValue());
    }

}

Output

HELLO!

How to Get a Specific Column Value from a DataTable?

As per the title of the post I just needed to get all values from a specific column. Here is the code I used to achieve that.

    public static IEnumerable<T> ColumnValues<T>(this DataColumn self)
    {
        return self.Table.Select().Select(dr => (T)Convert.ChangeType(dr[self], typeof(T)));
    }

Do I need to compile the header files in a C program?

Okay, let's understand the difference between active and passive code.

The active code is the implementation of functions, procedures, methods, i.e. the pieces of code that should be compiled to executable machine code. We store it in .c files and sure we need to compile it.

The passive code is not being execute itself, but it needed to explain the different modules how to communicate with each other. Usually, .h files contains only prototypes (function headers), structures.

An exception are macros, that formally can contain an active pieces, but you should understand that they are using at the very early stage of building (preprocessing) with simple substitution. At the compile time macros already are substituted to your .c file.

Another exception are C++ templates, that should be implemented in .h files. But here is the story similar to macros: they are substituted on the early stage (instantiation) and formally, each other instantiation is another type.

In conclusion, I think, if the modules formed properly, we should never compile the header files.

Verilog generate/genvar in an always block

for verilog just do

parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
  temp <= {ROWBITS{1'b0}}; // fill with 0
end

How to frame two for loops in list comprehension python

tags = [u'man', u'you', u'are', u'awesome']
entries = [[u'man', u'thats'],[ u'right',u'awesome']]

result = []
[result.extend(entry) for tag in tags for entry in entries if tag in entry]

print(result)

Output:

['man', 'thats', 'right', 'awesome']

Can't find out where does a node.js app running and can't kill it

If all those kill process commands don't work for you, my suggestion is to check if you were using any other packages to run your node process.

I had the similar issue, and it was due to I was running my node process using PM2(a NPM package). The kill [processID] command disables the process but keeps the port occupied. Hence I had to go into PM2 and dump all node process to free up the port again.

How to get current route in react-router 2.0.0-rc5

As of version 3.0.0, you can get the current route by calling:

this.context.router.location.pathname

Sample code is below:

var NavLink = React.createClass({
    contextTypes: {
        router: React.PropTypes.object
    },

    render() {   
        return (
            <Link {...this.props}></Link>
        );
    }
});

Mod in Java produces negative numbers

Since Java 8 you can use the Math.floorMod() method:

Math.floorMod(-1, 2); //== 1

Note: If the modulo-value (here 2) is negative, all output values will be negative too. :)

Source: https://stackoverflow.com/a/25830153/2311557

Multiple types were found that match the controller named 'Home'

You can also get the 500 error if you add your own assembly that contains the ApiController by overriding GetAssemblies of the DefaultAssembliesResolver and it is already in the array from base.GetAssemblies()

Case in point:

public class MyAssembliesResolver : DefaultAssembliesResolver
{
    public override ICollection<Assembly> GetAssemblies()
    {
        var baseAssemblies = base.GetAssemblies();

        var assemblies = new List<Assembly>(baseAssemblies);

        assemblies.Add(Assembly.GetAssembly(typeof(MyAssembliesResolver)));

        return new List<Assembly>(assemblies);
    }
}

if the above code is in the same assembly as your Controller, that assembly will be in the list twice and will generate a 500 error since the Web API doesn't know which one to use.

Primary key or Unique index?

As long as you do not allow NULL for a value, they should be handled the same, but the value NULL is handled differently on databases(AFAIK MS-SQL do not allow more than one(1) NULL value, mySQL and Oracle allow this, if a column is UNIQUE) So you must define this column NOT NULL UNIQUE INDEX

How to test if a DataSet is empty?

It is not a valid answer as it gives following error

Cannot find table 0.

Use the following statement instead

if (ds.Tables.Count == 0)
{
     //DataSet is empty
}

How to call a parent method from child class in javascript?

Here's how its done: ParentClass.prototype.myMethod();

Or if you want to call it in the context of the current instance, you can do: ParentClass.prototype.myMethod.call(this)

Same goes for calling a parent method from child class with arguments: ParentClass.prototype.myMethod.call(this, arg1, arg2, ..) * Hint: use apply() instead of call() to pass arguments as an array.

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

One additional step I needed to take was to switch my URL from http://localhost to http://127.0.0.0

Run Java Code Online

Some new java online compiler and runner:

  1. Java Launch
  2. Srikanthdaggumalli

These sites are in under development. But you can view the compilation errors, Runtime Exceptions as well as output of a java program by clicking on the TryItYourself link.

Use of "this" keyword in formal parameters for static methods in C#

I just learnt this myself the other day: the this keyword defines that method has being an extension of the class that proceeds it. So for your example, MyClass will have a new extension method called Foo (which doesn't accept any parameter and returns an int; it can be used as with any other public method).

How to make a whole 'div' clickable in html and css without JavaScript?

Without JS, I am doing it like this:

My HTML:

<div class="container">
  <div class="sometext">Some text here</div>
  <div class="someothertext">Some other text here</div>
  <a href="#" class="mylink">text of my link</a>
</div>

My CSS:

.container{
  position: relative;
}

.container.a{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-indent: -9999px; //these two lines are to hide my actual link text.
  overflow: hidden; //these two lines are to hide my actual link text.
}

selecting from multi-index pandas

Understanding how to access multi-indexed pandas DataFrame can help you with all kinds of task like that.

Copy paste this in your code to generate example:

# hierarchical indices and columns
index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]],
                                   names=['year', 'visit'])
columns = pd.MultiIndex.from_product([['Bob', 'Guido', 'Sue'], ['HR', 'Temp']],
                                     names=['subject', 'type'])

# mock some data
data = np.round(np.random.randn(4, 6), 1)
data[:, ::2] *= 10
data += 37

# create the DataFrame
health_data = pd.DataFrame(data, index=index, columns=columns)
health_data

Will give you table like this:

enter image description here

Standard access by column

health_data['Bob']
type       HR   Temp
year visit      
2013    1   22.0    38.6
        2   52.0    38.3
2014    1   30.0    38.9
        2   31.0    37.3


health_data['Bob']['HR']
year  visit
2013  1        22.0
      2        52.0
2014  1        30.0
      2        31.0
Name: HR, dtype: float64

# filtering by column/subcolumn - your case:
health_data['Bob']['HR']==22
year  visit
2013  1         True
      2        False
2014  1        False
      2        False

health_data['Bob']['HR'][2013]    
visit
1    22.0
2    52.0
Name: HR, dtype: float64

health_data['Bob']['HR'][2013][1]
22.0

Access by row

health_data.loc[2013]
subject Bob Guido   Sue
type    HR  Temp    HR  Temp    HR  Temp
visit                       
1   22.0    38.6    40.0    38.9    53.0    37.5
2   52.0    38.3    42.0    34.6    30.0    37.7

health_data.loc[2013,1] 
subject  type
Bob      HR      22.0
         Temp    38.6
Guido    HR      40.0
         Temp    38.9
Sue      HR      53.0
         Temp    37.5
Name: (2013, 1), dtype: float64

health_data.loc[2013,1]['Bob']
type
HR      22.0
Temp    38.6
Name: (2013, 1), dtype: float64

health_data.loc[2013,1]['Bob']['HR']
22.0

Slicing multi-index

idx=pd.IndexSlice
health_data.loc[idx[:,1], idx[:,'HR']]
    subject Bob Guido   Sue
type    HR  HR  HR
year    visit           
2013    1   22.0    40.0    53.0
2014    1   30.0    52.0    45.0

background-size in shorthand background property (CSS3)

You will have to use vendor prefixes to support different browsers and therefore can't use it in shorthand.

body { 
        background: url(images/bg.jpg) no-repeat center center fixed; 
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}

No line-break after a hyphen

You could also wrap the relevant text with

<span style="white-space: nowrap;"></span>

Latex Multiple Linebreaks

Insert some vertical space

blah blah blah \\
\vspace{1cm}

to scale to the font, use ex (the height of a lowercase "x") as the unit, and there are various predefined lengths related to the line spacing available, you might be particularly interested in baselineskip.

How to get folder path for ClickOnce application

Assuming the question is about accessing files in the application folder after the ClickOnce (true == System.Deployment.ApplicationDeploy.IsNetworkDeployed) application is installed on the user's PC, their are three ways to get this folder by the application itself:

String path1 = System.AppDomain.CurrentDomain.BaseDirectory;
String path2 = System.IO.Directory.GetCurrentDirectory();    
String path3 = System.Reflection.Assembly.GetExecutingAssembly().CodeBase; //Remove the last path component, the executing assembly itself.

These work from VS IDE and from a deployed/installed ClickedOnce app, no "true == System.Deployment.ApplicationDeploy.IsNetworkDeployed" check required. ClickOnce picks up any files included in the Visual Studio 2017 project so really the application can access any and all deployed files using relative paths from within the application.

This is based on Windows 10 and Visual Studio 2017

How to create .pfx file from certificate and private key?

I know a few users have talked about installing this and that and adding command lines programmes and downloading...

Personally I am lazy and find all these methods cumbersome and slow, plus I don't want to download anything and find the correct cmd lines if I don't have to.

Best way for me on my personal IIS server is to use RapidSSLOnline. This is a tool that's on a server allows you to upload your certificate and private key and is able to generate a pfx file for you that you can directly import into IIS.

The link is here: https://www.rapidsslonline.com/ssl-tools/ssl-converter.php

Below is the steps used for the scenario requested.

  1. Select Current Type = PEM
  2. Change for = PFX
  3. Upload your certificate
  4. Upload your private key
  5. If you have ROOT CA cert or intermediate certs upload them too
  6. Set a password of your choosing, used in IIS
  7. Click the reCaptcha to prove you're not a bot
  8. Click Convert

And that's it you should have a PFX downloaded and use this in your Import process on IIS.

Hope this helps other like minded, lazy tech people.

Clearing an HTML file upload field via JavaScript

You can't set the input value in most browsers, but what you can do is create a new element, copy the attributes from the old element, and swap the two.

Given a form like:

<form> 
    <input id="fileInput" name="fileInput" type="file" /> 
</form>

The straight DOM way:

function clearFileInput(id) 
{ 
    var oldInput = document.getElementById(id); 

    var newInput = document.createElement("input"); 

    newInput.type = "file"; 
    newInput.id = oldInput.id; 
    newInput.name = oldInput.name; 
    newInput.className = oldInput.className; 
    newInput.style.cssText = oldInput.style.cssText; 
    // TODO: copy any other relevant attributes 

    oldInput.parentNode.replaceChild(newInput, oldInput); 
}

clearFileInput("fileInput");

Simple DOM way. This may not work in older browsers that don't like file inputs:

oldInput.parentNode.replaceChild(oldInput.cloneNode(), oldInput);

The jQuery way:

$("#fileInput").replaceWith($("#fileInput").val('').clone(true));

// .val('') required for FF compatibility as per @nmit026

Resetting the whole form via jQuery: https://stackoverflow.com/a/13351234/1091947

Tool to monitor HTTP, TCP, etc. Web Service traffic

I've been using Charles for the last couple of years. Very pleased with it.

git command to move a folder inside another

Another way to move all files in a directory to a sub directory (keeps git history):

$ for file in $(ls | grep -v 'subDir'); do git mv $file subDir; done;

ReactJS - How to use comments?

To summarize, JSX doesn't support comments, either html-like or js-like:

<div>
    /* This will be rendered as text */
    // as well as this
    <!-- While this will cause compilation failure -->
</div>

and the only way to add comments "in" JSX is actually to escape into JS and comment in there:

<div>
    {/* This won't be rendered */}
    {// just be sure that your closing bracket is out of comment
    }
</div>

if you don't want to make some nonsense like

<div style={{display:'none'}}>
    actually, there are other stupid ways to add "comments"
    but cluttering your DOM is not a good idea
</div>

Finally, if you do want to create a comment node via React, you have to go much fancier, check out this answer.

R plot: size and resolution

A reproducible example:

the_plot <- function()
{
  x <- seq(0, 1, length.out = 100)
  y <- pbeta(x, 1, 10)
  plot(
    x,
    y,
    xlab = "False Positive Rate",
    ylab = "Average true positive rate",
    type = "l"
  )
}

James's suggestion of using pointsize, in combination with the various cex parameters, can produce reasonable results.

png(
  "test.png",
  width     = 3.25,
  height    = 3.25,
  units     = "in",
  res       = 1200,
  pointsize = 4
)
par(
  mar      = c(5, 5, 2, 2),
  xaxs     = "i",
  yaxs     = "i",
  cex.axis = 2,
  cex.lab  = 2
)
the_plot()
dev.off()

Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,

library(ggplot2)

ggplot_alternative <- function()
{
  the_data <- data.frame(
    x <- seq(0, 1, length.out = 100),
    y = pbeta(x, 1, 10)
  )

ggplot(the_data, aes(x, y)) +
    geom_line() +
    xlab("False Positive Rate") +
    ylab("Average true positive rate") +
    coord_cartesian(0:1, 0:1)
}

ggsave(
  "ggtest.png",
  ggplot_alternative(),
  width = 3.25,
  height = 3.25,
  dpi = 1200
)

INSERT IF NOT EXISTS ELSE UPDATE?

Have a look at http://sqlite.org/lang_conflict.html.

You want something like:

insert or replace into Book (ID, Name, TypeID, Level, Seen) values
((select ID from Book where Name = "SearchName"), "SearchName", ...);

Note that any field not in the insert list will be set to NULL if the row already exists in the table. This is why there's a subselect for the ID column: In the replacement case the statement would set it to NULL and then a fresh ID would be allocated.

This approach can also be used if you want to leave particular field values alone if the row in the replacement case but set the field to NULL in the insert case.

For example, assuming you want to leave Seen alone:

insert or replace into Book (ID, Name, TypeID, Level, Seen) values (
   (select ID from Book where Name = "SearchName"),
   "SearchName",
    5,
    6,
    (select Seen from Book where Name = "SearchName"));

How to use multiple @RequestMapping annotations in spring?

The shortest way is: @RequestMapping({"", "/", "welcome"})

Although you can also do:

  • @RequestMapping(value={"", "/", "welcome"})
  • @RequestMapping(path={"", "/", "welcome"})

for-in statement

In Typescript 1.5 and later, you can use for..of as opposed to for..in

var numbers = [1, 2, 3];

for (var number of numbers) {
    console.log(number);
}

Trust Store vs Key Store - creating with keytool

In simplest terms :

Keystore is used to store your credential (server or client) while truststore is used to store others credential (Certificates from CA).

Keystore is needed when you are setting up server side on SSL, it is used to store server's identity certificate, which server will present to a client on the connection while trust store setup on client side must contain to make the connection work. If you browser to connect to any website over SSL it verifies certificate presented by server against its truststore.

How to get the current directory of the cmdlet being executed

this function will set the prompt location to script path, dealing with the differents way to get scriptpath between vscode, psise and pwd :

function Set-CurrentLocation
{
    $currentPath = $PSScriptRoot                                                                                                     # AzureDevOps, Powershell
    if (!$currentPath) { $currentPath = Split-Path $pseditor.GetEditorContext().CurrentFile.Path -ErrorAction SilentlyContinue }     # VSCode
    if (!$currentPath) { $currentPath = Split-Path $psISE.CurrentFile.FullPath -ErrorAction SilentlyContinue }                       # PsISE

    if ($currentPath) { Set-Location $currentPath }
}

C - freeing structs

Because you defined the struct as consisting of char arrays, the two strings are the structure and freeing the struct is sufficient, nor is there a way to free the struct but keep the arrays. For that case you would want to do something like struct { char *firstName, *lastName; }, but then you need to allocate memory for the names separately and handle the question of when to free that memory.

Aside: Is there a reason you want to keep the names after the struct has been freed?

Entity Framework - Code First - Can't Store List<String>

I want to add that when using Npgsql (data provider for PostgreSQL), arrays and lists of primitive types are actually supported:

https://www.npgsql.org/efcore/mapping/array.html

Insert a line at specific line number with sed or awk

sed -e '8iProject_Name=sowstest' -i start using GNU sed

Sample run:

[root@node23 ~]# for ((i=1; i<=10; i++)); do echo "Line #$i"; done > a_file
[root@node23 ~]# cat a_file
Line #1
Line #2
Line #3
Line #4
Line #5
Line #6
Line #7
Line #8
Line #9
Line #10
[root@node23 ~]# sed -e '3ixxx inserted line xxx' -i a_file 
[root@node23 ~]# cat -An a_file 
     1  Line #1$
     2  Line #2$
     3  xxx inserted line xxx$
     4  Line #3$
     5  Line #4$
     6  Line #5$
     7  Line #6$
     8  Line #7$
     9  Line #8$
    10  Line #9$
    11  Line #10$
[root@node23 ~]# 
[root@node23 ~]# sed -e '5ixxx (inserted) "line" xxx' -i a_file
[root@node23 ~]# cat -n a_file 
     1  Line #1
     2  Line #2
     3  xxx inserted line xxx
     4  Line #3
     5  xxx (inserted) "line" xxx
     6  Line #4
     7  Line #5
     8  Line #6
     9  Line #7
    10  Line #8
    11  Line #9
    12  Line #10
[root@node23 ~]# 

is there any IE8 only css hack?

Can you not use the hack you've already shown, and then use an IE7 and below hack to override it?

Can I pass parameters in computed properties in Vue.Js

You can pass parameters but either it is not a vue.js way or the way you are doing is wrong.

However there are cases when you need to do so.I am going to show you a simple example passing value to computed property using getter and setter.

<template>
    <div>
        Your name is {{get_name}} <!-- John Doe at the beginning -->
        <button @click="name = 'Roland'">Change it</button>
    </div>
</template>

And the script

export default {
    data: () => ({
        name: 'John Doe'
    }),
    computed:{
        get_name: {
            get () {
                return this.name
            },
            set (new_name) {
                this.name = new_name
            }
        },
    }    
}

When the button clicked we are passing to computed property the name 'Roland' and in set() we are changing the name from 'John Doe' to 'Roland'.

Below there is a common use case when computed is used with getter and setter. Say you have the follow vuex store:

export default new Vuex.Store({
  state: {
    name: 'John Doe'
  },
  getters: {
    get_name: state => state.name
  },
  mutations: {
    set_name: (state, payload) => state.name = payload
  },
})

And in your component you want to add v-model to an input but using the vuex store.

<template>
    <div>
        <input type="text" v-model="get_name">
        {{get_name}}
    </div>
</template>
<script>
export default {
    computed:{
        get_name: {
            get () {
                return this.$store.getters.get_name
            },
            set (new_name) {
                this.$store.commit('set_name', new_name)
            }
        },
    }    
}
</script>

How do I calculate power-of in C#?

You are looking for the static method Math.Pow().

Get PHP class property by string

$classname = "myclass";
$obj = new $classname($params);

$variable_name = "my_member_variable";
$val = $obj->$variable_name; //do care about the level(private,public,protected)

$func_name = "myFunction";
$val = $obj->$func_name($parameters);

why edit: before : using eval (evil) after : no eval at all. being old in this language.

What exactly does Double mean in java?

Double is a wrapper class,

The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.

In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double.

The double data type,

The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

Check each datatype with their ranges : Java's Primitive Data Types.


Important Note : If you'r thinking to use double for precise values, you need to re-think before using it. Java Traps: double

How can I convert an HTML table to CSV?

Assuming that you've designed an HTML page containing a table, I would recommend this solution. Worked like charm for me:

$(document).ready(() => {
  $("#buttonExport").click(e => {
    // Getting values of current time for generating the file name
    const dateTime = new Date();
    const day      = dateTime.getDate();
    const month    = dateTime.getMonth() + 1;
    const year     = dateTime.getFullYear();
    const hour     = dateTime.getHours();
    const minute   = dateTime.getMinutes();
    const postfix  = `${day}.${month}.${year}_${hour}.${minute}`;

    // Creating a temporary HTML link element (they support setting file names)
    const downloadElement = document.createElement('a');

    // Getting data from our `div` that contains the HTML table
    const dataType  = 'data:application/vnd.ms-excel';
    const tableDiv  = document.getElementById('divData');
    const tableHTML = tableDiv.outerHTML.replace(/ /g, '%20');

    // Setting the download source
    downloadElement.href = `${dataType},${tableHTML}`;

    // Setting the file name
    downloadElement.download = `exported_table_${postfix}.xls`;

    // Trigger the download
    downloadElement.click();

    // Just in case, prevent default behaviour
    e.preventDefault();
  });
});

Courtesy: http://www.kubilayerdogan.net/?p=218

You can edit the file format to .csv here:

downloadElement.download = `exported_table_${postfix}.csv`;

How to compare two maps by their values

If anyone is looking to do it in Java 8 streams below is the example.

import java.util.HashMap;
import java.util.Map;

public class CompareTwoMaps {

    public static void main(String[] args) {

        Map<String, String> a = new HashMap<>();
        a.put("foo", "bar" + "bar");
        a.put("zoo", "bar" + "bar");

        Map<String, String> b = new HashMap<>();
        b.put(new String("foo"), "bar" + "bar");
        b.put(new String("zoo"), "bar" + "bar");

        System.out.println("result = " + areEqual(a, b));
    }

    private static boolean areEqual(Map<String, String> first, Map<String, String> second) {
        return first.entrySet().stream()
                .allMatch(e -> e.getValue().equals(second.get(e.getKey())));
    }
}

Display Two <div>s Side-by-Side

Try this : (http://jsfiddle.net/TpqVx/)

.left-div {
    float: left;
    width: 100px;
    /*height: 20px;*/
    margin-right: 8px;
    background-color: linen;
}
.right-div {

    margin-left: 108px;
    background-color: lime;
}??

<div class="left-div">
    &nbsp;
</div>
<div class="right-div">
    My requirements are <b>[A]</b> Content in the two divs should line up at the top, <b>[B]</b> Long text in right-div should not wrap underneath left-div, and <b>[C]</b> I do not want to specify a width of right-div. I don't want to set the width of right-div because this markup needs to work within different widths.
</div>
<div style='clear:both;'>&nbsp;</div>

Hints :

  • Just use float:left in your left-most div only.
  • No real reason to use height, but anyway...
  • Good practice to use <div 'clear:both'>&nbsp;</div> after your last div.

How do we determine the number of days for a given month in python

Just for the sake of academic interest, I did it this way...

(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

If statement within Where clause

You can't use IF like that. You can do what you want with AND and OR:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE ((status_flag = STATUS_ACTIVE   AND t.status = 'A')
     OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
     OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
     OR (source_flag = SOURCE_USER     AND t.business_unit = 'users'))
   AND t.first_name LIKE firstname
   AND t.last_name  LIKE lastname
   AND t.employid   LIKE employeeid;

error: member access into incomplete type : forward declaration of

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}

How to make a launcher

They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.

File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish

But if you do not have samples loaded, then download it using the below steps

Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install

Calling a user defined function in jQuery

If you want to call a normal function via a jQuery event, you can do it like this:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#btnSun').click(myFunction);_x000D_
});_x000D_
_x000D_
function myFunction() {_x000D_
  alert('hi');_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="btnSun">Say hello!</button>
_x000D_
_x000D_
_x000D_

implementing merge sort in C++

The problem with merge sort is the merge, if you don't actually need to implement the merge, then it is pretty simple (for a vector of ints):

#include <algorithm>
#include <vector>
using namespace std;

typedef vector<int>::iterator iter;

void mergesort(iter b, iter e) {
    if (e -b > 1) {
        iter m = b + (e -b) / 2;
        mergesort(b, m);
        mergesort(m, e);
        inplace_merge(b, m, e);
    }
}

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

You want a parameter source:

Set<Integer> ids = ...;

MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);

List<Foo> foo = getJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",
     parameters, getRowMapper());

This only works if getJdbcTemplate() returns an instance of type NamedParameterJdbcTemplate

How can I read SMS messages from the device programmatically in Android?

There are lots of answers are already available but i think all of them are missing an important part of this question. Before reading data from an internal database or its table we have to understand how data is stored in it and then we can find the solution of the above question that is :

How can I read SMS messages from the device programmatically in Android?

So,In android SMS table is like look like this

enter image description here

Know,we can select whatever we want from the database.In our case we have only required

id,address and body

In case of reading SMS:

1.Ask for permissions

int REQUEST_PHONE_CALL = 1;

   if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_SMS}, REQUEST_PHONE_CALL);
        }

or

 <uses-permission android:name="android.permission.READ_SMS" />

2.Now your code goes like this

// Create Inbox box URI
Uri inboxURI = Uri.parse("content://sms/inbox");

// List required columns
String[] reqCols = new String[]{"_id", "address", "body"};

// Get Content Resolver object, which will deal with Content Provider
ContentResolver cr = getContentResolver();

// Fetch Inbox SMS Message from Built-in Content Provider
Cursor c = cr.query(inboxURI, reqCols, null, null, null);

// Attached Cursor with adapter and display in listview
adapter = new SimpleCursorAdapter(this, R.layout.a1_row, c,
        new String[]{"body", "address"}, new int[]{
        R.id.A1_txt_Msg, R.id.A1_txt_Number});
lst.setAdapter(adapter);

I hope this one will be helpful. Thanks.

How to get IP address of the device from code?

private InetAddress getLocalAddress()throws IOException {

            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            //return inetAddress.getHostAddress().toString();
                            return inetAddress;
                        }
                    }
                }
            } catch (SocketException ex) {
                Log.e("SALMAN", ex.toString());
            }
            return null;
        }

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

For anyone who lands here and all the other solutions did not work give this a try. I am using typescript + react and my problem was that I was associating the files in vscode as javascriptreact not typescriptreact so check your settings for the following entries.

   "files.associations": {
    "*.tsx": "typescriptreact",
    "*.ts": "typescriptreact"
  },

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

It seems that when this error appears it is an indication that the selenium-java plugin for maven is out-of-date.

Changing the version in the pom.xml should fix the problem

What are the First and Second Level caches in (N)Hibernate?

In a second level cache, domain hbm files can be of key mutable and value false. For example, In this domain class some of the duration in a day remains constant as the universal truth. So, it can be marked as immutable across application.

Using psql to connect to PostgreSQL in SSL mode

Found the following options useful to provide all the files for a self signed postgres instance

psql "host={hostname} sslmode=prefer sslrootcert={ca-cert.pem} sslcert={client-cert.pem} sslkey={client-key.pem} port={port} user={user} dbname={db}"

Is there a way to get a list of all current temporary tables in SQL Server?

Is this what you are after?

select * from tempdb..sysobjects
--for sql-server 2000 and later versions

select * from tempdb.sys.objects
--for sql-server 2005 and later versions

TypeError: 'str' object cannot be interpreted as an integer

You have to convert input x and y into int like below.

x=int(x)
y=int(y)

How to reverse MD5 to get the original string?

No, that's not really possible, as

  • there can be more than one string giving the same MD5
  • it was designed to be hard to "reverse"

The goal of the MD5 and its family of hashing functions is

  • to get short "extracts" from long string
  • to make it hard to guess where they come from
  • to make it hard to find collisions, that is other words having the same hash (which is a very similar exigence as the second one)

Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.

This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

For Android 6.0 at least, the ARM Translation thing is apparently unnecessary.

Just grab an x86 + Android 6.0 package (nano is fine) from OpenGApps and install by dragging-and-dropping and telling it to flash.

It seems the ARM translation thing was previously required, before the x86 package was available. You might still need the ARM translation if you want to install ARM-only apps though.

Removing rounded corners from a <select> element in Chrome/Webkit

Inset box-shadow does the trick.

select{
  -webkit-appearance: none;
  box-shadow: inset 0px 0px 0px 4px;
  border-radius: 0px;
  border: none;
  padding:20px 150px 20px 10px;
}

Demo

How to get the bluetooth devices as a list?

In this code you just need to call this in your button click.

private void list_paired_Devices() {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        ArrayList<String> devices = new ArrayList<>();
        for (BluetoothDevice bt : pairedDevices) {
            devices.add(bt.getName() + "\n" + bt.getAddress());
        }
        ArrayAdapter arrayAdapter = new ArrayAdapter(bluetooth.this, android.R.layout.simple_list_item_1, devices);
        emp.setAdapter(arrayAdapter);
    }

Can an Android App connect directly to an online mysql database

Yes definitely you can connect to the MySql online database for that you need to create a web service. This web service will provide you access to the MySql database. Then you can easily pull and push data to MySql Database. PHP will be a good option for creating web service its simple to implement. Good luck...

Jquery show/hide table rows

The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:

    var black = $('.black');
    var white = $('.white');

The selector will find every element classed under black or white. Button functions stay as stated above:

    $('#showBlackButton').click(function() {
           black.show();
           white.hide();
    });

    $('#showWhiteButton').click(function() {
           white.show();
           black.hide();
    });

Error in plot.new() : figure margins too large, Scatter plot

Every time you are creating plots you might get this error - "Error in plot.new() : figure margins too large". To avoid such errors you can first check par("mar") output. You should be getting:

[1] 5.1 4.1 4.1 2.1

To change that write:

par(mar=c(1,1,1,1))

This should rectify the error. Or else you can change the values accordingly.

Hope this works for you.

Is header('Content-Type:text/plain'); necessary at all?

PHP uses Content-Type "text/html" as default - which is pretty similar to "text/plain" - and this explains why you don't see any differences. text/plain is necessary if you want to output text as is (including <>-symbols). Examples:

header("Content-Type: text/plain");
echo "<b>hello world</b>";
// Output: <b>hello world</b>

header("Content-Type: text/html");
echo "<b>hello world</b>";
// Output: hello world

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

How to escape single quotes within single quoted strings

In the given example, simply used double quotes instead of single quotes as outer escape mechanism:

alias rxvt="urxvt -fg '#111111' -bg '#111111'"

This approach is suited for many cases where you just want to pass a fixed string to a command: Just check how the shell will interpret the double-quoted string through an echo, and escape characters with backslash if necessary.

In the example, you'd see that double quotes are sufficient to protect the string:

$ echo "urxvt -fg '#111111' -bg '#111111'"
urxvt -fg '#111111' -bg '#111111'

File path for project files?

You would do something like this to get the path "Data\ich_will.mp3" inside your application environments folder.

string fileName = "ich_will.mp3";
string path = Path.Combine(Environment.CurrentDirectory, @"Data\", fileName);

In my case it would return the following:

C:\MyProjects\Music\MusicApp\bin\Debug\Data\ich_will.mp3

I use Path.Combine and Environment.CurrentDirectory in my example. These are very useful and allows you to build a path based on the current location of your application. Path.Combine combines two or more strings to create a location, and Environment.CurrentDirectory provides you with the working directory of your application.

The working directory is not necessarily the same path as where your executable is located, but in most cases it should be, unless specified otherwise.

sum two columns in R

The sum function will add all numbers together to produce a single number, not a vector (well, at least not a vector of length greater than 1).

It looks as though at least one of your columns is a factor. You could convert them into numeric vectors by checking this

head(as.numeric(data$col1))  # make sure this gives you the right output

And if that looks right, do

data$col1 <- as.numeric(data$col1)
data$col2 <- as.numeric(data$col2)

You might have to convert them into characters first. In which case do

data$col1 <- as.numeric(as.character(data$col1))
data$col2 <- as.numeric(as.character(data$col2))

It's hard to tell which you should do without being able to see your data.

Once the columns are numeric, you just have to do

data$col3 <- data$col1 + data$col2

"if not exist" command in batch file

if not exist "%USERPROFILE%\.qgis-custom\" (
    mkdir "%USERPROFILE%\.qgis-custom" 2>nul
    if not errorlevel 1 (
        xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
    )
)

You have it almost done. The logic is correct, just some little changes.

This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).

If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.

If everyting is ok, files are copied.

All paths are quoted to avoid problems with spaces.

It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files

mkdir "%USERPROFILE%\.qgis-custom" 2>nul 
if not errorlevel 1 (
    xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)

In both code samples, files are not copied if the folder is not being created during the script execution.

EDITED - As dbenham comments, the same code can be written as a single line

md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e

The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.

Regular Expression to match string starting with a specific word

If you wish to match only lines beginning with stop use

^stop

If you wish to match lines beginning with the word stop followed by a space

^stop\s

Or, if you wish to match lines beginning with the word stop but followed by either a space or any other non word character you can use (your regex flavor permitting)

^stop\W

On the other hand, what follows matches a word at the beginning of a string on most regex flavors (in these flavors \w matches the opposite of \W)

^\w

If your flavor does not have the \w shortcut, you can use

^[a-zA-Z0-9]+

Be wary that this second idiom will only match letters and numbers, no symbol whatsoever.

Check your regex flavor manual to know what shortcuts are allowed and what exactly do they match (and how do they deal with Unicode.)

Disable time in bootstrap date time picker

Not as put off time and language at a time I put this and not work

$(function () {
    $('#datetimepicker2').datetimepicker({
              locale: 'es',
              pickTime: false
          });
});

Using group by and having clause

1.Get supplier numbers and names for suppliers of parts supplied to at least two different projects.

 SELECT S.SID, S.NAME
 FROM SUPPLIES SP
 JOIN SUPPLIER S
 ON SP.SID = S.SID
 WHERE PID IN
 (SELECT PID FROM SUPPPLIES GROUP BY PID, JID HAVING COUNT(*) >= 2)

I am not slear about your second question

Mac OS X - EnvironmentError: mysql_config not found

This answer is for MacOS users who did not install from brew but rather from the official .dmg/.pkg. That installer fails to edit your PATH, causing things to break out of the box:

  1. All MySQL commands like mysql, mysqladmin, mysql_config, etc cannot be found, and as a result:
  2. the "MySQL Preference Pane" fails to appear in System Preferences, and
  3. you cannot install any API that communicates with MySQL, including mysqlclient

What you have to do is appending the MySQL bin folder (typically /usr/local/mysql/bin in your PATH by adding this line in your ~/.bash_profile file:

export PATH="/usr/local/mysql/bin/:$PATH"

You should then reload your ~/.bash_profile for the change to take effect in your current Terminal session:

source ~/.bash_profile

Before installing mysqlclient, however, you need to accept the XcodeBuild license:

sudo xcodebuild -license

Follow their directions to sign away your family, after which you should be able to install mysqlclient without issue:

pip install mysqlclient

After installing that, you must do one more thing to fix a runtime bug that ships with MySQL (Dynamic Library libmysqlclient.dylib not found), by adding this line to your system dynamic libraries path:

export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/:$DYLD_LIBRARY_PATH

How to get the day name from a selected date?

DateTime.Now.DayOfWeek quite easy to guess actually.

for any given date:

   DateTime dt = //....
   DayOfWeek dow = dt.DayOfWeek; //enum
   string str = dow.ToString(); //string

How do I lowercase a string in Python?

Also, you can overwrite some variables:

s = input('UPPER CASE')
lower = s.lower()

If you use like this:

s = "Kilometer"
print(s.lower())     - kilometer
print(s)             - Kilometer

It will work just when called.

How to bind list to dataGridView?

I know this is old, but this hung me up for awhile. The properties of the object in your list must be actual "properties", not just public members.

public class FileName
{        
     public string ThisFieldWorks {get;set;}
     public string ThisFieldDoesNot;
}

how to hide the content of the div in css

_x000D_
_x000D_
.button {_x000D_
        width: 40px;_x000D_
        height: 40px;_x000D_
        font-size: 0;_x000D_
        background: url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%221284%20207%2024%2024%22%3E%3Cg%20fill%3D%22none%22%3E%3Cpath%20d%3D%22M1298.5%20222.9C1297.5%20223.6%201296.3%20224%201295%20224%201291.7%20224%201289%20221.3%201289%20218%201289%20214.7%201291.7%20212%201295%20212%201298.3%20212%201301%20214.7%201301%20218%201301%20219.3%201300.6%20220.5%201299.9%20221.5L1302.7%20224.2C1303%20224.6%201303.1%20225.3%201302.7%20225.7%201302.3%20226%201301.6%20226%201301.2%20225.7L1298.5%20222.9ZM1295%20222C1297.2%20222%201299%20220.2%201299%20218%201299%20215.8%201297.2%20214%201295%20214%201292.8%20214%201291%20215.8%201291%20218%201291%20220.2%201292.8%20222%201295%20222Z%22%20fill%3D%22%239299A6%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E") #f0f2f5 no-repeat 50%;_x000D_
    }
_x000D_
<button class="button">?????</button>
_x000D_
_x000D_
_x000D_

How to find char in string and get all the indexes?

All the other answers have two main flaws:

  1. They do a Python loop through the string, which is horrifically slow, or
  2. They use numpy which is a pretty big additional dependency.
def findall(haystack, needle):
    idx = -1
    while True:
        idx = haystack.find(needle, idx+1)
        if idx == -1:
            break
        yield idx

This iterates through haystack looking for needle, always starting at where the previous iteration ended. It uses the builtin str.find which is much faster than iterating through haystack character-by-character. It doesn't require any new imports.

Align Bootstrap Navigation to Center

Thank you all for your help, I added this code and it seems it fixed the issue:

.navbar .navbar-nav {
    display: inline-block;
    float: none;
}

.navbar .navbar-collapse {
    text-align: center;
}

Source

Center content in responsive bootstrap navbar

How to sort multidimensional array by column?

You can use the sorted method with a key.

sorted(a, key=lambda x : x[1])

What's the algorithm to calculate aspect ratio?

Here is my solution it is pretty straight forward since all I care about is not necessarily GCD or even accurate ratios: because then you get weird things like 345/113 which are not human comprehensible.

I basically set acceptable landscape, or portrait ratios and their "value" as a float... I then compare my float version of the ratio to each and which ever has the lowest absolute value difference is the ratio closest to the item. That way when the user makes it 16:9 but then removes 10 pixels from the bottom it still counts as 16:9...

accepted_ratios = {
    'landscape': (
        (u'5:4', 1.25),
        (u'4:3', 1.33333333333),
        (u'3:2', 1.5),
        (u'16:10', 1.6),
        (u'5:3', 1.66666666667),
        (u'16:9', 1.77777777778),
        (u'17:9', 1.88888888889),
        (u'21:9', 2.33333333333),
        (u'1:1', 1.0)
    ),
    'portrait': (
        (u'4:5', 0.8),
        (u'3:4', 0.75),
        (u'2:3', 0.66666666667),
        (u'10:16', 0.625),
        (u'3:5', 0.6),
        (u'9:16', 0.5625),
        (u'9:17', 0.5294117647),
        (u'9:21', 0.4285714286),
        (u'1:1', 1.0)
    ),
}


def find_closest_ratio(ratio):
    lowest_diff, best_std = 9999999999, '1:1'
    layout = 'portrait' if ratio < 1.0 else 'landscape'
    for pretty_str, std_ratio in accepted_ratios[layout]:
        diff = abs(std_ratio - ratio)
        if diff < lowest_diff:
            lowest_diff = diff
            best_std = pretty_str
    return best_std


def extract_ratio(width, height):
    try:
        divided = float(width)/float(height)
        if divided == 1.0: return '1:1'
        return find_closest_ratio(divided)
    except TypeError:
        return None

Array of char* should end at '\0' or "\0"?

According to the C99 spec,

  • NULL expands to a null pointer constant, which is not required to be, but typically is of type void *
  • '\0' is a character constant; character constants are of type int, so it's equivalen to plain 0
  • "\0" is a null-terminated string literal and equivalent to the compound literal (char [2]){ 0, 0 }

NULL, '\0' and 0 are all null pointer constants, so they'll all yield null pointers on conversion, whereas "\0" yields a non-null char * (which should be treated as const as modification is undefined); as this pointer may be different for each occurence of the literal, it can't be used as sentinel value.

Although you may use any integer constant expression of value 0 as a null pointer constant (eg '\0' or sizeof foo - sizeof foo + (int)0.0), you should use NULL to make your intentions clear.

jQuery AJAX single file upload

A. Grab file data from the file field

The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:

// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

This saves the file data to a file variable for later use.

B. Handle the file upload on submit

When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:

$('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

// START A LOADING SPINNER HERE

// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
    data.append(key, value);
});

$.ajax({
    url: 'submit.php?files',
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            submitForm(event, data);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
        // STOP LOADING SPINNER
    }
});
}

What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:

  • processData - Because jQuery will convert the files arrays into strings and the server can't pick it up.
  • contentType - Set this to false because jQuery defaults to application/x-www-form-urlencoded and doesn't send the files. Also setting it to multipart/form-data doesn't seem to work either.

C. Upload the files

Quick and dirty php script to upload the files and pass back some info:

<?php // You need to add server side validation and better error handling here

$data = array();

if(isset($_GET['files']))
{  
$error = false;
$files = array();

$uploaddir = './uploads/';
foreach($_FILES as $file)
{
    if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
    {
        $files[] = $uploaddir .$file['name'];
    }
    else
    {
        $error = true;
    }
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);
}

echo json_encode($data);

?>

IMP: Don't use this, write your own.

D. Handle the form submit

The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:

function submitForm(event, data)
{
  // Create a jQuery object from the form
$form = $(event.target);

// Serialize the form data
var formData = $form.serialize();

// You should sterilise the file names
$.each(data.files, function(key, value)
{
    formData = formData + '&filenames[]=' + value;
});

$.ajax({
    url: 'submit.php',
    type: 'POST',
    data: formData,
    cache: false,
    dataType: 'json',
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            console.log('SUCCESS: ' + data.success);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
    },
    complete: function()
    {
        // STOP LOADING SPINNER
    }
});
}

Final note

This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.

Referenced From

Does Python have an ordered set?

There's no OrderedSet in official library. I make an exhaustive cheatsheet of all the data structure for your reference.

DataStructure = {
    'Collections': {
        'Map': [
            ('dict', 'OrderDict', 'defaultdict'),
            ('chainmap', 'types.MappingProxyType')
        ],
        'Set': [('set', 'frozenset'), {'multiset': 'collection.Counter'}]
    },
    'Sequence': {
        'Basic': ['list', 'tuple', 'iterator']
    },
    'Algorithm': {
        'Priority': ['heapq', 'queue.PriorityQueue'],
        'Queue': ['queue.Queue', 'multiprocessing.Queue'],
        'Stack': ['collection.deque', 'queue.LifeQueue']
        },
    'text_sequence': ['str', 'byte', 'bytearray']
}

Setting WPF image source in code

After having the same problem as you and doing some reading, I discovered the solution - Pack URIs.

I did the following in code:

Image finalImage = new Image();
finalImage.Width = 80;
...
BitmapImage logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png");
logo.EndInit();
...
finalImage.Source = logo;

Or shorter, by using another BitmapImage constructor:

finalImage.Source = new BitmapImage(
    new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png"));

The URI is broken out into parts:

  • Authority: application:///
  • Path: The name of a resource file that is compiled into a referenced assembly. The path must conform to the following format: AssemblyShortName[;Version][;PublicKey];component/Path

    • AssemblyShortName: the short name for the referenced assembly.
    • ;Version [optional]: the version of the referenced assembly that contains the resource file. This is used when two or more referenced assemblies with the same short name are loaded.
    • ;PublicKey [optional]: the public key that was used to sign the referenced assembly. This is used when two or more referenced assemblies with the same short name are loaded.
    • ;component: specifies that the assembly being referred to is referenced from the local assembly.
    • /Path: the name of the resource file, including its path, relative to the root of the referenced assembly's project folder.

The three slashes after application: have to be replaced with commas:

Note: The authority component of a pack URI is an embedded URI that points to a package and must conform to RFC 2396. Additionally, the "/" character must be replaced with the "," character, and reserved characters such as "%" and "?" must be escaped. See the OPC for details.

And of course, make sure you set the build action on your image to Resource.

keycode and charcode

The property event.which is added when using jQuery to avoid browser differences. See docs.

The which property will be undefined if you are not using jQuery.

How to sort by Date with DataTables jquery plugin?

Just in case someone is having trouble where they have blank spaces either in the date values or in cells, you will have to handle those bits. Sometimes an empty space is not handled by trim function coming from html it's like "$nbsp;". If you don't handle these, your sorting will not work properly and will break where ever there is a blank space.

I got this bit of code from jquery extensions here too and changed it a little bit to suit my requirement. You should do the same:) cheers!

function trim(str) {
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}

jQuery.fn.dataTableExt.oSort['uk-date-time-asc'] = function(a, b) {
    if (trim(a) != '' && a!="&nbsp;") {
        if (a.indexOf(' ') == -1) {
            var frDatea = trim(a).split(' ');
            var frDatea2 = frDatea[0].split('/');
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0]) * 1;
        }
        else {
            var frDatea = trim(a).split(' ');
            var frTimea = frDatea[1].split(':');
            var frDatea2 = frDatea[0].split('/');
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
        }
    } else {
        var x = 10000000; // = l'an 1000 ...
    }

    if (trim(b) != '' && b!="&nbsp;") {
        if (b.indexOf(' ') == -1) {
            var frDateb = trim(b).split(' ');
            frDateb = frDateb[0].split('/');
            var y = (frDateb[2] + frDateb[1] + frDateb[0]) * 1;
        }
        else {
            var frDateb = trim(b).split(' ');
            var frTimeb = frDateb[1].split(':');
            frDateb = frDateb[0].split('/');
            var y = (frDateb[2] + frDateb[1] + frDateb[0] + frTimeb[0] + frTimeb[1] + frTimeb[2]) * 1;
        }
    } else {
        var y = 10000000;
    }
    var z = ((x < y) ? -1 : ((x > y) ? 1 : 0));
    return z;
};

jQuery.fn.dataTableExt.oSort['uk-date-time-desc'] = function(a, b) {
    if (trim(a) != '' && a!="&nbsp;") {
        if (a.indexOf(' ') == -1) {
            var frDatea = trim(a).split(' ');
            var frDatea2 = frDatea[0].split('/');
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0]) * 1;
        }
        else {
            var frDatea = trim(a).split(' ');
            var frTimea = frDatea[1].split(':');
            var frDatea2 = frDatea[0].split('/');
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
        }
    } else {
        var x = 10000000;
    }

    if (trim(b) != '' && b!="&nbsp;") {
        if (b.indexOf(' ') == -1) {
            var frDateb = trim(b).split(' ');
            frDateb = frDateb[0].split('/');
            var y = (frDateb[2] + frDateb[1] + frDateb[0]) * 1;
        }
        else {
            var frDateb = trim(b).split(' ');
            var frTimeb = frDateb[1].split(':');
            frDateb = frDateb[0].split('/');
            var y = (frDateb[2] + frDateb[1] + frDateb[0] + frTimeb[0] + frTimeb[1] + frTimeb[2]) * 1;
        }
    } else {
        var y = 10000000;
    }

    var z = ((x < y) ? 1 : ((x > y) ? -1 : 0));
    return z;
};

SQL Server - SELECT FROM stored procedure

You can cheat a little with OPENROWSET :

SELECT ...fieldlist...
FROM OPENROWSET('SQLNCLI', 'connection string', 'name of sp')
WHERE ...

This would still run the entire SP every time, of course.

Count number of objects in list

Advice for R newcomers like me : beware, the following is a list of a single object :

> mylist <- list (1:10)
> length (mylist)
[1] 1

In such a case you are not looking for the length of the list, but of its first element :

> length (mylist[[1]])
[1] 10

This is a "true" list :

> mylist <- list(1:10, rnorm(25), letters[1:3])
> length (mylist)
[1] 3

Also, it seems that R considers a data.frame as a list :

> df <- data.frame (matrix(0, ncol = 30, nrow = 2))
> typeof (df)
[1] "list"

In such a case you may be interested in ncol() and nrow() rather than length() :

> ncol (df)
[1] 30
> nrow (df)
[1] 2

Though length() will also work (but it's a trick when your data.frame has only one column) :

> length (df)
[1] 30
> length (df[[1]])
[1] 2

How to overwrite the previous print to stdout in python?

I couldn't get any of the solutions on this page to work for IPython, but a slight variation on @Mike-Desimone's solution did the job: instead of terminating the line with the carriage return, start the line with the carriage return:

for x in range(10):
    print '\r{0}'.format(x),

Additionally, this approach doesn't require the second print statement.

How store a range from excel into a Range variable?

here is an example that allows for performing code on each line of the desired areas (pick either from top & bottom of selection, of from selection

Sub doROWSb()           'WORKS    for do selected rows     SEE FIX ROWS ABOVE  (small ver)
Dim E7 As String    'note:  workcell E7 shows:  BG381
E7 = RANGE("E7")    'see eg below
Dim r As Long       'NOTE: this example has a paste formula(s) down a column(s).  WILL REDUCE 10 HOUR DAYS OF PASTING COLUMNS, DOWN TO 3 MINUTES?
Dim c As Long
Dim rCell As RANGE
'Dim LastRow As Long
r = ActiveCell.row
c = ActiveCell.Column   'might not matter if your code affects whole line anyways, still leave as is

Dim FirstRow As Long    'not in use, Delete if only want last row, note: this code already allows for selection as start
Dim LastRow As Long


If 1 Then     'if you are unable to delete rows not needed, just change 2 lines from: If 1, to if 0 (to go from selection last row, to all rows down from selection)
With Selection
    'FirstRow = .Rows(1).row                 'not used here, Delete if only want last row
    LastRow = .Rows(.Rows.Count).row        'find last row in selection
End With
application.CutCopyMode = False             'if not doing any paste op below
Else
    LastRow = Cells(Rows.Count, 1).End(xlUp).row  'find last row used in sheet
End If
application.EnableEvents = True             'EVENTS  need this?
application.ScreenUpdating = False          'offset-cells(row, col)
'RANGE(E7).Select  'TOP ROW SELECT
RANGE("A1") = vbNullString                  'simple macros on-off switch, vb not here:  If RANGE("A1").Value > 0 Then


For Each rCell In RANGE(Cells(r, c), Cells(LastRow, c)) 'new
    rCell.Select    'make 3 macros for each paste macro below
'your code here:

If 1 Then     'to if 0, if want to paste formulas/formats/all down a column
    Selection.EntireRow.Calculate     'calcs all selected rows, even if just selecting 1 cell in each row (might only be doing 1 row aat here, as part of loop)
Else
'dorows() DO ROWS()
'eg's for paste cells down a column, can make 3 separate macros for each: sub alte() altf & altp
      Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False    'make sub alte ()    add thisworkbook:  application.OnKey "%{e}", "alte"
      'Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False     'make sub altf ()    add thisworkbook:  application.OnKey "%{f}", "altf"
      'Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=False, Transpose:=False         'amke sub altp ()    add thisworkbook:  application.OnKey "%{p}", "altp"
End If
Next rCell

'application.CutCopyMode = False            'finished - stop copy mode
'RANGE("A2").Select
goBEEPS (2), (0.25)       'beeps secs
application.EnableEvents = True             'EVENTS

'note:  workcell E7 has: SUBSTITUTE(SUBSTITUTE(CELL("address",$BG$369),"$",""),"","")
'other col eg (shows: BG:BG):  =SUBSTITUTE(SUBSTITUTE(CELL("address",$BG2),"$",""),ROW(),"")&":"& SUBSTITUTE(SUBSTITUTE(CELL("address",$BG2),"$",""),ROW(),"")
End Sub


'OTHER:
Sub goBEEPSx(b As Long, t As Double)   'beeps secs as:  goBEEPS (2), (0.25)  OR:  goBEEPS(2, 0.25)
  Dim dt  'as double    'worked wo as double
  Dim x
  For b = b To 1 Step -1
    Beep
    x = Timer
  Do
  DoEvents
  dt = Timer - x
  If dt < 0 Then dt = dt + 86400    '86400 no. seconds in a day, in case hit midnight & timer went down to 0
  Loop Until dt >= t
  Next
End Sub

How to unblock with mysqladmin flush hosts

You should put it into command line in windows.

mysqladmin -u [username] -p flush-hosts
**** [MySQL password]

or

mysqladmin flush-hosts -u [username] -p
**** [MySQL password]

For network login use the following command:

mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts 

you can permanently solution your problem by editing my.ini file[Mysql configuration file] change variables max_connections = 10000;

or

login into MySQL using command line -

mysql -u [username] -p
**** [MySQL password]

put the below command into MySQL window

SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;

check veritable using command-

show variables like "max_connections";
show variables like "max_connect_errors";

How to implement a tree data-structure in Java?

No answer mentions over-simplified but working code, so here it is:

public class TreeNodeArray<T> {
    public T value;
    public final  java.util.List<TreeNodeArray<T>> kids =  new java.util.ArrayList<TreeNodeArray<T>>();
}

How to set a Fragment tag by code?

I know it's been 6 years ago but if anyone is facing the same problem do like I've done:

Create a custom Fragment Class with a tag field:

public class MyFragment extends Fragment {
 private String _myTag;
 public void setMyTag(String value)
 {
   if("".equals(value))
     return;
   _myTag = value;
 }
 //other code goes here
}

Before adding the fragment to the sectionPagerAdapter set the tag just like that:

 MyFragment mfrag= new MyFragment();
 mfrag.setMyTag("TAG_GOES_HERE");
 sectionPagerAdapter.AddFragment(mfrag);

removing table border

border-spacing: 0; should work as well

Ctrl+click doesn't work in Eclipse Juno

I was facing the same issue in eclipse. I verified preferences and build path and also no error. Tried closing and opening the eclipse but nothing worked. Even I could not run debug configuration. I created a new workspace and Ctrl+click / ?+click (Mac os) was working fine.

Hope this may help someone.

How to center the text in PHPExcel merged cell

<?php
    /** Error reporting */
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
    date_default_timezone_set('Europe/London');

    /** Include PHPExcel */
    require_once '../Classes/PHPExcel.php';

    $objPHPExcel = new PHPExcel();
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->setCellValueByColumnAndRow(0, 1, "test");
    $sheet->mergeCells('A1:B1');
    $sheet->getActiveSheet()->getStyle('A1:B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save("test.xlsx");
?>

How to create a custom scrollbar on a div (Facebook style)

If you're looking for a Facebook like scroll bar, then I'd highly recommend you take a look at this one:

http://rocha.la/jQuery-slimScroll

What is the printf format specifier for bool?

ANSI C99/C11 don't include an extra printf conversion specifier for bool.

But the GNU C library provides an API for adding custom specifiers.

An example:

#include <stdio.h>
#include <printf.h>
#include <stdbool.h>

static int bool_arginfo(const struct printf_info *info, size_t n,
    int *argtypes, int *size)
{
  if (n) {
    argtypes[0] = PA_INT;
    *size = sizeof(bool);
  }
  return 1;
}
static int bool_printf(FILE *stream, const struct printf_info *info,
    const void *const *args)
{
  bool b =  *(const bool*)(args[0]);
  int r = fputs(b ? "true" : "false", stream);
  return r == EOF ? -1 : (b ? 4 : 5);
}
static int setup_bool_specifier()
{
  int r = register_printf_specifier('B', bool_printf, bool_arginfo);
  return r;
}
int main(int argc, char **argv)
{
  int r = setup_bool_specifier();
  if (r) return 1;
  bool b = argc > 1;
  r = printf("The result is: %B\n", b);
  printf("(written %d characters)\n", r);
  return 0;
}

Since it is a glibc extensions the GCC warns about that custom specifier:

$ gcc -Wall -g    main.c   -o main
main.c: In function ‘main’:
main.c:34:3: warning: unknown conversion type character ‘B’ in format [-Wformat=]
   r = printf("The result is: %B\n", b);
   ^
main.c:34:3: warning: too many arguments for format [-Wformat-extra-args]

Output:

$ ./main
The result is: false
(written 21 characters)
$ ./main 1
The result is: true
(written 20 characters)

Convert a Unicode string to an escaped ASCII string

Here is my current implementation:

public static class UnicodeStringExtensions
{
    public static string EncodeNonAsciiCharacters(this string value) {
        var bytes = Encoding.Unicode.GetBytes(value);
        var sb = StringBuilderCache.Acquire(value.Length);
        bool encodedsomething = false;
        for (int i = 0; i < bytes.Length; i += 2) {
            var c = BitConverter.ToUInt16(bytes, i);
            if ((c >= 0x20 && c <= 0x7f) || c == 0x0A || c == 0x0D) {
                sb.Append((char) c);
            } else {
                sb.Append($"\\u{c:x4}");
                encodedsomething = true;
            }
        }
        if (!encodedsomething) {
            StringBuilderCache.Release(sb);
            return value;
        }
        return StringBuilderCache.GetStringAndRelease(sb);
    }


    public static string DecodeEncodedNonAsciiCharacters(this string value)
      => Regex.Replace(value,/*language=regexp*/@"(?:\\u[a-fA-F0-9]{4})+", Decode);

    static readonly string[] Splitsequence = new [] { "\\u" };
    private static string Decode(Match m) {
        var bytes = m.Value.Split(Splitsequence, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => ushort.Parse(s, NumberStyles.HexNumber)).SelectMany(BitConverter.GetBytes).ToArray();
        return Encoding.Unicode.GetString(bytes);
    }
}

This passes a test:

public void TestBigUnicode() {
    var s = "\U00020000";
    var encoded = s.EncodeNonAsciiCharacters();
    var decoded = encoded.DecodeEncodedNonAsciiCharacters();
    Assert.Equals(s, decoded);
}

with the encoded value: "\ud840\udc00"

This implementation makes use of a StringBuilderCache (reference source link)

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Open Project properties by selecting project then go to

View>Properties Windows

and make sure Anonymous Authentication is Enabled

enter image description here

How do I retrieve an HTML element's actual width and height?

element.offsetWidth and element.offsetHeight should do, as suggested in previous post.

However, if you just want to center the content, there is a better way of doing so. Assuming you use xhtml strict DOCTYPE. set the margin:0,auto property and required width in px to the body tag. The content gets center aligned to the page.

How to find the sum of an array of numbers

try this...

function arrSum(arr){
    total = 0;  
    arr.forEach(function(key){
        total = total + key;            
    });
    return total;
}

How do I get JSON data from RESTful service using Python?

Well first of all I think rolling out your own solution for this all you need is urllib2 or httplib2 . Anyways in case you do require a generic REST client check this out .

https://github.com/scastillo/siesta

However i think the feature set of the library will not work for most web services because they shall probably using oauth etc .. . Also I don't like the fact that it is written over httplib which is a pain as compared to httplib2 still should work for you if you don't have to handle a lot of redirections etc ..

The type initializer for 'MyClass' threw an exception

This can happen if you have a dependency property that is registered to the wrong owner type (ownerType argument).

Notice SomeOtherControl should have been YourControl.

public partial class YourControl
{
    public bool Enabled
    {
        get { return (bool)GetValue(EnabledProperty);   }
        set { SetValue(EnabledProperty, value); }
    }
    public static readonly DependencyProperty EnabledProperty =
        DependencyProperty.Register(nameof(Enabled), typeof(bool), typeof(SomeOtherControl), new PropertyMetadata(false));
}

Difference between if () { } and if () : endif;

At our company, the preferred way for handling HTML is:

<? if($condition) { ?>
   HTML content here
<? } else { ?>
   Other HTML content here
<? } ?>

In the end, it really is a matter of choosing one and sticking with it.

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

sqlcmd works, System.Data.SqlClient not working - Server not found in Kerberos database. You should add RestrictedKrbHost SPN

https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-kile/445e4499-7e49-4f2a-8d82-aaf2d1ee3c47

5.1.2 SPNs with Serviceclass Equal to "RestrictedKrbHost"

Supporting the "RestrictedKrbHost" service class allows client applications to use Kerberos authentication when they do not have the identity of the service but have the server name. This does not provide client-to-service mutual authentication, but rather client-to-server computer authentication. Services of different privilege levels have the same session key and could decrypt each other's data if the underlying service does not ensure that data cannot be accessed by higher services.

SimpleXml to string

You can use the SimpleXMLElement::asXML() method to accomplish this:

$string = "<element><child>Hello World</child></element>";
$xml = new SimpleXMLElement($string);

// The entire XML tree as a string:
// "<element><child>Hello World</child></element>"
$xml->asXML();

// Just the child node as a string:
// "<child>Hello World</child>"
$xml->child->asXML();

How to create a HTTP server in Android?

Consider this one: https://github.com/NanoHttpd/nanohttpd. Very small, written in Java. I used it without any problem.

Calling a class function inside of __init__

How about:

class MyClass(object):
    def __init__(self, filename):
        self.filename = filename 
        self.stats = parse_file(filename)

def parse_file(filename):
    #do some parsing
    return results_from_parse

By the way, if you have variables named stat1, stat2, etc., the situation is begging for a tuple: stats = (...).

So let parse_file return a tuple, and store the tuple in self.stats.

Then, for example, you can access what used to be called stat3 with self.stats[2].

Android scale animation on view

Here is a code snip to do exactly that.

public void scaleView(View v, float startScale, float endScale) {
    Animation anim = new ScaleAnimation(
            1f, 1f, // Start and end values for the X axis scaling
            startScale, endScale, // Start and end values for the Y axis scaling
            Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
            Animation.RELATIVE_TO_SELF, 1f); // Pivot point of Y scaling
    anim.setFillAfter(true); // Needed to keep the result of the animation
    anim.setDuration(1000);
    v.startAnimation(anim);
}

The ScaleAnimation constructor used here takes 8 args, 4 related to handling the X-scale which we don't care about (1f, 1f, ... Animation.RELATIVE_TO_SELF, 0f, ...).

The other 4 args are for the Y-scaling we do care about.

startScale, endScale - In your case, you'd use 0f, 0.6f.

Animation.RELATIVE_TO_SELF, 1f - This specifies where the shrinking of the view collapses to (referred to as the pivot in the documentation). Here, we set the float value to 1f because we want the animation to start growing the bar from the bottom. If we wanted it to grow downward from the top, we'd use 0f.

Finally, and equally important, is the call to anim.setFillAfter(true). If you want the result of the animation to stick around after the animation completes, you must run this on the animator before executing the animation.

So in your case, you can do something like this:

View v = findViewById(R.id.viewContainer);
scaleView(v, 0f, .6f);

Break a previous commit into multiple commits

Previous answers have covered the use of git rebase -i to edit the commit that you want to split, and committing it in parts.

This works well when splitting the files into different commits, but if you want to break apart changes to the individual files, there's more you need to know.

Having got to the commit you want to split, using rebase -i and marking it for edit, you have two options.

  1. After using git reset HEAD~, go through the patches individually using git add -p to select the ones you want in each commit

  2. Edit the working copy to remove the changes you do not want; commit that interim state; and then pull back the full commit for the next round.

Option 2 is useful if you're splitting a large commit, as it lets you check that the interim versions build and run properly as part of the merge. This proceeds as follows.

After using rebase -i and editing the commit, use

git reset --soft HEAD~

to undo the commit, but leave the committed files in the index. You can also do a mixed reset by omitting --soft, depending on how close to the final result your initial commit is going to be. The only difference is whether you start with all the changes staged or with them all unstaged.

Now go in and edit the code. You can remove changes, delete added files, and do whatever you want to construct the first commit of the series you're looking for. You can also build it, run it, and confirm that you have a consistent set of source.

Once you're happy, stage/unstage the files as needed (I like to use git gui for this), and commit the changes through the UI or the command line

git commit

That's the first commit done. Now you want to restore your working copy to the state it had after the commit you are splitting, so that you can take more of the changes for your next commit. To find the sha1 of the commit you're editing, use git status. In the first few lines of the status you'll see the rebase command that is currently executing, in which you can find the sha1 of your original commit:

$ git status
interactive rebase in progress; onto be83b41
Last commands done (3 commands done):
   pick 4847406 US135756: add debugging to the file download code
   e 65dfb6a US135756: write data and download from remote
  (see more in file .git/rebase-merge/done)
...

In this case, the commit I'm editing has sha1 65dfb6a. Knowing that, I can check out the content of that commit over my working directory using the form of git checkout which takes both a commit and a file location. Here I use . as the file location to replace the whole working copy:

git checkout 65dfb6a .

Don't miss the dot on the end!

This will check out, and stage, the files as they were after the commit you're editing, but relative to the previous commit you made, so any changes you already committed won't be part of the commit.

You can either go ahead now and commit it as-is to finish the split, or go around again, deleting some parts of the commit before making another interim commit.

If you want to reuse the original commit message for one or more commits, you can use it straight from the rebase's working files:

git commit --file .git/rebase-merge/message

Finally, once you've committed all the changes,

git rebase --continue

will carry on and complete the rebase operation.

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

You can use ax.figure.savefig(), as suggested in a comment on the question:

import pandas as pd

df = pd.DataFrame([0, 1])
ax = df.plot.line()
ax.figure.savefig('demo-file.pdf')

This has no practical benefit over ax.get_figure().savefig() as suggested in other answers, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure() simply returns self.figure:

# Source from snippet linked above
def get_figure(self):
    """Return the `.Figure` instance the artist belongs to."""
    return self.figure

Media Player called in state 0, error (-38,0)

i tested below code. working fine

public class test extends Activity implements OnErrorListener, OnPreparedListener {

private MediaPlayer player;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    player = new MediaPlayer();
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        player.setDataSource("http://www.hubharp.com/web_sound/BachGavotte.mp3");
        player.setOnErrorListener(this);
        player.setOnPreparedListener(this);
        player.prepareAsync();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }       
}
@Override
public void onDestroy() {
    super.onDestroy();
    player.release();
    player = null;
}
@Override
public void onPrepared(MediaPlayer play) {
    play.start();
}
@Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
    return false;
}
}

Print all day-dates between two dates

Essentially the same as Gringo Suave's answer, but with a generator:

from datetime import datetime, timedelta


def datetime_range(start=None, end=None):
    span = end - start
    for i in xrange(span.days + 1):
        yield start + timedelta(days=i)

Then you can use it as follows:

In: list(datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)))
Out: 
[datetime.datetime(2014, 1, 1, 0, 0),
 datetime.datetime(2014, 1, 2, 0, 0),
 datetime.datetime(2014, 1, 3, 0, 0),
 datetime.datetime(2014, 1, 4, 0, 0),
 datetime.datetime(2014, 1, 5, 0, 0)]

Or like this:

In []: for date in datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)):
   ...:     print date
   ...:     
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
2014-01-04 00:00:00
2014-01-05 00:00:00

Remove HTML tags from a String

I think that the simpliest way to filter the html tags is:

private static final Pattern REMOVE_TAGS = Pattern.compile("<.+?>");

public static String removeTags(String string) {
    if (string == null || string.length() == 0) {
        return string;
    }

    Matcher m = REMOVE_TAGS.matcher(string);
    return m.replaceAll("");
}

Convert xlsx to csv in Linux with command line

As others said, libreoffice can convert xls files to csv. The problem for me was the sheet selection.

This libreoffice Python script does a fine job at converting a single sheet to CSV.

Usage is:

./libreconverter.py File.xls:"Sheet Name" output.csv

The only downside (on my end) is that --headless doesn't seem to work. I have a LO window that shows up for a second and then quits.
That's OK with me, it's the only tool that does the job rapidly.

Get a CSS value with JavaScript

As a matter of safety, you may wish to check that the element exists before you attempt to read from it. If it doesn't exist, your code will throw an exception, which will stop execution on the rest of your JavaScript and potentially display an error message to the user -- not good. You want to be able to fail gracefully.

var height, width, top, margin, item;
item = document.getElementById( "image_1" );
if( item ) {
  height = item.style.height;
  width = item.style.width;
  top = item.style.top;
  margin = item.style.margin;
} else {
  // Fail gracefully here
}

CSS way to horizontally align table

style="text-align:center;" 

(i think)

or you could just ignore it, it still works

How to get MD5 sum of a string using python?

Use hashlib.md5 in Python 3.

import hashlib

source = '000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite'.encode()
md5 = hashlib.md5(source).hexdigest() # returns a str
print(md5) # a02506b31c1cd46c2e0b6380fb94eb3d

If you need byte type output, use digest() instead of hexdigest().

How do I exclude all instances of a transitive dependency when using Gradle?

Your approach is correct. (Depending on the circumstances, you might want to use configurations.all { exclude ... }.) If these excludes really exclude more than a single dependency (I haven't ever noticed that when using them), please file a bug at http://forums.gradle.org, ideally with a reproducible example.

Is it possible to decompile an Android .apk file?

Decompilation of APK file is possible. But it might be difficult to understand the code if it is obfuscated.

ApkTool to view resources inside APK File

  • Extracts AndroidManifest.xml and everything in res folder(layout xml files, images, htmls used on webview etc..)
  • command : apktool.bat d sampleApp.apk
  • NOTE: You can achieve this by using zip utility like 7-zip. But, It also extracts the .smali file of all .class files.

Using dex2jar

  • Generates .jar file from .apk file, we need JD-GUI to view the source code from this .jar.
  • command : dex2jar sampleApp.apk

Decompiling .jar using JD-GUI

  • decompiles the .class files (obfuscated- in a case of the android app, but a readable original code is obtained in a case of other .jar file). i.e., we get .java back from the application.

Plot two graphs in same plot in R

tl;dr: You want to use curve (with add=TRUE) or lines.


I disagree with par(new=TRUE) because that will double-print tick-marks and axis labels. Eg

sine and parabola

The output of plot(sin); par(new=T); plot( function(x) x**2 ).

Look how messed up the vertical axis labels are! Since the ranges are different you would need to set ylim=c(lowest point between the two functions, highest point between the two functions), which is less easy than what I'm about to show you---and way less easy if you want to add not just two curves, but many.


What always confused me about plotting is the difference between curve and lines. (If you can't remember that these are the names of the two important plotting commands, just sing it.)

Here's the big difference between curve and lines.

curve will plot a function, like curve(sin). lines plots points with x and y values, like: lines( x=0:10, y=sin(0:10) ).

And here's a minor difference: curve needs to be called with add=TRUE for what you're trying to do, while lines already assumes you're adding to an existing plot.

id & sine

Here's the result of calling plot(0:2); curve(sin).


Behind the scenes, check out methods(plot). And check body( plot.function )[[5]]. When you call plot(sin) R figures out that sin is a function (not y values) and uses the plot.function method, which ends up calling curve. So curve is the tool meant to handle functions.

How do I fix the indentation of an entire file in Vi?

1G=G. That should indent all the lines in the file. 1G takes you the first line, = will start the auto-indent and the final G will take you the last line in the file.

Pandas groupby: How to get a union of strings

In [4]: df = read_csv(StringIO(data),sep='\s+')

In [5]: df
Out[5]: 
   A         B       C
0  1  0.749065    This
1  2  0.301084      is
2  3  0.463468       a
3  4  0.643961  random
4  1  0.866521  string
5  2  0.120737       !

In [6]: df.dtypes
Out[6]: 
A      int64
B    float64
C     object
dtype: object

When you apply your own function, there is not automatic exclusions of non-numeric columns. This is slower, though, than the application of .sum() to the groupby

In [8]: df.groupby('A').apply(lambda x: x.sum())
Out[8]: 
   A         B           C
A                         
1  2  1.615586  Thisstring
2  4  0.421821         is!
3  3  0.463468           a
4  4  0.643961      random

sum by default concatenates

In [9]: df.groupby('A')['C'].apply(lambda x: x.sum())
Out[9]: 
A
1    Thisstring
2           is!
3             a
4        random
dtype: object

You can do pretty much what you want

In [11]: df.groupby('A')['C'].apply(lambda x: "{%s}" % ', '.join(x))
Out[11]: 
A
1    {This, string}
2           {is, !}
3               {a}
4          {random}
dtype: object

Doing this on a whole frame, one group at a time. Key is to return a Series

def f(x):
     return Series(dict(A = x['A'].sum(), 
                        B = x['B'].sum(), 
                        C = "{%s}" % ', '.join(x['C'])))

In [14]: df.groupby('A').apply(f)
Out[14]: 
   A         B               C
A                             
1  2  1.615586  {This, string}
2  4  0.421821         {is, !}
3  3  0.463468             {a}
4  4  0.643961        {random}

Reading data from DataGridView in C#

string[,] myGridData = new string[dataGridView1.Rows.Count,3];

int i = 0;

foreach(DataRow row in dataGridView1.Rows)

{

    myGridData[i][0] = row.Cells[0].Value.ToString();
    myGridData[i][1] = row.Cells[1].Value.ToString();
    myGridData[i][2] = row.Cells[2].Value.ToString();

    i++;
}

Hope this helps....

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

go to "Project-Properties-Configuration Properties-Linker-input-Additional dependencies" then go to the end and type ";ws2_32.lib".

Python 3 ImportError: No module named 'ConfigParser'

I still have this issue, so I go to /usr/lib/python3.8 and type as sudoer:

cp configparser.py ConfigParser.py

You may have another python version than 3.8.

ActionBarActivity cannot resolve a symbol

Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.

Why can't Python parse this JSON data?

If you're using Python3, you can try changing your (connection.json file) JSON to:

{
  "connection1": {
    "DSN": "con1",
    "UID": "abc",
    "PWD": "1234",
    "connection_string_python":"test1"
  }
  ,
  "connection2": {
    "DSN": "con2",
    "UID": "def",
    "PWD": "1234"
  }
}

Then using the following code:

connection_file = open('connection.json', 'r')
conn_string = json.load(connection_file)
conn_string['connection1']['connection_string_python'])
connection_file.close()
>>> test1

How do I make a simple crawler in PHP?

I created a small class to grab data from the provided url, then extract html elements of your choice. The class makes use of CURL and DOMDocument.

php class:

class crawler {


   public static $timeout = 2;
   public static $agent   = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';


   public static function http_request($url) {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL,            $url);
      curl_setopt($ch, CURLOPT_USERAGENT,      self::$agent);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$timeout);
      curl_setopt($ch, CURLOPT_TIMEOUT,        self::$timeout);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      $response = curl_exec($ch);
      curl_close($ch);
      return $response;
   }


   public static function strip_whitespace($data) {
      $data = preg_replace('/\s+/', ' ', $data);
      return trim($data);
   }


   public static function extract_elements($tag, $data) {
      $response = array();
      $dom      = new DOMDocument;
      @$dom->loadHTML($data);
      foreach ( $dom->getElementsByTagName($tag) as $index => $element ) {
         $response[$index]['text'] = self::strip_whitespace($element->nodeValue);
         foreach ( $element->attributes as $attribute ) {
            $response[$index]['attributes'][strtolower($attribute->nodeName)] = self::strip_whitespace($attribute->nodeValue);
         }
      }
      return $response;
   }


}

example usage:

$data  = crawler::http_request('https://stackoverflow.com/questions/2313107/how-do-i-make-a-simple-crawler-in-php');
$links = crawler::extract_elements('a', $data);
if ( count($links) > 0 ) {
   file_put_contents('links.json', json_encode($links, JSON_PRETTY_PRINT));
}

example response:

[
    {
        "text": "Stack Overflow",
        "attributes": {
            "href": "https:\/\/stackoverflow.com",
            "class": "-logo js-gps-track",
            "data-gps-track": "top_nav.click({is_current:false, location:2, destination:8})"
        }
    },
    {
        "text": "Questions",
        "attributes": {
            "id": "nav-questions",
            "href": "\/questions",
            "class": "-link js-gps-track",
            "data-gps-track": "top_nav.click({is_current:true, location:2, destination:1})"
        }
    },
    {
        "text": "Developer Jobs",
        "attributes": {
            "id": "nav-jobs",
            "href": "\/jobs?med=site-ui&ref=jobs-tab",
            "class": "-link js-gps-track",
            "data-gps-track": "top_nav.click({is_current:false, location:2, destination:6})"
        }
    }
]

How do you check that a number is NaN in JavaScript?

It seems that isNaN() is not supported in Node.js out of the box.
I worked around with

var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);

MySQL table is marked as crashed and last (automatic?) repair failed

This is a 100% solution. I tried it myself.

myisamchk -r -v -f --sort_buffer_size=128M --key_buffer_size=128M /var/lib/mysql/databasename/tabloname

Why do we assign a parent reference to the child object in Java?

for example we have a

class Employee

{

int getsalary()

{return 0;}

String getDesignation()

{

return “default”;

}

}

class Manager extends Employee

{

int getsalary()

{

return 20000;

}

String getDesignation()

{

return “Manager”

}

}

class SoftwareEngineer extends Employee

{

int getsalary()

{

return 20000;

}

String getDesignation()

{

return “Manager”

}

}

now if you want to set or get salary and designation of all employee (i.e software enginerr,manager etc )

we will take an array of Employee and call both method getsalary(),getDesignation

Employee arr[]=new Employee[10];

arr[1]=new SoftwareEngieneer();

arr[2]=new Manager();

arr[n]=…….

for(int i;i>arr.length;i++)

{

System.out.println(arr[i].getDesignation+””+arr[i].getSalary())

}

now its an kind of loose coupling because you can have different types of employees ex:softeware engineer,manager,hr,pantryEmployee etc

so you can give object to the parent reference irrespective of different employee object

How to output to the console in C++/Windows

Whether to use subsystem:console or subsystem:windows kind of depends on whether how you want to start your application:

  • If you use subsystem:console, then you get all of the stdout written to the terminal. The trouble is that if you start the application from the Start Menu/Desktop, you (by default) get a console appearing as well as the application window (which can look pretty ugly).
  • If you use subsystem:windows, you won't get stdout/stderr even if you run the application from a DOS window, Cygwin, or other terminal.

If you want the middle way which is to output to the terminal IF the application was started in a terminal, then follow the link that Luke provided in his solution (http://dslweb.nwnexus.com/~ast/dload/guicon.htm)

For reference, I ran into this problem with an application that I want to run in either normal Windows mode or batch mode (that is, as part of a script) depending on command-line switches. The whole differentiation between console and Windows applications is a bit bizarre to Unix folks!

How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project

You'll need AJAX if you want to update a part of your page without reloading the entire page.

main cshtml view

<div id="refTable">
     <!-- partial view content will be inserted here -->
</div>

@Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());
<button id="pY">PrevY</button>

<script>
    $(document).ready(function() {
        $("#pY").on("click", function() {
            var val = $('#yearSelect3').val();
            $.ajax({
                url: "/Holiday/Calendar",
                type: "GET",
                data: { year: ((val * 1) + 1) }
            })
            .done(function(partialViewResult) {
                $("#refTable").html(partialViewResult);
            });
        });
    });
</script>

You'll need to add the fields I have omitted. I've used a <button> instead of submit buttons because you don't have a form (I don't see one in your markup) and you just need them to trigger javascript on the client side.

The HolidayPartialView gets rendered into html and the jquery done callback inserts that html fragment into the refTable div.

HolidayController Update action

[HttpGet]
public ActionResult Calendar(int year)
{
    var dates = new List<DateTime>() { /* values based on year */ };
    HolidayViewModel model = new HolidayViewModel {
        Dates = dates
    };
    return PartialView("HolidayPartialView", model);
}

This controller action takes the year parameter and returns a list of dates using a strongly-typed view model instead of the ViewBag.

view model

public class HolidayViewModel
{
    IEnumerable<DateTime> Dates { get; set; }
}

HolidayPartialView.csthml

@model Your.Namespace.HolidayViewModel;

<table class="tblHoliday">
    @foreach(var date in Model.Dates)
    {
        <tr><td>@date.ToString("MM/dd/yyyy")</td></tr>
    }
</table>

This is the stuff that gets inserted into your div.

What charset does Microsoft Excel use when saving files?

I had a similar problem last week. I received a number of CSV files with varying encodings. Before importing into the database I then used the chardet libary to automatically sniff out the correct encoding.

Chardet is a port from Mozillas character detection engine and if the sample size is large enough (one accentuated character will not do) works really well.

HTML/CSS - Adding an Icon to a button

Here's what you can do using font-awesome library.

_x000D_
_x000D_
button.btn.add::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f067\00a0";_x000D_
}_x000D_
_x000D_
button.btn.edit::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f044\00a0";_x000D_
}_x000D_
_x000D_
button.btn.save::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00c\00a0";_x000D_
}_x000D_
_x000D_
button.btn.cancel::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00d\00a0";_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!--FA unicodes here: http://astronautweb.co/snippet/font-awesome/-->_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>
_x000D_
_x000D_
_x000D_

Fiddle here.

How to inherit constructors?

Another simple solution could be to use a structure or simple data class that contains the parameters as properties; that way you can have all the default values and behaviors set up ahead of time, passing the "parameter class" in as the single constructor parameter:

public class FooParams
{
    public int Size...
    protected myCustomStruct _ReasonForLife ...
}
public class Foo
{
    private FooParams _myParams;
    public Foo(FooParams myParams)
    {
          _myParams = myParams;
    }
}

This avoids the mess of multiple constructors (sometimes) and gives strong typing, default values, and other benefits not provided by a parameter array. It also makes it easy to carry forward since anything that inherits from Foo can still get to, or even add to, FooParams as needed. You still need to copy the constructor, but you always (most of the time) only (as a general rule) ever (at least, for now) need one constructor.

public class Bar : Foo
{
    public Bar(FooParams myParams) : base(myParams) {}
}

I really like the overloaded Initailize() and Class Factory Pattern approaches better, but sometimes you just need to have a smart constructor. Just a thought.

Pretty git branch graphs

I wrote a web tool for converting git logs into pretty SVG graphs: Bit-Booster - Offline Commit Graph Drawing Tool

Upload output from git log --pretty='%h|%p|%d' directly into the tool and then click on the "download graph.svg" link.

The tool is pure-client-side, and so none of your Git data is shared with my server. You can also save the HTML + JS locally and run it using "file:///" URL's. Verified on Chrome 48 and Firefox 43 on Ubuntu 12.04.

It generates HTML that can be posted directly into any page (including the blogspot blogging engine!). Take a look at some of the blog posts here:

http://bit-booster.blogspot.ca/

Here's a screenshot of a sample HTML file generated by the tool:

http://bit-booster.com/graph.html (the tool)

How to "select distinct" across multiple data frame columns in pandas?

I've tried different solutions. First was:

a_df=np.unique(df[['col1','col2']], axis=0)

and it works well for not object data Another way to do this and to avoid error (for object columns type) is to apply drop_duplicates()

a_df=df.drop_duplicates(['col1','col2'])[['col1','col2']]

You can also use SQL to do this, but it worked very slow in my case:

from pandasql import sqldf
q="""SELECT DISTINCT col1, col2 FROM df;"""
pysqldf = lambda q: sqldf(q, globals())
a_df = pysqldf(q)

Get file name from a file location in Java

Apache Commons IO provides the FilenameUtils class which gives you a pretty rich set of utility functions for easily obtaining the various components of filenames, although The java.io.File class provides the basics.

Biggest advantage to using ASP.Net MVC vs web forms

Web forms also gain from greater maturity and support from third party control providers like Telerik.

What is the meaning of prepended double colon "::"?

The :: operator is called the scope-resolution operator and does just that, it resolves scope. So, by prefixing a type-name with this, it tells your compiler to look in the global namespace for the type.

Example:

int count = 0;

int main(void) {
  int count = 0;
  ::count = 1;  // set global count to 1
  count = 2;    // set local count to 2
  return 0;
}

JavaScript - get the first day of the week from current date

setDate() has issues with month boundaries that are noted in comments above. A clean workaround is to find the date difference using epoch timestamps rather than the (surprisingly counterintuitive) methods on the Date object. I.e.

function getPreviousMonday(fromDate) {
    var dayMillisecs = 24 * 60 * 60 * 1000;

    // Get Date object truncated to date.
    var d = new Date(new Date(fromDate || Date()).toISOString().slice(0, 10));

    // If today is Sunday (day 0) subtract an extra 7 days.
    var dayDiff = d.getDay() === 0 ? 7 : 0;

    // Get date diff in millisecs to avoid setDate() bugs with month boundaries.
    var mondayMillisecs = d.getTime() - (d.getDay() + dayDiff) * dayMillisecs;

    // Return date as YYYY-MM-DD string.
    return new Date(mondayMillisecs).toISOString().slice(0, 10);
}

How to change TextField's height and width?

To adjust the width, you could wrap your TextField with a Container widget, like so:

Container(              
  width: 100.0,
  child: TextField()
)

I'm not really sure what you're after when it comes to the height of the TextField but you could definitely have a look at the TextStyle widget, with which you can manipulate the fontSize and/or height

Container(              
  width: 100.0,
  child: TextField(                                 
    style: TextStyle(
      fontSize: 40.0,
      height: 2.0,
      color: Colors.black                  
    )
  )
)

Bear in mind that the height in the TextStyle is a multiplier of the font size, as per comments on the property itself:

The height of this text span, as a multiple of the font size.

When [height] is null or omitted, the line height will be determined by the font's metrics directly, which may differ from the fontSize. When [height] is non-null, the line height of the span of text will be a multiple of [fontSize] and be exactly fontSize * height logical pixels tall.

Last but not least, you might want to have a look at the decoration property of you TextField, which gives you a lot of possibilities

EDIT: How to change the inner padding/margin of the TextField

You could play around with the InputDecoration and the decoration property of the TextField. For instance, you could do something like this:

TextField(                                
    decoration: const InputDecoration(
        contentPadding: const EdgeInsets.symmetric(vertical: 40.0),
    )
)

OpenCV in Android Studio

This worked for me and was as easy as adding a gradle dependancy:

https://bintray.com/seesaa/maven/opencv#

https://github.com/seesaa/opencv-android

The one caveat being that I had to use a hardware debugging device as arm emulators were running too slow for me (as AVD Manager says they will), and, as described at the repo README, this version does not include x86 or x86_64 support.

It seems to build and the suggested test:

static {
    OpenCVLoader.initDebug();
}

spits out a bunch of output that looks about right to me.

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

Solved it by setting workspace on a local folder, and set data from import project, from existing resources.

OnItemCLickListener not working in listview

The problem is that your layouts contain either focusable or clickable items. If a view contains either focusable or clickable item the OnItemCLickListener won't be called.

Click here for more information.

Please post one of your layout xmls if that isn't the case.

paint() and repaint() in Java

The paint() method supports painting via a Graphics object.

The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

Exclude property from type

I do like that:

interface XYZ {
  x: number;
  y: number;
  z: number;
}
const a:XYZ = {x:1, y:2, z:3};
const { x, y, ...last } = a;
const { z, ...firstTwo} = a;
console.log(firstTwo, last);

Deserialize from string instead TextReader

1-liner, takes a XML string text and YourType as the expected object type. not very different from other answers, just compressed to 1 line:

var result =  (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));

Android: adbd cannot run as root in production builds

The problem is that, even though your phone is rooted, the 'adbd' server on the phone does not use root permissions. You can try to bypass these checks or install a different adbd on your phone or install a custom kernel/distribution that includes a patched adbd.

Or, a much easier solution is to use 'adbd insecure' from chainfire which will patch your adbd on the fly. It's not permanent, so you have to run it before starting up the adb server (or else set it to run every boot). You can get the app from the google play store for a couple bucks:

https://play.google.com/store/apps/details?id=eu.chainfire.adbd&hl=en

Or you can get it for free, the author has posted a free version on xda-developers:

http://forum.xda-developers.com/showthread.php?t=1687590

Install it to your device (copy it to the device and open the apk file with a file manager), run adb insecure on the device, and finally kill the adb server on your computer:

% adb kill-server

And then restart the server and it should already be root.

How to embed matplotlib in pyqt - for Dummies

It is not that complicated actually. Relevant Qt widgets are in matplotlib.backends.backend_qt4agg. FigureCanvasQTAgg and NavigationToolbar2QT are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple example with a Figure, Navigation and a single button that draws some random data. I've added comments to explain things.

import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

import random

class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QtGui.QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.clear()

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

Edit:

Updated to reflect comments and API changes.

  • NavigationToolbar2QTAgg changed with NavigationToolbar2QT
  • Directly import Figure instead of pyplot
  • Replace deprecated ax.hold(False) with ax.clear()

UnicodeDecodeError, invalid continuation byte

If this error arises when manipulating a file that was just opened, check to see if you opened it in 'rb' mode