Programs & Examples On #Qsa

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

How to convert JSON object to an Typescript array?

That's correct, your response is an object with fields:

{
    "page": 1,
    "results": [ ... ]
}

So you in fact want to iterate the results field only:

this.data = res.json()['results'];

... or even easier:

this.data = res.json().results;

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

I was getting a 403 on HEAD requests while the GET requests were working. It turned out to be the CORS config in s3 permissions. I had to add HEAD

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

Solved this by adding following

RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
 RewriteCond %{REQUEST_FILENAME} -f [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^ - [L]

json: cannot unmarshal object into Go value of type

Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR

The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.

For example:

{ "things": ["a", "b", "c"] }

Would Unmarshal into a:

type Item struct {
    Things []string
}

And not into:

type Item struct {
    Things string
}

The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int or float field -- "1" needs to Unmarshal into a string, not into an int like we saw with ShippingAdditionalCost int

.htaccess not working on localhost with XAMPP

Just had a similar issue

Resolved it by checking in httpd.conf

     # AllowOverride controls what directives may be placed in .htaccess files.
     # It can be "All", "None", or any combination of the keywords:
     #   Options FileInfo AuthConfig Limit
     #
     AllowOverride All   <--- make sure this is not set to "None"

It is worth bearing in mind I tried (from Mark's answer) the "put garbage in the .htaccess" which did give a server error - but even though it was being read, it wasn't being acted on due to no overrides allowed.

Request exceeded the limit of 10 internal redirects due to probable configuration error

I just found a solution to the problem here:

http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/

The .htaccess file in webroot should look like:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

instead of this:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /projectname
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

enable cors in .htaccess

Thanks to Devin, I figured out the solution for my SLIM application with multi domain access.

In htaccess:

SetEnvIf Origin "http(s)?://(www\.)?(allowed.domain.one|allowed.domain.two)$" AccessControlAllowOrigin=$0$1
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header set Access-Control-Allow-Credentials true

in index.php

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
// instead of mapping:
$app->options('/(:x+)', function() use ($app) {
    //...return correct headers...
    $app->response->setStatus(200);
});

What does $1 [QSA,L] mean in my .htaccess file?

This will capture requests for files like version, release, and README.md, etc. which should be treated either as endpoints, if defined (as in the case of /release), or as "not found."

Header set Access-Control-Allow-Origin in .htaccess doesn't work

I have a shared hosting on GoDaddy. I needed an answer to this question, too, and after searching around I found that it is possible.

I wrote an .htaccess file, put it in the same folder as my action page. Here are the contents of the .htaccess file:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Here is my ajax call:

    $.ajax({
        url: 'http://www.mydomain.com/myactionpagefolder/gbactionpage.php',  //server script to process data
        type: 'POST',
        xhr: function() {  // custom xhr
            myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
            }
            return myXhr;
        },
        //Ajax events
        beforeSend: beforeSendHandler,
        success: completeHandler,
        error: errorHandler,
        // Form data
        data: formData,
        //Options to tell JQuery not to process data or worry about content-type
        cache: false,
        contentType: false,
        processData: false
    });

See this article for reference:

Header set Access-Control-Allow-Origin in .htaccess doesn't work

How to check whether mod_rewrite is enable on server?

I was having the exact problem, I solved it by clicking custom structure, then adding /index.php/%postname%/ and it works

Hope this saves someone the stress that I went through finding what the heck was wrong with it.

what does this mean ? image/png;base64?

They serve the actual image inside CSS so there will be less HTTP requests per page.

jquery get all input from specific form

To iterate through all the inputs in a form you can do this:

$("form#formID :input").each(function(){
 var input = $(this); // This is the jquery object of the input, do what you will
});

This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :

$("form#formID input[type=text]")//...

etc.

CodeIgniter 404 Page Not Found, but why?

Leaving this answer here for others who ran into my situation.

My codeigniter app was working fine in localhost/WAMP, but was unable to route and produced 404 not found errors when pushing to an AWS EC2 instance. My issue was solved from the answer from HERE htaccess works in localhost but doesn't work in EC2 instance

(route to my admin page) {domain}/admin was producing 404

the /etc/httpd/conf/httpd.conf file needs to be modified.

-after every instance of "DocumentRoot "/var/www/html"" (2 places) "AllowOverride None" needed to be changed to "AllowOverride All".

Restarted the EC2 instance from the AWS dashboard.

{domain}/admin is now accessible and working as intended.

hope this helps someone else like it helped me!

Python base64 data decode

Well, I assume you are not on Interactive Mode and you used this code to decode your string:

import base64
your_string = 'Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YHcAAAAABDlgeCAAAAAEOWB5QAAAAAQ5YHpkNx8H9Dlge4REqBx0OWB8pEpZ10Q5YH3ES2lxFDlgfuRIuPbEOWB/9EA9SqQ5YIEUIFJtxDlggjAAAAAEOWCDVDDMm3Q5YIR0N5wOtDlghZQ4GkeEOWCGtDD0CbQ5YIfQAAAABDlgiOAAAAAEOWCKAAAAAAQ5YIsgAAAABDlob5AAAAAEOWhwsAAAAAQ5aHHQAAAABDlocvAAAAAEOWh0FBC+dQQ5aHU0NJ9WdDlodlQ9RK6kOWh3dEDRdFQ5aHiUQARjZDloebQ5xn3kOWh61C1TYMQ5aHvwAAAABDlofRAAAAAEOWh+MAAAAAQ5aH9QAAAABDnFl9AAAAAEOcWZAAAAAAQ5xZpAAAAABDnFm3AAAAAEOcWctDH72jQ5xZ3kNDentDnFnxQ0QCp0OcWgVDK52XQ5xaGEMDUuNDnFosAAAAAEOcWj8AAAAAQ5xaUwAAAABDnFpmAAAAAEOcWnkAAAAAQ5xajQAAAABDnFqgAAAAAEOcWrRBnlHwQ5xax0MvOY9DnFraQ6AiZkOcWu5DquEAQ5xbAUNtwQNDnFsVQqVdQEOcWygAAAAAQ5xbPAAAAABDnFtPAAAAAEOc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K9GuBERY9WQ2Ml50RFj5RDoK7UREWP0kOl+WhERZAQQ22uP0RFkE5Coc28REWQjAAAAABERZDKAAAAAERFkQgAAAAAREWRRgAAAABER8aUAAAAAERHxtQAAAAAREfHEwAAAABER8dTAAAAAERHx5JDh8FaREfH0UO9DJBER8gRQ9bfKERHyFBDzkoWREfIkEOuMHxER8jPAAAAAERHyQ4AAAAAREfJTgAAAABER8mNAAAAAERIbk4AAAAAREhujgAAAABESG7OAAAAAERIbw4AAAAAREhvTkMM9UlESG+NQ083Y0RIb81DOgL9REhwDUK2XghESHBNAAAAAERIcI0AAAAAREhwzQAAAABESHEMAAAAAERKh+IAAAAAREqIIwAAAABESohkAAAAAERKiKYAAAAAREqI50Lh96RESokoQ35MV0RKiWlDnMTYREqJqkNxeg9ESonrQr2M/kRKii0AAAAAREqKbgAAAABESoqvAAAAAERKivAAAAAAREvFtwAAAABES8X5AAAAAERLxjsAAAAAREvGfQAAAABES8a/QwTfiURLxwFDcL+ZREvHQ0OJfrJES8eFQ2HTSURLx8dDAQzpREvICQAAAABES8hLAAAAAERLyI0AAAAAREvIzwAAAABES8wpAAAAAERLzGsAAAAAREvMrQAAAABES8zvAAAAAERLzTFC78e2REvNc0NWbJ9ES821Q5QpeERLzfdDbnPBREvOOUJOhwhES857AAAAAERLzrwAAAAAREvO/gAAAABES89AAAAAAERMDGoAAAAAREwMrQAAAABETAzvAAAAAERMDTEAAAAAREwNc0MbaL1ETA21Q4XDPkRMDfdDlMa4REwOOkNYuqFETA58QoUC7kRMDr4AAAAAREwPAAAAAABETA9CAAAAAERMD4QAAAAARE+u2AAAAABET68dAAAAAERPr2EAAAAARE+vpgAAAABET6/qQyyLhURPsC9DWN/HRE+wc0NkY0tET7C4QxkM20RPsPwAAAAARE+xQQAAAABET7GFAAAAAERPscoAAAAARFAOCQAAAABEUA5OAAAAAERQDpMAAAAARFAO1wAAAABEUA8cQwDAqURQD2FDdvAjRFAPpkOL1RJEUA/qQ0OKJURQEC9CXTp0RFAQdAAAAABEUBC5AAAAAERQEP4AAAAARFARQgAAAABEVcuoAAAAAERVy/AAAAAARFXMOQAAAABEVcyCAAAAAERVzMpCzsoORFXNE0NaGXFEVc1bQ3R5C0RVzaRDKbY/RFXN7QAAAABEVc41AAAAAERVzn4AAAAARFXOxwAAAABEV5BlAAAAAERXkK4AAAAARFeQ+AAAAABEV5FCAAAAAERXkYxDKSu1RFeR1kNbVSFEV5IgQ1lH20RXkmlDOlYfRFeSs0M4QDVEV5L9Q0YP/0RXk0dDMzG5RFeTkQAAAABEV5PaAAAAAERXlCQAAAAARFeUbgAAAABEV6FpAAAAAERXobMAAAAARFeh/QAAAABEV6JHAAAAAERXopFDDVORRFei20NxGSNEV6MlQ22aoURXo25C9lnCRFejuAAAAABEV6QCAAAAAERXpEwAAAAARFeklgAAAABEV6W9AAAAAERXpgcAAAAARFemUQAAAABEV6abAAAAAERXpuVDLnHjRFenL0M9OBdEV6d5QxBdL0RXp8MAAAAARFeoDQAAAABEV6hWAAAAAERXqKAAAAAARF33JAAAAABEXfdzAAAAAERd98EAAAAARF34DwAAAABEXfheQy+tTURd+KxDS93XRF34+kM42jtEXflIQswuZkRd+ZcAAAAARF355QAAAABEXfozAAAAAERd+oEAAAAARF5M4QAAAABEXk0wAAAAAEReTX4AAAAARF5NzQAAAABEXk4bQrksMkReTmpDvnVcRF5OuEQoL11EXk8HREPcqkReT1VEI/uQRF5PpEPTigZEXk/zQ4LN9kReUEFDX7PhRF5QkAAAAABEXlDeAAAAAEReUS0AAAAARF5RewAAAABEXo0MAAAAAERejVsAAAAARF6NqQAAAABEXo34AAAAAERejkdDA7iRRF6OlUOCrD5EXo7kQ8vYCkRejzND56FuRF6PgUO0Y8BEXo/QQyOz3URekB8AAAAARF6QbgAAAABEXpC8AAAAAERekQsAAAAARF7MvgAAAABEXs0NAAAAAERezVwAAAAARF7NqgAAAABEXs35Q478yERezkhDw2IoRF7Ol0PtNthEXs7mQ+gZFERezzVDnL2ORF7PhAAAAABEXs/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RHFR/0NnQT9EcVJcQxBEBURxUrgAAAAARHFTFQAAAABEcVNxAAAAAERxU84AAAAARHUP2wAAAABEdRA6AAAAAER1EJkAAAAARHUQ+QAAAABEdRFYQoIpDER1EbhDbzAjRHUSF0OZA/BEdRJ2Q5gAnkR1EtZDj7qGRHUTNUN1fidEdROVQxFdtUR1E/QAAAAARHUUUwAAAABEdRSzAAAAAER1FRIAAAAARIFNGgAAAABEgU1PAAAAAESBTYQAAAAARIFNuQAAAABEgU3uQy178USBTiNDb4JRRIFOWEOhvR5EgU6NQ7dIFESBTsNDkg3MRIFO+ELaUAREgU8tAAAAAESBT2IAAAAARIFPlwAAAABEgU/MAAAAAESBpzIAAAAARIGnZwAAAABEgaecAAAAAESBp9IAAAAARIGoB0Jew0REgag9QzrtF0SBqHJDhC78RIGop0NtEDlEgajdQy4kQ0SBqRIAAAAARIGpSAAAAABEgal9AAAAAESBqbMAAAAARIHnXgAAAABEgeeUAAAAAESB58kAAAAARIHn/wAAAABEgeg1QwZ+g0SB6GpDhNUoRIHooEOId6xEgejWQvQoEkSB6QsAAAAARIHpQQAAAABEgel2AAAAAESB6awAAAAARIIHpwAAAABEggfdAAAAAESCCBMAAAAARIIISAAAAABEggh+Qv4nckSCCLRDWj6rRIII6kNbO+tEggkfQwvuw0SCCVUAAAAARIIJiwAAAABEggnBAAAAAESCCfYAAAAARIInlQAAAABEgifLAAAAAESCKAAAAAAARIIoNgAAAABEgihsQpgZsESCKKJDTqwDRIIo2ENlUilEgikOQwzsVUSCKUMAAAAARIIpeQAAAABEgimvAAAAAESCKeUAAAAARIJjZgAAAABEgmOcAAAAAESCY9IAAAAARIJkCAAAAABEgmQ+QxAFj0SCZHRDUubtRIJkq0NEJytEgmThQrRT7ESCZRcAAAAARIJlTQAAAABEgmWDAAAAAESCZbkAAAAARILgJgAAAABEguBcAAAAAESC4JMAAAAARILgyQAAAABEguEAQykld0SC4TZDdX0HRILhbENFmp9EguGjQb3PWESC4dkAAAAARILiEAAAAABEguJGAAAAAESC4n0AAAAARILldwAAAABEguWtAAAAAESC5eMAAAAARILmGgAAAABEguZQQwBjuUSC5odDV6cNRILmvUM6wtdEgub0QqvdxESC5yoAAAAARILnYQAAAABEgueXAAAAAESC580AAAAARIQHrQAAAABEhAflAAAAAESECBwAAAAARIQIVAAAAABEhAiLQ6u3TESECMJDwF2mRIQI+kO6QMBEhAkxQ4fEYkSECWlC/e2yRIQJoAAAAABEhAnXAAAAAESECg8AAAAARIQKRgAAAABEhkcTAAAAAESGR00AAAAARIZHhgAAAABEhke/AAAAAESGR/lDLs0JRIZIMkNUEF9EhkhrQ0uXC0SGSKRDHr1tRIZI3gAAAABEhkkXAAAAAESGSVAAAAAARIZJikL/SApEhknDQ2n1HUSGSfxDaNZfRIZKNULoybBEhkpvAAAAAESGSqgAAAAARIZK4QAAAABEhksbAAAAAESKp1YAAAAARIqnkwAAAABEiqfQAAAAAESKqA0AAAAARIqoSkOZccZEiqiHQ8OX8ESKqMRD0uwsRIqpAUPBGSZEiqk+Q4aumESKqXsAAAAARIqpuAAAAABEiqn1AAAAAESKqjMAAAAARIsHRgAAAABEiweEAAAAAESLB8EAAAAARIsH/gAAAABEiwg8QRzZQESLCHlDOZ21RIsIt0NpEt9Eiwj0Qxy7mUSLCTIAAAAARIsJbwAAAABEiwmsAAAAAESLCepC1l7iRIsKJ0NKJGFEiwplQ2VGDUSLCqJDI96fRIsK3wAAAABEiwsdAAAAAESLC1oAAAAARIsLmAAAAABEi6aPAAAAAESLps0AAAAARIunCgAAAABEi6dIAAAAAESLp4ZDAlSPRIunxEN89OlEi6gCQ36+10SLqEBDKC6nRIuofgAAAABEi6i8AAAAAESLqPoAAAAARIupOAAAAABEi6l2AAAAAESLqbQAAAAARIup8kMy0NNEi6owQ4TQBkSLqm5DkiguRIuqrENtXpdEi6rqQtiDoESLqygAAAAARIurZgAAAABEi6ukAAAAAESLq+IAAAAARIwKEwAAAABEjApRAAAAAESMCpAAAAAARIwKzgAAAABEjAsMQvIq9k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p/AwAAAAARKn8aAAAAABEqfzEAAAAAESp/SBDNOW9RKn9e0NlYU9Eqf3XQ0R360Sp/jNCwDr2RKn+jwAAAABEqf7rAAAAAESp/0YAAAAARKn/ogAAAABErEarAAAAAESsRwoAAAAARKxHaAAAAABErEfGAAAAAESsSCVCE4y4RKxIg0NICpdErEjhQ4IvIkSsSUBDKx7dRKxJngAAAABErEn8AAAAAESsSloAAAAARKxKuQAAAABEtQkRAAAAAES1CXkAAAAARLUJ4QAAAABEtQpKAAAAAES1CrJDJhD9RLULGkN2IZtEtQuCQ0j6M0S1C+pCqdwmRLUMUgAAAABEtQy6AAAAAES1DSMAAAAARLUNiwAAAABEt1aPAAAAAES3VvkAAAAARLdXZAAAAABEt1fPAAAAAES3WDpDesoPRLdYpUPA01ZEt1kPQ9YeGkS3WXpDvpdCRLdZ5UOX1rpEt1pQAAAAAES3WrsAAAAARLdbJgAAAABEt1uQAAAAAETFGvIAAAAARMUbbQAAAABExRvpAAAAAETFHGQAAAAARMUc30JvoHRExR1bQ31mOUTFHdZDt+aSRMUeUkPAB3pExR7NQ6mPcETFH0lDgLBwRMUfxEMHHK9ExSBAAAAAAETFILsAAAAARMUhNwAAAABExSGyAAAAAETHFHgAAAAARMcU9gAAAABExxV0AAAAAETHFfIAAAAARMcWcEM1n/lExxbuQ1u19UTHF2xDRxs7RMcX6kLjC6ZExxhoAAAAAETHGOYAAAAARMcZZAAAAABExxniAAAAAETH/rQAAAAARMf/MwAAAABEx/+yAAAAAETIADEAAAAA'
base64.b64decode(your_string)

Well first of all you need to assign the finished product to a variable to be able to be printed out:

code_string = base64.b64decode(your_string)

Then like any beginner programmer would know, you would print the results out: Python 2.7x:

print code_string

Python 3.x:

print(code_string)

After the successful decoding, you will get a string about the size of the not yet decoded string. I hope this helps you!

PHP AES encrypt / decrypt

If you are using MCRYPT_RIJNDAEL_128, try rtrim($output, "\0\3"). If the length of the string is less than 16, the decrypt function will return a string with length of 16 characters, adding 03 at the end.

You can easily check this, e.g. by trying:

$string = "TheString";
$decrypted_string = decrypt_function($stirng, $key);

echo bin2hex($decrypted_string)."=".bin2hex("TheString");

How to Load RSA Private Key From File

Two things. First, you must base64 decode the mykey.pem file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec, which is based on the SubjectPublicKeyInfo ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...   

String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);

urlencoded Forward slash is breaking URL

Apache denies all URLs with %2F in the path part, for security reasons: scripts can't normally (ie. without rewriting) tell the difference between %2F and / due to the PATH_INFO environment variable being automatically URL-decoded (which is stupid, but a long-standing part of the CGI specification so there's nothing can be done about it).

You can turn this feature off using the AllowEncodedSlashes directive, but note that other web servers will still disallow it (with no option to turn that off), and that other characters may also be taboo (eg. %5C), and that %00 in particular will always be blocked by both Apache and IIS. So if your application relied on being able to have %2F or other characters in a path part you'd be limiting your compatibility/deployment options.

I am using urlencode() while preparing the search URL

You should use rawurlencode(), not urlencode() for escaping path parts. urlencode() is misnamed, it is actually for application/x-www-form-urlencoded data such as in the query string or the body of a POST request, and not for other parts of the URL.

The difference is that + doesn't mean space in path parts. rawurlencode() will correctly produce %20 instead, which will work both in form-encoded data and other parts of the URL.

C Program to find day of week given date

For Day of Week, years 2000 - 2099.

uint8_t rtc_DayOfWeek(uint8_t year, uint8_t month, uint8_t day)
{
    //static const uint8_t month_offset_table[] = {0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5}; // Typical table.

    // Added 1 to Jan, Feb. Subtracted 1 from each instead of adding 6 in calc below.

    static const uint8_t month_offset_table[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};

    // Year is 0 - 99, representing years 2000 - 2099

    // Month starts at 0.

    // Day starts at 1.

    // Subtract 1 in calc for Jan, Feb, only in leap years.
    // Subtracting 1 from year has the effect of subtracting 2 in leap years, subtracting 1 otherwise.
    // Adding 1 for Jan, Feb in Month Table so calc ends up subtracting 1 for Jan, Feb, only in leap years.
    // All of this complication to avoid the check if it is a leap year.
    if (month < 2) {
        year--;
    }

    // Century constant is 6. Subtract 1 from Month Table, so difference is 7.

    // Sunday (0), Monday (1) ...

    return (day + month_offset_table[month] + year + (year >> 2)) % 7;

} /* end rtc_DayOfWeek() */

How to post SOAP Request from PHP

Below is a quick example of how to do this (which best explained the matter to me) that I essentially found at this website. That website link also explains WSDL, which is important for working with SOAP services.

However, I don't think the API address they were using in the example below still works, so just switch in one of your own choosing.

$wsdl = 'http://terraservice.net/TerraService.asmx?WSDL';

$trace = true;
$exceptions = false;

$xml_array['placeName'] = 'Pomona';
$xml_array['MaxItems'] = 3;
$xml_array['imagePresence'] = true;

$client = new SoapClient($wsdl, array('trace' => $trace, 'exceptions' => $exceptions));
$response = $client->GetPlaceList($xml_array);

var_dump($response);

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

Reinitialize Slick js after successful ajax call

This should work.

$.ajax({
    type: 'get',
    url: '/public/index',
    dataType: 'script',
    data: data_send,
    success: function() {
        $('.skills_section').slick('reinit');
      }
});

HTML Canvas Full Screen

On document load set the

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

Rollback to an old Git commit in a public repo

git read-tree -um @ $commit_to_revert_to

will do it. It's "git checkout" but without updating HEAD.

You can achieve the same effect with

git checkout $commit_to_revert_to
git reset --soft @{1}

if you prefer stringing convenience commands together.

These leave you with your worktree and index in the desired state, you can just git commit to finish.

SQL Query Multiple Columns Using Distinct on One Column Only

I needed to do the same and had to query a query to get the result

I set my first query up to bring in all IDs from the table and all other information needed to filter:

SELECT tMAIN.tLOTS.NoContract, tMAIN.ID
FROM tMAIN INNER JOIN tLOTS ON tMAIN.ID = tLOTS.id
WHERE (((tLOTS.NoContract)=False));

Save this as Q04_1 -0 this returned 1229 results (there are 63 unique records to query - soime with multiple LOTs)

SELECT DISTINCT ID
FROM q04_1;

Saved that as q04_2

I then wrote another query which brought in the required information linked to the ID

SELECT q04_2.ID, tMAIN.Customer, tMAIN.Category
FROM q04_2 INNER JOIN tMAIN ON q04_2.ID = tMAIN.ID;

Worked a treat and got me exactly what I needed - 63 unique records returned with customer and category details.

This is how I worked around it as I couldn't get the Group By working at all - although I am rather "wet behind the ears" weith SQL (so please be gentle and constructive with feedback)

How can I call a function using a function pointer?

If you need help with complex definitions, like

double (*(*pf)())[3][4];

take a look at my right-left rule here.

how to use jQuery ajax calls with node.js

I suppose your html page is hosted on a different port. Same origin policy requires in most browsers that the loaded file be on the same port than the loading file.

How to send json data in the Http request using NSURLRequest

Since my edit to Mike G's answer to modernize the code was rejected 3 to 2 as

This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer

I'm reposting my edit as a separate answer here. This edit removes the JSONRepresentation dependency with NSJSONSerialization as Rob's comment with 15 upvotes suggests.

    NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
      [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
    NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
    NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

    NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

    NSLog(@"jsonRequest is %@", jsonRequest);

    NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


    NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData];

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if (connection) {
     receivedData = [[NSMutableData data] retain];
    }

The receivedData is then handled by:

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSDictionary *question = [jsonDict objectForKey:@"question"];

Is it possible to hide the cursor in a webpage using CSS or Javascript?

If you want to hide the cursor in the entire webpage, using body will not work unless it covers the entire visible page, which is not always the case. To make sure the cursor is hidden everywhere in the page, use:

document.documentElement.style.cursor = 'none';

To reenable it:

document.documentElement.style.cursor = 'auto';

The analogue with static CSS notation is in the answer by Pavel Salaquarda (in essence: html * {cursor:none})

Java Delegates?

I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.

How It Works

There is a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.

With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.

In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array does not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to its inner workings.

The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.

What follows is an example using a callback to process the files in a directory tree. This is an initial validation pass which just counts the files to process and ensure none exceed a predetermined maximum size. In this case we just create the callback inline with the API invocation. However, we reflect the target method out as a static value so that the reflection is not done every time.

static private final Method             COUNT =Callback.getMethod(Xxx.class,"callback_count",true,File.class,File.class);

...

IoUtil.processDirectory(root,new Callback(this,COUNT),selector);

...

private void callback_count(File dir, File fil) {
    if(fil!=null) {                                                                             // file is null for processing a directory
        fileTotal++;
        if(fil.length()>fileSizeLimit) {
            throw new Abort("Failed","File size exceeds maximum of "+TextUtil.formatNumber(fileSizeLimit)+" bytes: "+fil);
            }
        }
    progress("Counting",dir,fileTotal);
    }

IoUtil.processDirectory():

/**
 * Process a directory using callbacks.  To interrupt, the callback must throw an (unchecked) exception.
 * Subdirectories are processed only if the selector is null or selects the directories, and are done
 * after the files in any given directory.  When the callback is invoked for a directory, the file
 * argument is null;
 * <p>
 * The callback signature is:
 * <pre>    void callback(File dir, File ent);</pre>
 * <p>
 * @return          The number of files processed.
 */
static public int processDirectory(File dir, Callback cbk, FileSelector sel) {
    return _processDirectory(dir,new Callback.WithParms(cbk,2),sel);
    }

static private int _processDirectory(File dir, Callback.WithParms cbk, FileSelector sel) {
    int                                 cnt=0;

    if(!dir.isDirectory()) {
        if(sel==null || sel.accept(dir)) { cbk.invoke(dir.getParent(),dir); cnt++; }
        }
    else {
        cbk.invoke(dir,(Object[])null);

        File[] lst=(sel==null ? dir.listFiles() : dir.listFiles(sel));
        if(lst!=null) {
            for(int xa=0; xa<lst.length; xa++) {
                File ent=lst[xa];
                if(!ent.isDirectory()) {
                    cbk.invoke(dir,ent);
                    lst[xa]=null;
                    cnt++;
                    }
                }
            for(int xa=0; xa<lst.length; xa++) {
                File ent=lst[xa];
                if(ent!=null) { cnt+=_processDirectory(ent,cbk,sel); }
                }
            }
        }
    return cnt;
    }

This example illustrates the beauty of this approach - the application specific logic is abstracted into the callback, and the drudgery of recursively walking a directory tree is tucked nicely away in a completely reusable static utility method. And we don't have to repeatedly pay the price of defining and implementing an interface for every new use. Of course, the argument for an interface is that it is far more explicit about what to implement (it's enforced, not simply documented) - but in practice I have not found it to be a problem to get the callback definition right.

Defining and implementing an interface is not really so bad (unless you're distributing applets, as I am, where avoiding creating extra classes actually matters), but where this really shines is when you have multiple callbacks in a single class. Not only is being forced to push them each into a separate inner class added overhead in the deployed application, but it's downright tedious to program and all that boiler-plate code is really just "noise".

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

How to use HTTP_X_FORWARDED_FOR properly?

I like Hrishikesh's answer, to which I only have this to add...because we saw a comma-delimited string coming across when multiple proxies along the way were used, we found it necessary to add an explode and grab the final value, like this:

$IParray=array_values(array_filter(explode(',',$_SERVER['HTTP_X_FORWARDED_FOR'])));
return end($IParray);

the array_filter is in there to remove empty entries.

How to scroll to top of page with JavaScript/jQuery?

Seeint the hash should do the job. If you have a header, you can use

window.location.href = "#headerid";

otherwise, the # alone will work

window.location.href = "#";

And as it get written into the url, it'll stay if you refresh.

In fact, you don't event need JavaScript for that if you want to do it on an onclick event, you should just put a link arround you element and give it # as href.

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

I use TINYINT(1)datatype in order to store boolean values in SQL Server though BIT is very effective

Get source JARs from Maven repository

For debugging you can also use a "Java Decompiler" such as: JAD and decompile source on the fly (although the generated source is never the same as the original). Then install JAD as a plugin in Eclipse or your favorite IDE.

"’" showing on page instead of " ' "

If someone gets this error on WordPress website, you need to change wp-config db charset:

define('DB_CHARSET', 'utf8mb4_unicode_ci');

instead of:

define('DB_CHARSET', 'utf8mb4');

Difference between const reference and normal parameter

Since none of you mentioned nothing about the const keyword...

The const keyword modifies the type of a type declaration or the type of a function parameter, preventing the value from varying. (Source: MS)

In other words: passing a parameter by reference exposes it to modification by the callee. Using the const keyword prevents the modification.

How do I flush the PRINT buffer in TSQL?

Yes... The first parameter of the RAISERROR function needs an NVARCHAR variable. So try the following;

-- Replace PRINT function
DECLARE @strMsg NVARCHAR(100)
SELECT @strMsg = 'Here''s your message...'
RAISERROR (@strMsg, 0, 1) WITH NOWAIT

OR

RAISERROR (n'Here''s your message...', 0, 1) WITH NOWAIT

Remove columns from dataframe where ALL values are NA

df[sapply(df, function(x) all(is.na(x)))] <- NULL

Delete the 'first' record from a table in SQL Server, without a WHERE condition

Does this really make sense?
There is no "first" record in a relational database, you can only delete one random record.

Composer Update Laravel

You can use :

composer self-update --2

To update to 2.0.8 version (Latest stable version)

What is the difference between VFAT and FAT32 file systems?

FAT32 along with FAT16 and FAT12 are File System Types, but vfat along with umsdos and msdos are drivers, used to mount the FAT file systems in Linux. The choosing of the driver determines how some of the features are applied to the file system, for example, systems mounted with msdos driver don't have long filenames (they are 8.3 format). vfat is the most common driver for mounting FAT32 file systems nowadays.

Source: this wikipedia article

Output of commands like df and lsblk indeed show vfat as the File System Type. But sudo file -sL /dev/<partition> shows FAT (32 bit) if a File System is FAT32.

You can confirm vfat is a module and not a File System Type by running modinfo vfat.

How to split a string to 2 strings in C

You can use strtok() for that Example: it works for me

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

int main ()
{
    char str[] ="- This, a sample string.";
    char * pch;
    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str," ,.-");
    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = strtok (NULL, " ,.-");
    }
    return 0;
}

CodeIgniter Select Query

function news_get_by_id ( $news_id )
{

    $this->db->select('*');
    $this->db->select("DATE_FORMAT( date, '%d.%m.%Y' ) as date_human",  FALSE );
    $this->db->select("DATE_FORMAT( date, '%H:%i') as time_human",      FALSE );


    $this->db->from('news');

    $this->db->where('news_id', $news_id );


    $query = $this->db->get();

    if ( $query->num_rows() > 0 )
    {
        $row = $query->row_array();
        return $row;
    }

}   
This 

How to add a form load event (currently not working)

Three ways you can do this - from the form designer, select the form, and where you normally see the list of properties, just above it there should be a little lightning symbol - this shows you all the events of the form. Find the form load event in the list, and you should be able to pick ProgramViwer_Load from the dropdown.

A second way to do it is programmatically - somewhere (constructor maybe) you'd need to add it, something like: ProgramViwer.Load += new EventHandler(ProgramViwer_Load);

A third way using the designer (probably the quickest) - when you create a new form, double click on the middle of it on it in design mode. It'll create a Form load event for you, hook it in, and take you to the event handler code. Then you can just add your two lines and you're good to go!

How to print variables in Perl

print "Number of lines: $nids\n";
print "Content: $ids\n";

How did Perl complain? print $ids should work, though you probably want a newline at the end, either explicitly with print as above or implicitly by using say or -l/$\.

If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}:

print "foo${ids}bar";

How can I get all sequences in an Oracle database?

select sequence_owner, sequence_name from dba_sequences;


DBA_SEQUENCES -- all sequences that exist 
ALL_SEQUENCES  -- all sequences that you have permission to see 
USER_SEQUENCES  -- all sequences that you own

Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES, there is no SEQUENCE_OWNER column in USER_SEQUENCES.

How do I negate a condition in PowerShell?

if you don't like the double brackets or you don't want to write a function, you can just use a variable.

$path = Test-Path C:\Code
if (!$path) {
    write "it doesn't exist!"
}

What's the simplest way to extend a numpy array in 2 dimensions?

The shortest in terms of lines of code i can think of is for the first question.

>>> import numpy as np
>>> p = np.array([[1,2],[3,4]])

>>> p = np.append(p, [[5,6]], 0)
>>> p = np.append(p, [[7],[8],[9]],1)

>>> p
array([[1, 2, 7],
   [3, 4, 8],
   [5, 6, 9]])

And the for the second question

    p = np.array(range(20))
>>> p.shape = (4,5)
>>> p
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
>>> n = 2
>>> p = np.append(p[:n],p[n+1:],0)
>>> p = np.append(p[...,:n],p[...,n+1:],1)
>>> p
array([[ 0,  1,  3,  4],
       [ 5,  6,  8,  9],
       [15, 16, 18, 19]])

LIKE vs CONTAINS on SQL Server

I think that CONTAINS took longer and used Merge because you had a dash("-") in your query adventure-works.com.

The dash is a break word so the CONTAINS searched the full-text index for adventure and than it searched for works.com and merged the results.

How to add constraints programmatically using Swift

This is one way to adding constraints programmatically

override func viewDidLoad() {
            super.viewDidLoad()


let myLabel = UILabel()
        myLabel.labelFrameUpdate(label: myLabel, text: "Welcome User", font: UIFont(name: "times new roman", size: 40)!, textColor: UIColor.red, textAlignment: .center, numberOfLines: 0, borderWidth: 2.0, BorderColor: UIColor.red.cgColor)
        self.view.addSubview(myLabel)


         let myLabelhorizontalConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
        let myLabelverticalConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
        let mylabelLeading = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 10)
        let mylabelTrailing = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: -10)
        let myLabelheightConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 50)
        NSLayoutConstraint.activate(\[myLabelhorizontalConstraint, myLabelverticalConstraint, myLabelheightConstraint,mylabelLeading,mylabelTrailing\])
}

extension UILabel
{
    func labelFrameUpdate(label:UILabel,text:String = "This is sample Label",font:UIFont = UIFont(name: "times new roman", size: 20)!,textColor:UIColor = UIColor.red,textAlignment:NSTextAlignment = .center,numberOfLines:Int = 0,borderWidth:CGFloat = 2.0,BorderColor:CGColor = UIColor.red.cgColor){
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = text
        label.font = font
        label.textColor = textColor
        label.textAlignment = textAlignment
        label.numberOfLines = numberOfLines
        label.layer.borderWidth = borderWidth
        label.layer.borderColor = UIColor.red.cgColor
    }
}

enter image description here

How to increase the gap between text and underlining in CSS

If you are using text-decoration: underline;, then you can add space between underline and text by using text-underline-position: under;

For more The text-underline-position properties, you can have look here

Limit Get-ChildItem recursion depth

@scanlegentil I like this.
A little improvement would be:

$Depth = 2
$Path = "."

$Levels = "\*" * $Depth
$Folder = Get-Item $Path
$FolderFullName = $Folder.FullName
Resolve-Path $FolderFullName$Levels | Get-Item | ? {$_.PsIsContainer} | Write-Host

As mentioned, this would only scan the specified depth, so this modification is an improvement:

$StartLevel = 1 # 0 = include base folder, 1 = sub-folders only, 2 = start at 2nd level
$Depth = 2      # How many levels deep to scan
$Path = "."     # starting path

For ($i=$StartLevel; $i -le $Depth; $i++) {
    $Levels = "\*" * $i
    (Resolve-Path $Path$Levels).ProviderPath | Get-Item | Where PsIsContainer |
    Select FullName
}

Adding padding to a tkinter widget only on one side

The padding options padx and pady of the grid and pack methods can take a 2-tuple that represent the left/right and top/bottom padding.

Here's an example:

import tkinter as tk

class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        l1 = tk.Label(self.root, text="Hello")
        l2 = tk.Label(self.root, text="World")
        l1.grid(row=0, column=0, padx=(100, 10))
        l2.grid(row=1, column=0, padx=(10, 100)) 

app = MyApp()
app.root.mainloop()

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

For a very specific reason Type Nullable<int> put your cursor on Nullable and hit F12 - The Metadata provides the reason (Note the struct constraint):

public struct Nullable<T> where T : struct
{
...
}

http://msdn.microsoft.com/en-us/library/d5x73970.aspx

Rollback transaction after @Test

Just add @Transactional annotation on top of your test:

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = {"testContext.xml"})
@Transactional
public class StudentSystemTest {

By default Spring will start a new transaction surrounding your test method and @Before/@After callbacks, rolling back at the end. It works by default, it's enough to have some transaction manager in the context.

From: 10.3.5.4 Transaction management (bold mine):

In the TestContext framework, transactions are managed by the TransactionalTestExecutionListener. Note that TransactionalTestExecutionListener is configured by default, even if you do not explicitly declare @TestExecutionListeners on your test class. To enable support for transactions, however, you must provide a PlatformTransactionManager bean in the application context loaded by @ContextConfiguration semantics. In addition, you must declare @Transactional either at the class or method level for your tests.

Execute a terminal command from a Cocoa app

In addition to the several excellent answers above, I use the following code to process the output of the command in the background and avoid the blocking mechanism of [file readDataToEndOfFile].

- (void)runCommand:(NSString *)commandToRun
{
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/sh"];

    NSArray *arguments = [NSArray arrayWithObjects:
                          @"-c" ,
                          [NSString stringWithFormat:@"%@", commandToRun],
                          nil];
    NSLog(@"run command:%@", commandToRun);
    [task setArguments:arguments];

    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput:pipe];

    NSFileHandle *file = [pipe fileHandleForReading];

    [task launch];

    [self performSelectorInBackground:@selector(collectTaskOutput:) withObject:file];
}

- (void)collectTaskOutput:(NSFileHandle *)file
{
    NSData      *data;
    do
    {
        data = [file availableData];
        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] );

    } while ([data length] > 0); // [file availableData] Returns empty data when the pipe was closed

    // Task has stopped
    [file closeFile];
}

Writing a list to a file with Python

Because i'm lazy....

import json
a = [1,2,3]
with open('test.txt', 'w') as f:
    f.write(json.dumps(a))

#Now read the file back into a Python list object
with open('test.txt', 'r') as f:
    a = json.loads(f.read())

How to debug .htaccess RewriteRule not working

If you have access to apache bin directory you can use,

httpd -M to check loaded modules first.

 info_module (shared)
 isapi_module (shared)
 log_config_module (shared)
 cache_disk_module (shared)
 mime_module (shared)
 negotiation_module (shared)
 proxy_module (shared)
 proxy_ajp_module (shared)
 rewrite_module (shared)
 setenvif_module (shared)
 socache_shmcb_module (shared)
 ssl_module (shared)
 status_module (shared)
 version_module (shared)
 php5_module (shared)

After that simple directives like Options -Indexes or deny from all will solidify that .htaccess are working correctly.

JavaScript - onClick to get the ID of the clicked button

How to do it without inline JavaScript

it is generally recommended to avoid inline JavaScript, but rarely is there an example of how to do it.
Here is my way of attaching events to buttons.
I'm not entirely happy with how much longer the recommended method is compared to a simple onClick attribute.

2014 browsers only

<button class="btn" id="b1">Button</button>
<script>
let OnEvent = (doc) => {
    return {
        on: (event, className, callback) => {
            doc.addEventListener('click', (event)=>{
                if(!event.target.classList.contains(className)) return;
                callback.call(event.target, event);
            }, false);
        }
    }
};


OnEvent(document).on('click', 'btn', function (e) {
    window.console.log(this.id, e);
});

</script>

2013 browsers only

<!DOCTYPE html>
<html>
<head>
<script>
(function(doc){
    var hasClass = function(el,className) {
        return el.classList.contains(className);
    }
    doc.addEventListener('click', function(e){
      if(hasClass(e.target, 'click-me')){
          e.preventDefault();
          doSomething.call(e.target, e);
      }
    });
})(document);

function insertHTML(str){
  var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
  lastScript.insertAdjacentHTML("beforebegin", str);
}

function doSomething(event){
  console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>

<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script>
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>

<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">

<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>

</body>
</html>

Cross-browser

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(doc){
    var cb_addEventListener = function(obj, evt, fnc) {
        // W3C model
        if (obj.addEventListener) {
            obj.addEventListener(evt, fnc, false);
            return true;
        } 
        // Microsoft model
        else if (obj.attachEvent) {
            return obj.attachEvent('on' + evt, fnc);
        }
        // Browser don't support W3C or MSFT model, go on with traditional
        else {
            evt = 'on'+evt;
            if(typeof obj[evt] === 'function'){
                // Object already has a function on traditional
                // Let's wrap it with our own function inside another function
                fnc = (function(f1,f2){
                    return function(){
                        f1.apply(this,arguments);
                        f2.apply(this,arguments);
                    }
                })(obj[evt], fnc);
            }
            obj[evt] = fnc;
            return true;
        }
        return false;
    };
    var hasClass = function(el,className) {
        return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
    }

    cb_addEventListener(doc, 'click', function(e){
      if(hasClass(e.target, 'click-me')){
          e.preventDefault ? e.preventDefault() : e.returnValue = false;
          doSomething.call(e.target, e);
      }
    });
})(document);

function insertHTML(str){
  var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
  lastScript.insertAdjacentHTML("beforebegin", str);
}

function doSomething(event){
  console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>

<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>

<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">

<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>

</body>
</html>

Cross-browser with jQuery

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function($){
    $(document).on('click', '.click-me', function(e){
      doSomething.call(this, e);
    });
})(jQuery);

function insertHTML(str){
  var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
  lastScript.insertAdjacentHTML("beforebegin", str);
}

function doSomething(event){
  console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>

<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>

<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">

<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>

</body>
</html>

You can run this before the document is ready, clicking the buttons will work because we attach the event to the document.

Here is a jsfiddle
For some strange reason the insertHTML function does not work in it even though it works in all my browsers.

You can always replace insertHTML with document.write if you don't mind it's drawbacks

<script>
document.write('<button class="click-me" id="btn1">Button 1</button>');
</script>

Sources:

Hive External Table Skip First Row

create external table table_name( 
Year int, 
Month int,
column_name data_type ) 
row format delimited fields terminated by ',' 
location '/user/user_name/example_data' TBLPROPERTIES('serialization.null.format'='', 'skip.header.line.count'='1');

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

I just ran into this problem and stumbled across a different situation. Although it's probably just a unicorn, I thought I'd lay it out.

I had one session that was smaller, and I noticed that the font sizes were different: the smaller session had the smaller fonts. Apparently, I had changed window font sizes for some reason.

So in OS X, I just did Cmd-+ on the smaller sized session, and it snapped back into place.

How do I migrate an SVN repository with history to a new Git repository?

I used the following script to read a text file that has a list of all my SVN repositories and convert them to Git, and later use git clone --bare to convert to a bare Git repository:

#!/bin/bash
file="list.txt"
while IFS= read -r repo_name
do
 printf '%s\n' "$repo_name"
 sudo git svn clone --shared --preserve-empty-dirs --authors-file=users.txt file:///programs/svn/$repo_name
 sudo git clone --bare /programs/git/$repo_name $repo_name.git
 sudo chown -R www-data:www-data $repo_name.git
 sudo rm -rf $repo_name
done <"$file"

list.txt has the format:

repo1_name
repo2_name

And users.txt has the format:

(no author) = Prince Rogers <[email protected]>

www-data is the Apache web server user, and permission is needed to push changes over HTTP.

onchange equivalent in angular2

We can use Angular event bindings to respond to any DOM event. The syntax is simple. We surround the DOM event name in parentheses and assign a quoted template statement to it. -- reference

Since change is on the list of standard DOM events, we can use it:

(change)="saverange()"

In your particular case, since you're using NgModel, you could break up the two-way binding like this instead:

[ngModel]="range" (ngModelChange)="saverange($event)"

Then

saverange(newValue) {
  this.range = newValue;
  this.Platform.ready().then(() => {
     this.rootRef.child("users").child(this.UserID).child('range').set(this.range)
  })
} 

However, with this approach saverange() is called with every keystroke, so you're probably better off using (change).

How can I make a weak protocol reference in 'pure' Swift (without @objc)

protocol must be subClass of AnyObject, class

example given below

    protocol NameOfProtocol: class {
   // member of protocol
    }
   class ClassName: UIViewController {
      weak var delegate: NameOfProtocol? 
    }

What's the best free C++ profiler for Windows?

There is an instrumenting (function-accurate) profiler for MS VC 7.1 and higher called MicroProfiler. You can get it here (x64) or here (x86). It doesn't require any modifications or additions to your code and is able of displaying function statistics with callers and callees in real-time without the need of closing application/stopping the profiling process.

It integrates with VisualStudio, so you can easily enable/disable profiling for a project. It is also possible to install it on the clean machine, it only needs the symbol information be located along with the executable being profiled.

This tool is useful when statistical approximation from sampling profilers like Very Sleepy isn't sufficient.

Rough comparison shows, that it beats AQTime (when it is invoked in instrumenting, function-level run). The following program (full optimization, inlining disabled) runs three times faster with micro-profiler displaying results in real-time, than with AQTime simply collecting stats:

void f()
{
    srand(time(0));

    vector<double> v(300000);

    generate_n(v.begin(), v.size(), &random);
    sort(v.begin(), v.end());
    sort(v.rbegin(), v.rend());
    sort(v.begin(), v.end());
    sort(v.rbegin(), v.rend());
}

How can I get the nth character of a string?

char* str = "HELLO";
char c = str[1];

Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.

HTML5 Video Autoplay not working correctly

Mobile browsers generally ignore this attribute to prevent consuming data until user explicitly starts the download.

UPDATE: newer version of mobile browser on Android and iOS do support autoplay function. But it only works if the video is muted or has no audio channel:

Some additional info: https://webkit.org/blog/6784/new-video-policies-for-ios/

What is the meaning of CTOR?

It's just shorthand for "constructor" - and it's what the constructor is called in IL, too. For example, open up Reflector and look at a type and you'll see members called .ctor for the various constructors.

Representing null in JSON

Let's evaluate the parsing of each:

http://jsfiddle.net/brandonscript/Y2dGv/

var json1 = '{}';
var json2 = '{"myCount": null}';
var json3 = '{"myCount": 0}';
var json4 = '{"myString": ""}';
var json5 = '{"myString": "null"}';
var json6 = '{"myArray": []}';

console.log(JSON.parse(json1)); // {}
console.log(JSON.parse(json2)); // {myCount: null}
console.log(JSON.parse(json3)); // {myCount: 0}
console.log(JSON.parse(json4)); // {myString: ""}
console.log(JSON.parse(json5)); // {myString: "null"}
console.log(JSON.parse(json6)); // {myArray: []}

The tl;dr here:

The fragment in the json2 variable is the way the JSON spec indicates null should be represented. But as always, it depends on what you're doing -- sometimes the "right" way to do it doesn't always work for your situation. Use your judgement and make an informed decision.


JSON1 {}

This returns an empty object. There is no data there, and it's only going to tell you that whatever key you're looking for (be it myCount or something else) is of type undefined.


JSON2 {"myCount": null}

In this case, myCount is actually defined, albeit its value is null. This is not the same as both "not undefined and not null", and if you were testing for one condition or the other, this might succeed whereas JSON1 would fail.

This is the definitive way to represent null per the JSON spec.


JSON3 {"myCount": 0}

In this case, myCount is 0. That's not the same as null, and it's not the same as false. If your conditional statement evaluates myCount > 0, then this might be worthwhile to have. Moreover, if you're running calculations based on the value here, 0 could be useful. If you're trying to test for null however, this is actually not going to work at all.


JSON4 {"myString": ""}

In this case, you're getting an empty string. Again, as with JSON2, it's defined, but it's empty. You could test for if (obj.myString == "") but you could not test for null or undefined.


JSON5 {"myString": "null"}

This is probably going to get you in trouble, because you're setting the string value to null; in this case, obj.myString == "null" however it is not == null.


JSON6 {"myArray": []}

This will tell you that your array myArray exists, but it's empty. This is useful if you're trying to perform a count or evaluation on myArray. For instance, say you wanted to evaluate the number of photos a user posted - you could do myArray.length and it would return 0: defined, but no photos posted.

How to do date/time comparison

For comparison between two times use time.Sub()

// utc life
loc, _ := time.LoadLocation("UTC")

// setup a start and end time
createdAt := time.Now().In(loc).Add(1 * time.Hour)
expiresAt := time.Now().In(loc).Add(4 * time.Hour)

// get the diff
diff := expiresAt.Sub(createdAt)
fmt.Printf("Lifespan is %+v", diff)

The program outputs:

Lifespan is 3h0m0s

http://play.golang.org/p/bbxeTtd4L6

Why do we need to install gulp globally and locally?

You can link the globally installed gulp locally with

npm link gulp

Making heatmap from pandas DataFrame

For people looking at this today, I would recommend the Seaborn heatmap() as documented here.

The example above would be done as follows:

import numpy as np 
from pandas import DataFrame
import seaborn as sns
%matplotlib inline

Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
Cols = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=Index, columns=Cols)

sns.heatmap(df, annot=True)

Where %matplotlib is an IPython magic function for those unfamiliar.

How to make a div with no content have a width?

If you set display: to inline-block, block, flex, ..., on the element with no content, then

For min-width to take effect on a tag with no content, you only need to apply padding for either top or bot.

For min-height to take effect on a tag with no content, you only need to apply padding for left or right.

This example showcases it; here I only sat the padding-left for the min-width to take effect on an empty span tag

How to show/hide if variable is null

<div ng-hide="myvar == null"></div>

or

<div ng-show="myvar != null"></div>

Including JavaScript class definition from another file in Node.js

Using ES6, you can have user.js:

export default class User {
  constructor() {
    ...
  }
}

And then use it in server.js

const User = require('./user.js').default;
const user = new User();

Create a new file in git bash

If you are using the Git Bash shell, you can use the following trick:

> webpage.html

This is actually the same as:

echo "" > webpage.html

Then, you can use git add webpage.html to stage the file.

align 3 images in same row with equal spaces?

HTML:

<div class="container">
    <span>
        <img ... >
    </span>
    <span>
        <img ... >
    </span>
    <span>
        <img ... >
    </span>
</div>

CSS:

.container{ width:50%; margin:0 auto; text-align:center}
.container span{ width:30%; margin:0 1%;  }

I haven't tested this, but hope this will work.

You can add 'display:inline-block' to .container span to make the span to have fixed 30% width

Getting list of pixel values from PIL

If you have numpy installed you can try:

data = numpy.asarray(im)

(I say "try" here, because it's unclear why getdata() isn't working for you, and I don't know whether asarray uses getdata, but it's worth a test.)

How to fix "ImportError: No module named ..." error in Python?

Example solution for adding the library to your PYTHONPATH.

  1. Add the following line into your ~/.bashrc or just run it directly:

    export PYTHONPATH="$PYTHONPATH:$HOME/.python"
    
  2. Then link your required library into your ~/.python folder, e.g.

    ln -s /home/user/work/project/foo ~/.python/
    

Start service in Android

Probably you don't have the service in your manifest, or it does not have an <intent-filter> that matches your action. Examining LogCat (via adb logcat, DDMS, or the DDMS perspective in Eclipse) should turn up some warnings that may help.

More likely, you should start the service via:

startService(new Intent(this, UpdaterServiceManager.class));

When should we use intern method of String on String literals

String literals and constants are interned by default. That is, "foo" == "foo" (declared by the String literals), but new String("foo") != new String("foo").

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

I have had this issue before.

client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;

do this against your wcf proxy before making the call.

How to decrypt hash stored by bcrypt

You're HASHING, not ENCRYPTING!

What's the difference?

The difference is that hashing is a one way function, where encryption is a two-way function.

So, how do you ascertain that the password is right?

Therefore, when a user submits a password, you don't decrypt your stored hash, instead you perform the same bcrypt operation on the user input and compare the hashes. If they're identical, you accept the authentication.

Should you hash or encrypt passwords?

What you're doing now -- hashing the passwords -- is correct. If you were to simply encrypt passwords, a breach of security of your application could allow a malicious user to trivially learn all user passwords. If you hash (or better, salt and hash) passwords, the user needs to crack passwords (which is computationally expensive on bcrypt) to gain that knowledge.

As your users probably use their passwords in more than one place, this will help to protect them.

Least common multiple for 3 or more numbers

Python 3.9 math module's gcd and lcm support over a list of numbers.

import math

lst = [1,2,3,4,5,6,7,8,9]

print(math.lcm(*lst))

print(math.gcd(*lst))

"inconsistent use of tabs and spaces in indentation"

I oddly ran into a similar issue with one of my .py files. I simply opened the file in Pycharm and pressed Option+Command+L which correctly formats the file contents in one go.

I suspect I was having trouble because I coded this particular .py file through jupyter labs as opposed to my usual choice of sublime text or Pycharm and therefore ran into some hidden indentation issues many answers here have alluded to

What does "to stub" mean in programming?

A stub is a controllable replacement for an Existing Dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly.

External Dependency - Existing Dependency:
It is an object in your system that your code under test interacts with and over which you have no control. (Common examples are filesystems, threads, memory, time, and so on.)

Forexample in below code:

public void Analyze(string filename)
    {
        if(filename.Length<8)
        {
            try
            {
                errorService.LogError("long file entered named:" + filename);
            }
            catch (Exception e)
            {
                mailService.SendEMail("[email protected]", "ErrorOnWebService", "someerror");
            }
        }
    }

You want to test mailService.SendEMail() method, but to do that you need to simulate an Exception in your test method, so you just need to create a Fake Stub errorService object to simulate the result you want, then your test code will be able to test mailService.SendEMail() method. As you see you need to simulate a result which is from an another Dependency which is ErrorService class object (Existing Dependency object).

Read entire file in Scala?

(EDIT: This does not work in scala 2.9 and maybe not 2.8 either)

Use trunk:

scala> io.File("/etc/passwd").slurp
res0: String = 
##
# User Database
# 
... etc

error::make_unique is not a member of ‘std’

This happens to me while working with XCode (I'm using the most current version of XCode in 2019...). I'm using, CMake for build integration. Using the following directive in CMakeLists.txt fixed it for me:

set(CMAKE_CXX_STANDARD 14).

Example:

cmake_minimum_required(VERSION 3.14.0)
set(CMAKE_CXX_STANDARD 14)

# Rest of your declarations...

How to get single value of List<object>

Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

Nexus 5 USB driver

Currently experienced this problem with my Nexus 5, when attempting to sideload latest 4.4.1 OTA update via stock recovery.

Solution:

  1. Open Android SDK Manager (in console get to sdk directory then run tools\android)
  2. Download/install latest USB drivers (under Extras).
  3. In Windows Device Manager (devmgmt.msc), right click the Nexus 5 device and select Update Driver Software.
  4. Browse My Computer for driver software > Android SDK Dir > Extras > usb_driver

What does print(... sep='', '\t' ) mean?

The sep='\t' can be use in many forms, for example if you want to read tab separated value: Example: I have a dataset tsv = tab separated value NOT comma separated value df = pd.read_csv('gapminder.tsv'). when you try to read this, it will give you an error because you have tab separated value not csv. so you need to give read csv a different parameter called sep='\t'.

Now you can read: df = pd.read_csv('gapminder.tsv, sep='\t'), with this you can read the it.

Merge / convert multiple PDF files into one PDF

If you want to convert all the downloaded images into one pdf then execute

convert img{0..19}.jpg slides.pdf

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

How to create a connection string in asp.net c#

It occurs when IIS is not being connected to SQL SERVER. For a solution, see this screenshot: Solution

How do I make a <div> move up and down when I'm scrolling the page?

Just for a more animated and cute solution:

$(window).scroll(function(){
  $("#div").stop().animate({"marginTop": ($(window).scrollTop()) + "px", "marginLeft":($(window).scrollLeft()) + "px"}, "slow" );
});

And a pen for those who want to see: http://codepen.io/think123/full/mAxlb, and fork: http://codepen.io/think123/pen/mAxlb

Update: and a non-animated jQuery solution:

$(window).scroll(function(){
  $("#div").css({"margin-top": ($(window).scrollTop()) + "px", "margin-left":($(window).scrollLeft()) + "px"});
});

How to find whether a ResultSet is empty or not in Java?

Definitely this gives good solution,

ResultSet rs = stmt.execute("SQL QUERY");
// With the above statement you will not have a null ResultSet 'rs'.
// In case, if any exception occurs then next line of code won't execute.
// So, no problem if I won't check rs as null.

if (rs.next()) {
    do {
      // Logic to retrieve the data from the resultset.
      // eg: rs.getString("abc");
    } while(rs.next());
} else {
    // No data
}

fopen deprecated warning

If you code is intended for a different OS (like Mac OS X, Linux) you may use following:

#ifdef _WIN32
#define _CRT_SECURE_NO_DEPRECATE
#endif

text box input height

I came here looking for making an input that's actually multiple lines. Turns out I didn't want an input, I wanted a textarea. You can set height or line-height as other answers specify, but it'll still just be one line of a textbox. If you want actual multiple lines, use a textarea instead. The following is an example of a 3-row textarea with a width of 500px (should be a good part of the page, not necessary to set this and will have to change it based on your requirements).

<textarea name="roleExplanation" style="width: 500px" rows="3">This role is for facility managers and holds the highest permissions in the application.</textarea>

React Native Responsive Font Size

I managed to overcome this by doing the following.

  1. Pick the font size you like for the current view you have (Make sure it looks good for the current device you are using in the simulator).

  2. import { Dimensions } from 'react-native' and define the width outside of the component like so: let width = Dimensions.get('window').width;

  3. Now console.log(width) and write it down. If your good looking font size is 15 and your width is 360 for example, then take 360 and divide by 15 ( = 24). This is going to be the important value that is going to adjust to different sizes.

    Use this number in your styles object like so: textFontSize: { fontSize = width / 24 },...

Now you have a responsive fontSize.

How to delete columns that contain ONLY NAs?

Another option is the janitor package:

df <- remove_empty_cols(df)

https://github.com/sfirke/janitor

How to sort a NSArray alphabetically?

The simplest approach is, to provide a sort selector (Apple's documentation for details)

Objective-C

sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

Swift

let descriptor: NSSortDescriptor = NSSortDescriptor(key: "YourKey", ascending: true, selector: "localizedCaseInsensitiveCompare:")
let sortedResults: NSArray = temparray.sortedArrayUsingDescriptors([descriptor])

Apple provides several selectors for alphabetic sorting:

  • compare:
  • caseInsensitiveCompare:
  • localizedCompare:
  • localizedCaseInsensitiveCompare:
  • localizedStandardCompare:

Swift

var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
students.sort()
print(students)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"

Reference

Questions every good Java/Java EE Developer should be able to answer?

How about what is a session bean and describe some differences between stateless and stateful session beans.

How does one remove a Docker image?

To remove an image from Docker using the image ID:

  1. Get the list of all Images

    docker images
    
  2. Identify the image ID of the image you want to delete, for example:

    REPOSITORY     TAG     IMAGE ID        CREATED        VIRTUAL SIZE
    kweku360/java  latest  08d3a9b8e166    2 weeks ago         5.733 GB`
    
  3. Finally remove the image using the image ID (only the first three digits are required)

    docker rmi 08d
    

Clearing all cookies with JavaScript

I have some more sophisticated and OOP-oriented cookie control module. It also contains deleteAll method to clear all existing cookie. Make notice that this version of deleteAll method has setting path=/ that causes deleting of all cookies within current domain. If you need to delete cookies only from some scope you will have to upgrade this method my adding dynamic path parameter to this method.

There is main Cookie class:

import {Setter} from './Setter';

export class Cookie {
    /**
     * @param {string} key
     * @return {string|undefined}
     */
    static get(key) {
        key = key.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1');

        const regExp = new RegExp('(?:^|; )' + key + '=([^;]*)');
        const matches = document.cookie.match(regExp);

        return matches
            ? decodeURIComponent(matches[1])
            : undefined;
    }

    /**
     * @param {string} name
     */
    static delete(name) {
        this.set(name, '', { expires: -1 });
    }

    static deleteAll() {
        const cookies = document.cookie.split('; ');

        for (let cookie of cookies) {
            const index = cookie.indexOf('=');

            const name = ~index
                ? cookie.substr(0, index)
                : cookie;

            document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
        }
    }

    /**
     * @param {string} name
     * @param {string|boolean} value
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     */
    static set(name, value, opts = {}) {
        Setter.set(name, value, opts);
    }
}

Cookie setter method (Cookie.set) is rather complex so I decomposed it into other class. There is code of this one:

export class Setter {
    /**
     * @param {string} name
     * @param {string|boolean} value
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     */
    static set(name, value, opts = {}) {
        value = Setter.prepareValue(value);
        opts = Setter.prepareOpts(opts);

        let updatedCookie = name + '=' + value;

        for (let i in opts) {
            if (!opts.hasOwnProperty(i)) continue;

            updatedCookie += '; ' + i;

            const value = opts[i];

            if (value !== true)
                updatedCookie += '=' + value;
        }

        document.cookie = updatedCookie;
    }

    /**
     * @param {string} value
     * @return {string}
     * @private
     */
    static prepareValue(value) {
        return encodeURIComponent(value);
    }

    /**
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     * @private
     */
    static prepareOpts(opts = {}) {
        opts = Object.assign({}, opts);

        let {expires} = opts;

        if (typeof expires == 'number' && expires) {
            const date = new Date();

            date.setTime(date.getTime() + expires * 1000);

            expires = opts.expires = date;
        }

        if (expires && expires.toUTCString)
            opts.expires = expires.toUTCString();

        return opts;
    }
}

Argparse: Required arguments listed under "optional arguments"?

Building off of @Karl Rosaen

parser = argparse.ArgumentParser()
optional = parser._action_groups.pop() # Edited this line
required = parser.add_argument_group('required arguments')
# remove this line: optional = parser...
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
parser._action_groups.append(optional) # added this line
return parser.parse_args()

and this outputs:

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

required arguments:
  --required_arg REQUIRED_ARG

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

What's the difference between a mock & stub?

following is my understanding...

  • if you create test objects locally and feed your local service with that, you are using mock object. this will give a test for the method you implemented in your local service. it is used to verify behaviors

  • when you get the test data from the real service provider, though from a test version of interface and get a test version of the object, you are working with stubs the stub can have logic to accept certain input and give corresponding output to help you perform state verification...

How to fire a button click event from JavaScript in ASP.NET

None of the solutions posted here would work for me, this was my eventual solution to the problem.

// In Server Side code
protected void Page_Load(object sender, EventArgs e)
{
    Page.GetPostBackEventReference(hiddenButton);
}

// Javascript
function SetSaved() {
    __doPostBack("<%= hiddenButton.UniqueID %>", "OnClick");
}

// ASP
 <asp:Button ID="hiddenButton" runat="server" OnClick="btnSaveGroup_Click" Visible="false"/>

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

You haven't set the timezone only added a Z to the end of the date/time, so it will look like a GMT date/time but this doesn't change the value.

Set the timezone to GMT and it will be correct.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

Android difference between Two Dates

Here is the modern answer. It’s good for anyone who either uses Java 8 or later (which doesn’t go for most Android phones yet) or is happy with an external library.

    String date1 = "20170717141000";
    String date2 = "20170719175500";

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    Duration diff = Duration.between(LocalDateTime.parse(date1, formatter), 
                                     LocalDateTime.parse(date2, formatter));

    if (diff.isZero()) {
        System.out.println("0m");
    } else {
        long days = diff.toDays();
        if (days != 0) {
            System.out.print("" + days + "d ");
            diff = diff.minusDays(days);
        }
        long hours = diff.toHours();
        if (hours != 0) {
            System.out.print("" + hours + "h ");
            diff = diff.minusHours(hours);
        }
        long minutes = diff.toMinutes();
        if (minutes != 0) {
            System.out.print("" + minutes + "m ");
            diff = diff.minusMinutes(minutes);
        }
        long seconds = diff.getSeconds();
        if (seconds != 0) {
            System.out.print("" + seconds + "s ");
        }
        System.out.println();
    }

This prints

2d 3h 45m 

In my own opinion the advantage is not so much that it is shorter (it’s not much), but leaving the calculations to an standard library is less errorprone and gives you clearer code. These are great advantages. The reader is not burdened with recognizing constants like 24, 60 and 1000 and verifying that they are used correctly.

I am using the modern Java date & time API (described in JSR-310 and also known under this name). To use this on Android under API level 26, get the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project. To use it with other Java 6 or 7, get ThreeTen Backport. With Java 8 and later it is built-in.

With Java 9 it will be still a bit easier since the Duration class is extended with methods to give you the days part, hours part, minutes part and seconds part separately so you don’t need the subtractions. See an example in my answer here.

Forms authentication timeout vs sessionState timeout

From what I understand they are independent of one another. By keeping the session timeout less than or equal to the authentication timeout, you can make sure any user-specific session variables are not persisted after the authentication has timed out (if that is your concern, which I think is the normal one when asking this question). Of course, you'll have to manually handle the disposal of session variables upon log-out.

Here is a decent response that may answer your question or at least point you in the right direction:

Full width image with fixed height

If you want to have same ratio you should create a container and hide a part of the image.

_x000D_
_x000D_
.container{_x000D_
  width:100%;_x000D_
  height:60px;_x000D_
  overflow:hidden;_x000D_
}_x000D_
.img {_x000D_
  width:100%;_x000D_
}
_x000D_
<div class="container">_x000D_
  <img src="http://placehold.it/100x100" class="img" alt="Our Location" /> _x000D_
</div>_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

Is there a way to delete all the data from a topic or delete the topic before every run?

I use the utility below to cleanup after my integration test run.

It uses the latest AdminZkClient api. The older api has been deprecated.

import javax.inject.Inject
import kafka.zk.{AdminZkClient, KafkaZkClient}
import org.apache.kafka.common.utils.Time

class ZookeeperUtils @Inject() (config: AppConfig) {

  val testTopic = "users_1"

  val zkHost = config.KafkaConfig.zkHost
  val sessionTimeoutMs = 10 * 1000
  val connectionTimeoutMs = 60 * 1000
  val isSecure = false
  val maxInFlightRequests = 10
  val time: Time = Time.SYSTEM

  def cleanupTopic(config: AppConfig) = {

    val zkClient = KafkaZkClient.apply(zkHost, isSecure, sessionTimeoutMs, connectionTimeoutMs, maxInFlightRequests, time)
    val zkUtils = new AdminZkClient(zkClient)

    val pp = new Properties()
    pp.setProperty("delete.retention.ms", "10")
    pp.setProperty("file.delete.delay.ms", "1000")
    zkUtils.changeTopicConfig(testTopic , pp)
    //    zkUtils.deleteTopic(testTopic)

    println("Waiting for topic to be purged. Then reset to retain records for the run")
    Thread.sleep(60000L)

    val resetProps = new Properties()
    resetProps.setProperty("delete.retention.ms", "3000000")
    resetProps.setProperty("file.delete.delay.ms", "4000000")
    zkUtils.changeTopicConfig(testTopic , resetProps)

  }


}

There is an option delete topic. But, it marks the topic for deletion. Zookeeper later deletes the topic. Since this can be unpredictably long, I prefer the retention.ms approach

How to tell if UIViewController's view is visible

I made a swift extension based on @progrmr's answer.

It allows you to easily check if a UIViewController is on screen like so:

if someViewController.isOnScreen {
    // Do stuff here
}

The extension:

//
//  UIViewControllerExtension.swift
//

import UIKit

extension UIViewController{
    var isOnScreen: Bool{
        return self.isViewLoaded() && view.window != nil
    }
}

How to check if keras tensorflow backend is GPU or CPU version?

Also you can check using Keras backend function:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

I test this on Keras (2.1.1)

Open firewall port on CentOS 7

If you have multiple ports to allow in Centos 7 FIrewalld then we can use the following command.

#firewall-cmd --add-port={port number/tcp,port number/tcp} --permanent

#firewall-cmd --reload


And check the Port opened or not after reloading the firewall.


#firewall-cmd --list-port


For other configuration [Linuxwindo.com][1]

How to make an installer for my C# application?

  1. Add a new install project to your solution.
  2. Add targets from all projects you want to be installed.
  3. Configure pre-requirements and choose "Check for .NET 3.5 and SQL Express" option. Choose the location from where missing components must be installed.
  4. Configure your installer settings - company name, version, copyright, etc.
  5. Build and go!

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

Firefox Developer Edition (59.0b6) has Scratchpad (Shift +F4) where you can run javascript

jQuery Force set src attribute for iframe

You cannot set FIX iframe's src or prevent javascript/form submit to change its location. However you can put script to onload of the page and change action of each dynamic link.

How to check if a directory containing a file exist?

To check if a folder exists or not, you can simply use the exists() method:

// Create a File object representing the folder 'A/B'
def folder = new File( 'A/B' )

// If it doesn't exist
if( !folder.exists() ) {
  // Create all folders up-to and including B
  folder.mkdirs()
}

// Then, write to file.txt inside B
new File( folder, 'file.txt' ).withWriterAppend { w ->
  w << "Some text\n"
}

Find the closest ancestor element that has a specific class

This does the trick:

function findAncestor (el, cls) {
    while ((el = el.parentElement) && !el.classList.contains(cls));
    return el;
}

The while loop waits until el has the desired class, and it sets el to el's parent every iteration so in the end, you have the ancestor with that class or null.

Here's a fiddle, if anyone wants to improve it. It won't work on old browsers (i.e. IE); see this compatibility table for classList. parentElement is used here because parentNode would involve more work to make sure that the node is an element.

Flask ImportError: No Module Named Flask

enter your python interactive mode then:

import sys

sys.path

it will print your path. Check wether flask is installed in the sys.path.

For MacOS, python path is under /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages

But pip'll install python package by default under /Library/Python/2.7/site-packages

That's why it doesn't work for MacOS.

Removing the password from a VBA project

This has a simple method using SendKeys to unprotect the VBA project. This would get you into the project, so you'd have to continue on using SendKeys to figure out a way to remove the password protection: http://www.pcreview.co.uk/forums/thread-989191.php

And here's one that uses a more advanced, somewhat more reliable method for unprotecting. Again, it will only unlock the VB project for you. http://www.ozgrid.com/forum/showthread.php?t=13006&page=2

I haven't tried either method, but this may save you some time if it's what you need to do...

PHP: convert spaces in string into %20?

Use the rawurlencode function instead.

How to detect online/offline event cross-browser?

In HTML5 you can use the navigator.onLine property. Look here:

http://www.w3.org/TR/offline-webapps/#related

Probably your current behavior is random as the javascript only ready the "browser" variable and then knows if you're offline and online, but it doesn't actually check the Network Connection.

Let us know if this is what you're looking for.

Kind Regards,

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

<img title="<a href="javascript:alert('hello world')">The Link</a>" /> 

Why do I need to do `--set-upstream` all the time?

Because git has the cool ability to push/pull different branches to different "upstream" repositories. You could even use separate repositories for pushing and pulling - on the same branch. This can create a distributed, multi-level flow, I can see this being useful on project such as the Linux kernel. Git was originally built to be used on that project.

As a consequence, it does not make assumption about which repo your branch should be tracking.

On the other hand, most people do not use git in this way, so it might make a good case for a default option.

Git is generally pretty low-level and it can be frustrating. Yet there are GUIs and it should be easy to write helper scripts if you still want to use it from the shell.

'"SDL.h" no such file or directory found' when compiling

Having a similar case and I couldn't use StackAttacks solution as he's referring to SDL2 which is for the legacy code I'm using too new.

Fortunately our friends from askUbuntu had something similar:

Download SDL

tar xvf SDL-1.2.tar.gz
cd SDL-1.2
./configure
make
sudo make install

How do I initialize Kotlin's MutableList to empty MutableList?

Various forms depending on type of List, for Array List:

val myList = mutableListOf<Kolory>() 
// or more specifically use the helper for a specific list type
val myList = arrayListOf<Kolory>()

For LinkedList:

val myList = linkedListOf<Kolory>()
// same as
val myList: MutableList<Kolory> = linkedListOf()

For other list types, will be assumed Mutable if you construct them directly:

val myList = ArrayList<Kolory>()
// or
val myList = LinkedList<Kolory>()

This holds true for anything implementing the List interface (i.e. other collections libraries).

No need to repeat the type on the left side if the list is already Mutable. Or only if you want to treat them as read-only, for example:

val myList: List<Kolory> = ArrayList()

Is the 'as' keyword required in Oracle to define an alias?

There is no difference between both, AS is just a more explicit way of mentioning the alias which is good because some dependent libraries depends on this small keyword. e.g. JDBC 4.0. Depend on use of it, different behaviour can be observed.

See this. I would always suggest to use the full form of semantic to avoid such issues.

How do I put a border around an Android textview?

Changing Konstantin Burov answer because not work in my case:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />
            <stroke android:width="2dip" android:color="#4fa5d5"/>
            <corners android:radius="7dp"/>
        </shape>
    </item>
</selector>

compileSdkVersion 26 (Android 8.0), minSdkVersion 21 (Android 5.0), targetSdkVersion 26, implementation 'com.android.support:appcompat-v7:26.1.0', gradle:4.1

How to add content to html body using JS?

You can use

document.getElementById("parentID").appendChild(/*..your content created using DOM methods..*/)

or

document.getElementById("parentID").innerHTML+= "new content"

Get all child elements

Yes, you can use find_elements_by_ to retrieve children elements into a list. See the python bindings here: http://selenium-python.readthedocs.io/locating-elements.html

Example HTML:

<ul class="bar">
    <li>one</li>
    <li>two</li>
    <li>three</li>
</ul>

You can use the find_elements_by_ like so:

parentElement = driver.find_element_by_class_name("bar")
elementList = parentElement.find_elements_by_tag_name("li")

If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.

How to recover just deleted rows in mysql?

As Mitch mentioned, backing data up is the best method.

However, it maybe possible to extract the lost data partially depending on the situation or DB server used. For most part, you are out of luck if you don't have any backup.

Simpler way to create dictionary of separate variables?

In reading the thread, I saw an awful lot of friction. It's easy enough to give a bad answer, then let someone give the correct answer. Anyway, here is what I found.

From: [effbot.org] (http://effbot.org/zone/python-objects.htm#names)

The names are a bit different — they’re not really properties of the object, and the object itself doesn't know what it’s called.

An object can have any number of names, or no name at all.

Names live in namespaces (such as a module namespace, an instance namespace, a function’s local namespace).

Note: that it says the object itself doesn’t know what it’s called, so that was the clue. Python objects are not self-referential. Then it says, Names live in namespaces. We have this in TCL/TK. So maybe my answer will help (but it did help me)


    jj = 123
    print eval("'" + str(id(jj)) + "'")
    print dir()

166707048
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'jj']

So there is 'jj' at the end of the list.

Rewrite the code as:


    jj = 123
    print eval("'" + str(id(jj)) + "'")
    for x in dir():
        print id(eval(x))

161922920
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'jj']
3077447796
136515736
3077408320
3077656800
136515736
161922920

This nasty bit of code id's the name of variable/object/whatever-you-pedantics-call-it.

So, there it is. The memory address of 'jj' is the same when we look for it directly, as when we do the dictionary look up in global name space. I'm sure you can make a function to do this. Just remember which namespace your variable/object/wypci is in.

QED.

What is the difference between Jupyter Notebook and JupyterLab?

Jupyter Notebook is a web-based interactive computational environment for creating Jupyter notebook documents. It supports several languages like Python (IPython), Julia, R etc. and is largely used for data analysis, data visualization and further interactive, exploratory computing.

JupyterLab is the next-generation user interface including notebooks. It has a modular structure, where you can open several notebooks or files (e.g. HTML, Text, Markdowns etc) as tabs in the same window. It offers more of an IDE-like experience.

For a beginner I would suggest starting with Jupyter Notebook as it just consists of a filebrowser and an (notebook) editor view. It might be easier to use. If you want more features, switch to JupyterLab. JupyterLab offers much more features and an enhanced interface, which can be extended through extensions: JupyterLab Extensions (GitHub)

How I can print to stderr in C?

Some examples of formatted output to stdout and stderr:

printf("%s", "Hello world\n");              // "Hello world" on stdout (using printf)
fprintf(stdout, "%s", "Hello world\n");     // "Hello world" on stdout (using fprintf)
fprintf(stderr, "%s", "Stack overflow!\n"); // Error message on stderr (using fprintf)

importing go files in same folder

No import is necessary as long as you declare both a.go and b.go to be in the same package. Then, you can use go run to recognize multiple files with:

$ go run a.go b.go

Slidedown and slideup layout with animation

I had a similar requirement in the app I am working on. And, I found a third-party library which does a slide-up, slide-down and slide-right in Android.

Refer to the link for more details: https://github.com/mancj/SlideUp-Android

To set up the library(copied from the ReadMe portion of its Github page on request):

Get SlideUp library

Add the JitPack repository to your build file. Add it in your root build.gradle at the end of repositories:

allprojects {
  repositories {
    ...
    maven { url 'https://jitpack.io' }
    maven { url "https://maven.google.com" } // or google() in AS 3.0
  }
}

Add the dependency (in the Module gradle)

dependencies {
    compile 'com.github.mancj:SlideUp-Android:2.2.1'
    compile 'ru.ztrap:RxSlideUp2:2.x.x' //optional, for reactive listeners based on RxJava-2
    compile 'ru.ztrap:RxSlideUp:1.x.x' //optional, for reactive listeners based on RxJava
}

To add the SlideUp into your project, follow these three simple steps:

Step 1:

create any type of layout

<LinearLayout
  android:id="@+id/slideView"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

Step 2:

Find that view in your activity/fragment

View slideView = findViewById(R.id.slideView);

Step 3:

Create a SlideUp object and pass in your view

slideUp = new SlideUpBuilder(slideView)
                .withStartState(SlideUp.State.HIDDEN)
                .withStartGravity(Gravity.BOTTOM)

                //.withSlideFromOtherView(anotherView)
                //.withGesturesEnabled()
                //.withHideSoftInputWhenDisplayed()
                //.withInterpolator()
                //.withAutoSlideDuration()
                //.withLoggingEnabled()
                //.withTouchableAreaPx()
                //.withTouchableAreaDp()
                //.withListeners()
                //.withSavedState()
                .build();

You may also refer to the sample project on the link. I found it quite useful.

Getting data-* attribute for onclick event for an html element

Like this:

$(this).data('id');
$(this).data('option');

Working example: http://jsfiddle.net/zwHUc/

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)

How to exit in Node.js

I was able to get all my node processes to die directly from the Git Bash shell on Windows 10 by typing taskkill -F -IM node.exe - this ends all the node processes on my computer at once. I found I could also use taskkill //F //IM node.exe. Not sure why both - and // work in this context. Hope this helps!

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

How to loop through key/value object in Javascript?

Something like this:

setUsers = function (data) {
    for (k in data) {
        user[k] = data[k];
    }
}

Maximum concurrent Socket.IO connections

I tried to use socket.io on AWS, I can at most keep around 600 connections stable.

And I found out it is because socket.io used long polling first and upgraded to websocket later.

after I set the config to use websocket only, I can keep around 9000 connections.

Set this config at client side:

const socket = require('socket.io-client')
const conn = socket(host, { upgrade: false, transports: ['websocket'] })

regex error - nothing to repeat

Beyond the bug that was discovered and fixed, I'll just note that the error message sre_constants.error: nothing to repeat is a bit confusing. I was trying to use r'?.*' as a pattern, and thought it was complaining for some strange reason about the *, but the problem is actually that ? is a way of saying "repeat zero or one times". So I needed to say r'\?.*'to match a literal ?

Format date in a specific timezone

A couple of answers already mention that moment-timezone is the way to go with named timezone. I just want to clarify something about this library that was pretty confusing to me. There is a difference between these two statements:

moment.tz(date, format, timezone)

moment(date, format).tz(timezone)

Assuming that a timezone is not specified in the date passed in:

The first code takes in the date and assumes the timezone is the one passed in. The second one will take date, assume the timezone from the browser and then change the time and timezone according to the timezone passed in.

Example:

moment.tz('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss', 'UTC').format() // "2018-07-17T19:00:00Z"

moment('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss').tz('UTC').format() // "2018-07-18T00:00:00Z"

My timezone is +5 from utc. So in the first case it does not change and it sets the date and time to have utc timezone.

In the second case, it assumes the date passed in is in -5, then turns it into UTC, and that's why it spits out the date "2018-07-18T00:00:00Z"

NOTE: The format parameter is really important. If omitted moment might fall back to the Date class which can unpredictable behaviors


Assuming the timezone is specified in the date passed in:

In this case they both behave equally


Even though now I understand why it works that way, I thought this was a pretty confusing feature and worth explaining.

LaTeX Optional Arguments

Here's my attempt, it doesn't follow your specs exactly though. Not fully tested, so be cautious.

\newcount\seccount

\def\sec{%
    \seccount0%
    \let\go\secnext\go
}

\def\secnext#1{%
    \def\last{#1}%
    \futurelet\next\secparse
}

\def\secparse{%
    \ifx\next\bgroup
        \let\go\secparseii
    \else
        \let\go\seclast
    \fi
    \go
}

\def\secparseii#1{%
    \ifnum\seccount>0, \fi
    \advance\seccount1\relax
    \last
    \def\last{#1}%
    \futurelet\next\secparse
}

\def\seclast{\ifnum\seccount>0{} and \fi\last}%

\sec{a}{b}{c}{d}{e}
% outputs "a, b, c, d and e"

\sec{a}
% outputs "a"

\sec{a}{b}
% outputs "a and b"

Connect to mysql on Amazon EC2 from a remote server

Change /etc/mysql/my.cnf:

bind-address            = 127.0.0.1 to 0.0.0.0

Create user with '%' host and restart:

/etc/init.d/mysql restart

Works for me! :)

How is a JavaScript hash map implemented?

Here is an easy and convenient way of using something similar to the Java map:

var map= {
    'map_name_1': map_value_1,
    'map_name_2': map_value_2,
    'map_name_3': map_value_3,
    'map_name_4': map_value_4
    }

And to get the value:

alert( map['map_name_1'] );    // fives the value of map_value_1

......  etc  .....

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Try this in Sql Server

SELECT 
      start_date as firstdate,end_date as seconddate
       ,cast(datediff(MI,start_date,end_date)as decimal(10,3)) as minutediff
      ,cast(cast(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) as int ) as varchar(10)) + ' ' + 'Days' + ' ' 
      + cast(cast((cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) - 
        floor(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)) ) * 24 as int) as varchar(10)) + ':' 

     + cast( cast(((cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) 
      - floor(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)))*24
        -
        cast(floor((cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60) 
      - floor(cast(datediff(MI,start_date,end_date)as decimal(10,3)) / (24*60)))*24) as decimal)) * 60 as int) as varchar(10))

    FROM [AdventureWorks2012].dbo.learndate

add class with JavaScript

There is build in forEach loop for array in ECMAScript 5th Edition.

var buttons = document.getElementsByClassName("navButton");

Array.prototype.forEach.call(buttons,function(button) { 
    button.setAttribute("class", "active");
    button.setAttribute("src", "images/arrows/top_o.png"); 
});

Select Rows with id having even number

Sql Server we can use %

select * from orders where ID % 2 = 0;

This can be used in both Mysql and oracle. It is more affection to use mod function that %.

select * from orders where mod(ID,2) = 0

Is the Javascript date object always one day off?

The following worked for me -

    var doo = new Date("2011-09-24").format("m/d/yyyy");

Convert a Unix timestamp to time in JavaScript

function getTIMESTAMP() {
  var date = new Date();
  var year = date.getFullYear();
  var month = ("0" + (date.getMonth() + 1)).substr(-2);
  var day = ("0" + date.getDate()).substr(-2);
  var hour = ("0" + date.getHours()).substr(-2);
  var minutes = ("0" + date.getMinutes()).substr(-2);
  var seconds = ("0" + date.getSeconds()).substr(-2);

  return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
}

//2016-01-14 02:40:01

Check time difference in Javascript

grab the input values after form submission in php

$start_time = $_POST('start_time');
$end_time =$_POST('end_time');
$start = $start_time;
$end = $end_time;
$datetime1 = new DateTime($end);
$datetime2 = new DateTime($start);
//echo $datetime1->format('H:i:s');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%h:%i');
$time = explode(":",$elapsed);
$hours = $time[0];
$minutes = $time[1];
$tminutes = $minutes + ($hours*60);

the variable $tminutes is total diff in minutes , working hour is $hour . this code is for php use this logic and convert this code to js

PyLint "Unable to import" error - how to set PYTHONPATH?

I had to update the system PYTHONPATH variable to add my App Engine path. In my case I just had to edit my ~/.bashrc file and add the following line:

export PYTHONPATH=$PYTHONPATH:/path/to/google_appengine_folder

In fact, I tried setting the init-hook first but this did not resolve the issue consistently across my code base (not sure why). Once I added it to the system path (probably a good idea in general) my issues went away.

Convert a matrix to a 1 dimensional array

Simple and fast since a 1d array is essentially a vector

vector <- array[1:length(array)]

Reference an Element in a List of Tuples

So you have "a list of tuples", let me assume that you are manipulating some 2-dimension matrix, and, in this case, one convenient interface to accomplish what you need is the one numpy provides.

Say you have an array arr = numpy.array([[1, 2], [3, 4], [5, 6]]), you can use arr[:, 0] to get a new array of all the first elements in each "tuple".

How do I get the scroll position of a document?

You can try this for example, this code put the scrollbar at the bottom for all DIV tags

Remember: jQuery can accept a function instead the value as argument. "this" is the object treated by jQuery, the function returns the scrollHeight property of the current DIV "this" and do it for all DIV in the document.

$("div").scrollTop(function(){return this.scrollHeight})

Writing file to web server - ASP.NET

There are methods like WriteAllText in the File class for common operations on files.

Use the MapPath method to get the physical path for a file in your web application.

File.WriteAllText(Server.MapPath("~/data.txt"), TextBox1.Text);

what is an illegal reflective access

If you want to go with the add-open option, here's a command to find which module provides which package ->

java --list-modules | tr @ " " | awk '{ print $1 }' | xargs -n1 java -d

the name of the module will be shown with the @ while the name of the packages without it

NOTE: tested with JDK 11

IMPORTANT: obviously is better than the provider of the package does not do the illegal access

Setting default value for TypeScript object passed as argument

Here is something to try, using interface and destructuring with default values. Please note that "lastName" is optional.

interface IName {
  firstName: string
  lastName?: string
}

function sayName(params: IName) {
  const { firstName, lastName = "Smith" } = params
  const fullName = `${firstName} ${lastName}`

  console.log("FullName-> ", fullName)
}

sayName({ firstName: "Bob" })

"RangeError: Maximum call stack size exceeded" Why?

Browsers can't handle that many arguments. See this snippet for example:

alert.apply(window, new Array(1000000000));

This yields RangeError: Maximum call stack size exceeded which is the same as in your problem.

To solve that, do:

var arr = [];
for(var i = 0; i < 1000000; i++){
    arr.push(Math.random());
}

Which MySQL datatype to use for an IP address?

You have two possibilities (for an IPv4 address) :

  • a varchar(15), if your want to store the IP address as a string
    • 192.128.0.15 for instance
  • an integer (4 bytes), if you convert the IP address to an integer
    • 3229614095 for the IP I used before


The second solution will require less space in the database, and is probably a better choice, even if it implies a bit of manipulations when storing and retrieving the data (converting it from/to a string).

About those manipulations, see the ip2long() and long2ip() functions, on the PHP-side, or inet_aton() and inet_ntoa() on the MySQL-side.

Where is Xcode's build folder?

It should by located in: ~/Library/Developer/Xcode/DerivedData.

If you changed the defaults, you can see where the build directory is by going to File->Workspace Settings then look at Build Location

Inner text shadow with CSS

text-shadow: 4px 4px 2px rgba(150, 150, 150, 1);

for box shadow:

-webkit-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);
-moz-box-shadow:    7px 7px 5px rgba(50, 50, 50, 0.75);
box-shadow:         7px 7px 5px rgba(50, 50, 50, 0.75);

you can see online text and box shadow: online text and box shadow

for more example you can go to this address : more example code freeclup

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

You need to restart VirtualBox service you can do it with this:

sudo /Library/StartupItems/VirtualBox/VirtualBox restart

If in this path is empty you can use:

sudo /Library/Application\ Support/VirtualBox/LaunchDaemons/VirtualBoxStartup.sh restart

After I use Parallels I always need to do it.

"Register" an .exe so you can run it from any command line in Windows

Let's say my exe is C:\Program Files\AzCopy\azcopy.exe

Command/CMD/Batch

SET "PATH=C:\Program Files\AzCopy;%PATH%"

PowerShell

$env:path = $env:path + ";C:\Program Files\AzCopy"

I can now simply type and use azcopy from any location from any shell inc command prompt, powershell, git bash etc

ImportError: numpy.core.multiarray failed to import

In my case installing from apt solved my problem.

You can try uninstall it from pip and install from apt (if you are using ubuntu etc.)

pip3 uninstall numpy
sudo apt-get install python3-numpy

REST API error code 500 handling

80 % of the times, this would due to wrong input by in soapRequest.xml file

How to declare Return Types for Functions in TypeScript

You can read more about function types in the language specification in sections 3.5.3.5 and 3.5.5.

The TypeScript compiler will infer types when it can, and this is done you do not need to specify explicit types. so for the greeter example, greet() returns a string literal, which tells the compiler that the type of the function is a string, and no need to specify a type. so for instance in this sample, I have the greeter class with a greet method that returns a string, and a variable that is assigned to number literal. the compiler will infer both types and you will get an error if you try to assign a string to a number.

class Greeter {
    greet() {
        return "Hello, ";  // type infered to be string
    }
} 

var x = 0; // type infered to be number

// now if you try to do this, you will get an error for incompatable types
x = new Greeter().greet(); 

Similarly, this sample will cause an error as the compiler, given the information, has no way to decide the type, and this will be a place where you have to have an explicit return type.

function foo(){
    if (true)
        return "string"; 
    else 
        return 0;
}

This, however, will work:

function foo() : any{
    if (true)
        return "string"; 
    else 
        return 0;
}

PHP - Debugging Curl

You can enable the CURLOPT_VERBOSE option and log that information to a (temporary) CURLOPT_STDERR:

// CURLOPT_VERBOSE: TRUE to output verbose information. Writes output to STDERR, 
// or the file specified using CURLOPT_STDERR.
curl_setopt($handle, CURLOPT_VERBOSE, true);

$verbose = fopen('php://temp', 'w+');
curl_setopt($handle, CURLOPT_STDERR, $verbose);

You can then read it after curl has done the request:

$result = curl_exec($handle);
if ($result === FALSE) {
    printf("cUrl error (#%d): %s<br>\n", curl_errno($handle),
           htmlspecialchars(curl_error($handle)));
}

rewind($verbose);
$verboseLog = stream_get_contents($verbose);

echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";

(I originally answered similar but more extended in a related question.)

More information like metrics about the last request is available via curl_getinfo. This information can be useful for debugging curl requests, too. A usage example, I would normally wrap that into a function:

$version = curl_version();
extract(curl_getinfo($handle));
$metrics = <<<EOD
URL....: $url
Code...: $http_code ($redirect_count redirect(s) in $redirect_time secs)
Content: $content_type Size: $download_content_length (Own: $size_download) Filetime: $filetime
Time...: $total_time Start @ $starttransfer_time (DNS: $namelookup_time Connect: $connect_time Request: $pretransfer_time)
Speed..: Down: $speed_download (avg.) Up: $speed_upload (avg.)
Curl...: v{$version['version']}
EOD;

Vector erase iterator

Something that you can do with modern C++ is using "std::remove_if" and lambda expression;

This code will remove "3" of the vector

vector<int> vec {1,2,3,4,5,6};

vec.erase(std::remove_if(begin(vec),end(vec),[](int elem){return (elem == 3);}), end(vec));

Moment Js UTC to Local Time

Note: please update the date format accordingly.

Format Date

   __formatDate: function(myDate){
      var ts = moment.utc(myDate);
      return ts.local().format('D-MMM-Y');
   }

Format Time

  __formatTime: function(myDate){
      var ts = moment.utc(myDate);
      return ts.local().format('HH:mm');
  },

What's the strangest corner case you've seen in C# or .NET?

Few years ago, when working on loyality program, we had an issue with the amount of points given to customers. The issue was related to casting/converting double to int.

In code below:

double d = 13.6;

int i1 = Convert.ToInt32(d);
int i2 = (int)d;

does i1 == i2 ?

It turns out that i1 != i2. Because of different rounding policies in Convert and cast operator the actual values are:

i1 == 14
i2 == 13

It's always better to call Math.Ceiling() or Math.Floor() (or Math.Round with MidpointRounding that meets our requirements)

int i1 = Convert.ToInt32( Math.Ceiling(d) );
int i2 = (int) Math.Ceiling(d);

How do I use a Boolean in Python?

True ... and False obviously.

Otherwise, None evaluates to False, as does the integer 0 and also the float 0.0 (although I wouldn't use floats like that). Also, empty lists [], empty tuplets (), and empty strings '' or "" evaluate to False.

Try it yourself with the function bool():

bool([])
bool(['a value'])
bool('')
bool('A string')
bool(True)  # ;-)
bool(False)
bool(0)
bool(None)
bool(0.0)
bool(1)

etc..

Difference between `Optional.orElse()` and `Optional.orElseGet()`

I would say the biggest difference between orElse and orElseGet comes when we want to evaluate something to get the new value in the else condition.

Consider this simple example -

// oldValue is String type field that can be NULL
String value;
if (oldValue != null) {
    value = oldValue;
} else {
    value = apicall().value;
}

Now let's transform the above example to using Optional along with orElse,

// oldValue is Optional type field
String value = oldValue.orElse(apicall().value);

Now let's transform the above example to using Optional along with orElseGet,

// oldValue is Optional type field
String value = oldValue.orElseGet(() -> apicall().value);

When orElse is invoked, the apicall().value is evaluated and passed to the method. Whereas, in the case of orElseGet the evaluation only happens if the oldValue is empty. orElseGet allows lazy evaluation.

Some projects cannot be imported because they already exist in the workspace error in Eclipse

New to Eclipse and Android development and this hung me up for quite a while. Here's a few things I was doing wrong that may help someone in the future:

  1. I was downloading code examples and assuming project name would be the same as the folder name and was looking for that folder name in the project explorer, not finding it, re-importing it, then getting the error message it already existed in the workspace. Yeah. Not proud of that.
  2. Didn't click on 'Copy projects into Workspace' and then searched in vain through the workspace when it didn't appear in the project explorer BECAUSE
  3. The 'Add project to working sets' option in the Import Projects tab isn't working as far as I can tell, so was not appearing in the project explorer for the active working set (refresh made no difference). Adding project to the working set had to be done after successfully importing it.

How to customize message box

You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:

FormBorderStyle    FixedToolWindow
ShowInTaskBar      False
StartPosition      CenterScreen

To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:

MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
    // etc
}

It would be advisable to add your own Show method that takes the text and other options you require:

public DialogResult Show(string text, Color foreColour)
{
     lblText.Text = text;
     lblText.ForeColor = foreColour;
     return this.ShowDialog();
}

Running a CMD or BAT in silent mode

I'm created RunApp to do such a job and also using it in my production env, hope it's helps.

The config like below:

file: config.arg

:style:hidden

MyBatchFile.bat
arg1
arg2

And launch runapp.exe instead.

how to loop through json array in jquery?

Try this:

var data = jQuery.parseJSON(response);
$.each(data, function(key, item) 
{
   console.log(item.com);
});

or

var data = $.parseJSON(response);

$(data).each(function(i,val)
 {
    $.each(val,function(key,val)
  {
          console.log(key + " : " + val);     
  });
});

Callback after all asynchronous forEach callbacks are completed

It's odd how many incorrect answers has been given to asynchronous case! It can be simply shown that checking index does not provide expected behavior:

// INCORRECT
var list = [4000, 2000];
list.forEach(function(l, index) {
    console.log(l + ' started ...');
    setTimeout(function() {
        console.log(index + ': ' + l);
    }, l);
});

output:

4000 started
2000 started
1: 2000
0: 4000

If we check for index === array.length - 1, callback will be called upon completion of first iteration, whilst first element is still pending!

To solve this problem without using external libraries such as async, I think your best bet is to save length of list and decrement if after each iteration. Since there's just one thread we're sure there no chance of race condition.

var list = [4000, 2000];
var counter = list.length;
list.forEach(function(l, index) {
    console.log(l + ' started ...');
    setTimeout(function() {
        console.log(index + ': ' + l);
        counter -= 1;
        if ( counter === 0)
            // call your callback here
    }, l);
});

How to use font-awesome icons from node-modules

If you're using npm you could use Gulp.js a build tool to build your Font Awesome packages from SCSS or LESS. This example will compile the code from SCSS.

  1. Install Gulp.js v4 locally and CLI V2 globally.

  2. Install a plugin called gulp-sass using npm.

  3. Create a main.scss file in your public folder and use this code:

    $fa-font-path: "../webfonts";
    @import "fontawesome/fontawesome";
    @import "fontawesome/brands";
    @import "fontawesome/regular";
    @import "fontawesome/solid";
    @import "fontawesome/v4-shims";
    
  4. Create a gulpfile.js in your app directory and copy this.

    const { src, dest, series, parallel } = require('gulp');
    const sass = require('gulp-sass');
    const fs = require('fs');
    
    function copyFontAwesomeSCSS() {
       return src('node_modules/@fortawesome/fontawesome-free/scss/*.scss')
         .pipe(dest('public/scss/fontawesome'));
    }
    
    function copyFontAwesomeFonts() {
       return src('node_modules/@fortawesome/fontawesome-free/webfonts/*')
         .pipe(dest('public/dist/webfonts'));
     }
    
     function compileSCSS() { 
       return src('./public/scss/theme.scss')
         .pipe(sass()).pipe(dest('public/css'));
     }
    
     // Series completes tasks sequentially and parallel completes them asynchronously
     exports.build = parallel(
       copyFontAwesomeFonts,
       series(copyFontAwesomeSCSS, compileSCSS)
     );
    
  5. Run 'gulp build' in your command line and watch the magic.

How to read all files in a folder from Java?

File directory = new File("/user/folder");      
File[] myarray;  
myarray=new File[10];
myarray=directory.listFiles();
for (int j = 0; j < myarray.length; j++)
{
       File path=myarray[j];
       FileReader fr = new FileReader(path);
       BufferedReader br = new BufferedReader(fr);
       String s = "";
       while (br.ready()) {
          s += br.readLine() + "\n";
       }
}

How to sort Counter by value? - python

Yes:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})

Using the sorted keyword key and a lambda function:

>>> sorted(x.items(), key=lambda i: i[1])
[('b', 3), ('a', 5), ('c', 7)]
>>> sorted(x.items(), key=lambda i: i[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

This works for all dictionaries. However Counter has a special function which already gives you the sorted items (from most frequent, to least frequent). It's called most_common():

>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
>>> list(reversed(x.most_common()))  # in order of least to most
[('b', 3), ('a', 5), ('c', 7)]

You can also specify how many items you want to see:

>>> x.most_common(2)  # specify number you want
[('c', 7), ('a', 5)]

Using a Glyphicon as an LI bullet point (Bootstrap 3)

If you want to have a different icon for each list-item, I suggest adding icons in HTML instead of using a pseudo element to keep your CSS down. It can be done quite simply as follows:

<ul>
  <li><span><i class="mdi mdi-lightbulb-outline"></i></span>An electric light with a wire filament heated to such a high temperature that it glows with visible light</li>
  <li><span><i class="mdi mdi-clipboard-check-outline"></i></span>A thin, rigid board with a clip at the top for holding paper in place.</li>
  <li><span><i class="mdi mdi-finance"></i></span>A graphical representation of data, in which the data is represented by symbols, such as bars in a bar chart, lines in a line chart, or slices in a pie chart.</li>
  <li><span><i class="mdi mdi-server"></i></span>A system that responds to requests across a computer network worldwide to provide, or help to provide, a network or data service.</li>
</ul>

-

ul {
  list-style-type: none;
  margin-left: 2.5em;
  padding-left: 0;
}
ul>li {
  position: relative;
}
span {
  left: -2em;
  position: absolute;
  text-align: center;
  width: 2em;
  line-height: inherit;
}

enter image description here

In this case I used Material Design Icons

VIEW DEMO

Intent.putExtra List

you can do it in two ways using

  • Serializable

  • Parcelable.

This examle will show you how to implement it with serializable

class Customer implements Serializable
{
   // properties, getter setters & constructor
}

// This is your custom object
Customer customer = new Customer(name, address, zip);

Intent intent = new Intent();
intent.setClass(SourceActivity.this, TargetActivity.this);
intent.putExtra("customer", customer);
startActivity(intent);

// Now in your TargetActivity
Bundle extras = getIntent().getExtras();
if (extras != null)
{
    Customer customer = (Customer)extras.getSerializable("customer");
    // do something with the customer
}

Now have a look at this. This link will give you a brief overview of how to implement it with Parcelable.

Look at this.. This discussion will let you know which is much better way to implement it.

Thanks.

How to establish a connection pool in JDBC?

HikariCP

It's modern, it's fast, it's simple. I use it for every new project. I prefer it a lot over C3P0, don't know the other pools too well.

Simple Vim commands you wish you'd known earlier

^y will copy the character above the cursor.

How to check if an environment variable exists and get its value?

There is no difference between environment variables and variables in a script. Environment variables are just defined earlier, outside the script, before the script is called. From the script's point of view, a variable is a variable.

You can check if a variable is defined:

if [ -z "$a" ]
then
    echo "not defined"
else 
    echo "defined"
fi

and then set a default value for undefined variables or do something else.

The -z checks for a zero-length (i.e. empty) string. See man bash and look for the CONDITIONAL EXPRESSIONS section.

You can also use set -u at the beginning of your script to make it fail once it encounters an undefined variable, if you want to avoid having an undefined variable breaking things in creative ways.

Does MySQL foreign_key_checks affect the entire database?

As explained by Ron, there are two variables, local and global. The local variable is always used, and is the same as global upon connection.

SET FOREIGN_KEY_CHECKS=0;
SET GLOBAL FOREIGN_KEY_CHECKS=0;

SHOW Variables WHERE Variable_name='foreign_key_checks'; # always shows local variable

When setting the GLOBAL variable, the local one isn't changed for any existing connections. You need to reconnect or set the local variable too.

Perhaps unintuitive, MYSQL does not enforce foreign keys when FOREIGN_KEY_CHECKS are re-enabled. This makes it possible to create an inconsistent database even though foreign keys and checks are on.

If you want your foreign keys to be completely consistent, you need to add the keys while checking is on.

Database corruption with MariaDB : Table doesn't exist in engine

You may try to:

  • backup your database folder from C:\xampp\mysql\data (.frm & .ibd files only corresponding your table names)
  • reinstall xampp and recopy DB folder at C:\xampp\mysql\data
  • modify my.ini add

    [mysqld]
    innodb_file_per_table = on
    
  • then open phpmyadmin (or any other DB viewer as Navicat or MYSQL Workbench) and run

    ALTER TABLE tbl_name IMPORT TABLESPACE 
    

    for each table

  • Once you can open your tables make a full mysql dump

  • delete everything and make a clean install

I know, a lot of work to do that you don't need it.

Adding a Time to a DateTime in C#

Using https://github.com/FluentDateTime/FluentDateTime

DateTime dateTime = DateTime.Now;
DateTime combined = dateTime + 36.Hours();
Console.WriteLine(combined);

How to display div after click the button in Javascript?

<div  style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" onclick="document.getElementsByClassName('answer_list')[0].style.display = 'auto';">

Create a jTDS connection string

jdbc:jtds:sqlserver://x.x.x.x/database replacing x.x.x.x with the IP or hostname of your SQL Server machine.

jdbc:jtds:sqlserver://MYPC/Blog;instance=SQLEXPRESS

or

jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS

If you are wanting to set the username and password in the connection string too instead of against a connection object separately:

jdbc:jtds:sqlserver://MYPC/Blog;instance=SQLEXPRESS;user=foo;password=bar

(Updated my incorrect information and add reference to the instance syntax)

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

concat scope variables into string in angular directive expression

You can just concat the values using +

<a ng-click="$navigate.go('#/path/' + obj.val1 + '/' + obj.val2)">{{obj.val1}}, {{obj.val2}}</a>

Simple example on jsfiddle

I am sure the code you posted is a simplified example, if your path building is more complex I would recommend extracting out a function (or service) that would build your urls so you can effectively write unit test.

The transaction manager has disabled its support for remote/network transactions

Make sure that the "Distributed Transaction Coordinator" Service is running on both database and client. Also make sure you check "Network DTC Access", "Allow Remote Client", "Allow Inbound/Outbound" and "Enable TIP".

To enable Network DTC Access for MS DTC transactions

  1. Open the Component Services snap-in.

    To open Component Services, click Start. In the search box, type dcomcnfg, and then press ENTER.

  2. Expand the console tree to locate the DTC (for example, Local DTC) for which you want to enable Network MS DTC Access.

  3. On the Action menu, click Properties.

  4. Click the Security tab and make the following changes: In Security Settings, select the Network DTC Access check box.

    In Transaction Manager Communication, select the Allow Inbound and Allow Outbound check boxes.

How to convert minutes to hours/minutes and add various time values together using jQuery?

In case you want to return a string in 00:00 format...

convertMinsToHrsMins: function (minutes) {
  var h = Math.floor(minutes / 60);
  var m = minutes % 60;
  h = h < 10 ? '0' + h : h;
  m = m < 10 ? '0' + m : m;
  return h + ':' + m;
}

Thanks for the up-votes. Here's a slightly tidier ES6 version :)

const convertMinsToHrsMins = (mins) => {
  let h = Math.floor(mins / 60);
  let m = mins % 60;
  h = h < 10 ? '0' + h : h;
  m = m < 10 ? '0' + m : m;
  return `${h}:${m}`;
}

Plotting histograms from grouped data in a pandas DataFrame

With recent version of Pandas, you can do df.N.hist(by=df.Letter)

Just like with the solutions above, the axes will be different for each subplot. I have not solved that one yet.

Pip install - Python 2.7 - Windows 7

pip is installed by default when we install Python in windows. After setting up the environment variables path for python executables, we can run python interpreter from the command line on windows CMD After that, we can directly use the python command with pip option to install further packages as following:-

C:\ python -m pip install python_module_name

This will install the module using pip.

How to use if statements in underscore.js templates?

From here:

"You can also refer to the properties of the data object via that object, instead of accessing them as variables." Meaning that for OP's case this will work (with a significantly smaller change than other possible solutions):

<% if (obj.date) { %><span class="date"><%= date %></span><% }  %>

How to dynamically add elements to String array?

You cant add add items in string array more than its size, i'll suggest you to use ArrayList you can add items dynamically at run time in arrayList if you feel any problem you can freely ask

Call to a member function fetch_assoc() on boolean in <path>

Please use if condition with while loop and try.

eg.

if ($result = $conn->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {

    }
    /* free result set */
    $result->free();
}

No module named MySQLdb

You need to use one of the following commands. Which one depends on what OS and software you have and use.

  1. easy_install mysql-python (mix os)
  2. pip install mysql-python (mix os/ python 2)
  3. pip install mysqlclient (mix os/ python 3)
  4. apt-get install python-mysqldb (Linux Ubuntu, ...)
  5. cd /usr/ports/databases/py-MySQLdb && make install clean (FreeBSD)
  6. yum install MySQL-python (Linux Fedora, CentOS ...)

For Windows, see this answer: Install mysql-python (Windows)

Alternate output format for psql

I just needed to spend more time staring at the documentation. This command:

\x on

will do exactly what I wanted. Here is some sample output:

select * from dda where u_id=24 and dda_is_deleted='f';
-[ RECORD 1 ]------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
dda_id             | 1121
u_id               | 24
ab_id              | 10304
dda_type           | CHECKING
dda_status         | PENDING_VERIFICATION
dda_is_deleted     | f
dda_verify_op_id   | 44938
version            | 2
created            | 2012-03-06 21:37:50.585845
modified           | 2012-03-06 21:37:50.593425
c_id               | 
dda_nickname       | 
dda_account_name   | 
cu_id              | 1
abd_id             | 

Linq where clause compare only date value without time value

EDIT

To avoid this error : The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

var _My_ResetSet_Array = _DB
                .tbl_MyTable
                .Where(x => x.Active == true)
                         .Select(x => x).ToList();

 var filterdata = _My_ResetSet_Array
        .Where(x=>DateTime.Compare(x.DateTimeValueColumn.Date, DateTime.Now.Date)  <= 0 );

The second line is required because LINQ to Entity is not able to convert date property to sql query. So its better to first fetch the data and then apply the date filter.

EDIT

If you just want to compare the date value of the date time than make use of

DateTime.Date Property - Gets the date component of this instance.

Code for you

var _My_ResetSet_Array = _DB
                .tbl_MyTable
                .Where(x => x.Active == true
     && DateTime.Compare(x.DateTimeValueColumn.Date, DateTime.Now.Date)  <= 0 )
                         .Select(x => x);

If its like that then use

DateTime.Compare Method - Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.

Code for you

var _My_ResetSet_Array = _DB
                .tbl_MyTable
                .Where(x => x.Active == true
                  && DateTime.Compare(x.DateTimeValueColumn, DateTime.Now)  <= 0 )
                         .Select(x => x);

Example

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

SQL: parse the first, middle and last name from a fullname field

Subject to the caveats that have already been raised regarding spaces in names and other anomalies, the following code will at least handle 98% of names. (Note: messy SQL because I don't have a regex option in the database I use.)

**Warning: messy SQL follows:

create table parsname (fullname char(50), name1 char(30), name2 char(30), name3 char(30), name4 char(40));
insert into parsname (fullname) select fullname from ImportTable;
update parsname set name1 = substring(fullname, 1, locate(' ', fullname)),
 fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))
 where locate(' ', rtrim(fullname)) > 0;
update parsname set name2 = substring(fullname, 1, locate(' ', fullname)),
 fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))
 where locate(' ', rtrim(fullname)) > 0;
update parsname set name3 = substring(fullname, 1, locate(' ', fullname)),
 fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))
 where locate(' ', rtrim(fullname)) > 0;
update parsname set name4 = substring(fullname, 1, locate(' ', fullname)),
 fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))
 where locate(' ', rtrim(fullname)) > 0;
// fullname now contains the last word in the string.
select fullname as FirstName, '' as MiddleName, '' as LastName from parsname where fullname is not null and name1 is null and name2 is null
union all
select name1 as FirstName, name2 as MiddleName, fullname as LastName from parsname where name1 is not null and name3 is null

The code works by creating a temporary table (parsname) and tokenizing the fullname by spaces. Any names ending up with values in name3 or name4 are non-conforming and will need to be dealt with differently.

Controlling mouse with Python

If you want to move the mouse, use this:

import pyautogui
pyautogui.moveTo(x,y)

If you want to click, use this:

import pyautogui
pyautogui.click(x,y)

If you don't have pyautogui installed, you must have python attached to CMD. Go to CMD and write: pip install pyautogui

This will install pyautogui for Python 2.x.

For Python 3.x, you will probably have to use pip3 install pyautogui or python3 -m pip install pyautogui.

Joda DateTime to Timestamp conversion

It is a common misconception that time (a measurable 4th dimension) is different over the world. Timestamp as a moment in time is unique. Date however is influenced how we "see" time but actually it is "time of day".

An example: two people look at the clock at the same moment. The timestamp is the same, right? But one of them is in London and sees 12:00 noon (GMT, timezone offset is 0), and the other is in Belgrade and sees 14:00 (CET, Central Europe, daylight saving now, offset is +2).

Their perception is different but the moment is the same.

You can find more details in this answer.

UPDATE

OK, it's not a duplicate of this question but it is pointless since you are confusing the terms "Timestamp = moment in time (objective)" and "Date[Time] = time of day (subjective)".

Let's look at your original question code broken down like this:

// Get the "original" value from database.
Timestamp momentFromDB = rs.getTimestamp("anytimestampcolumn");

// Turn it into a Joda DateTime with time zone.
DateTime dt = new DateTime(momentFromDB, DateTimeZone.forID("anytimezone"));

// And then turn it back into a timestamp but "with time zone".
Timestamp ts = new Timestamp(dt.getMillis());

I haven't run this code but I am certain it will print true and the same number of milliseconds each time:

System.out.println("momentFromDB == dt : " + (momentFromDB.getTime() == dt.getTimeInMillis());
System.out.println("momentFromDB == ts : " + (momentFromDB.getTime() == ts.getTime()));
System.out.println("dt == ts : " + (dt.getTimeInMillis() == ts.getTime()));

System.out.println("momentFromDB [ms] : " + momentFromDB.getTime());
System.out.println("ts [ms] : " + ts.getTime());
System.out.println("dt [ms] : " + dt.getTimeInMillis());

But as you said yourself printing them out as strings will result in "different" time because DateTime applies the time zone. That's why "time" is stored and transferred as Timestamp objects (which basically wraps a long) and displayed or entered as Date[Time].

In your own answer you are artificially adding an offset and creating a "wrong" time. If you use that timestamp to create another DateTime and print it out it will be offset twice.

// Turn it back into a Joda DateTime with time zone.
DateTime dt = new DateTime(ts, DateTimeZone.forID("anytimezone"));

P.S. If you have the time go through the very complex Joda Time source code to see how it holds the time (millis) and how it prints it.

JUnit Test as proof

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.junit.Before;
import org.junit.Test;


public class WorldTimeTest {
    private static final int MILLIS_IN_HOUR = 1000 * 60 * 60;
    private static final String ISO_FORMAT_NO_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSS";
    private static final String ISO_FORMAT_WITH_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    private TimeZone londonTimeZone;
    private TimeZone newYorkTimeZone;
    private TimeZone sydneyTimeZone;
    private long nowInMillis;
    private Date now;

    public static SimpleDateFormat createDateFormat(String pattern, TimeZone timeZone) throws Exception {
        SimpleDateFormat result = new SimpleDateFormat(pattern);
        // Must explicitly set the time zone with "setCalendar()".
        result.setCalendar(Calendar.getInstance(timeZone));
        return result;
    }

    public static SimpleDateFormat createDateFormat(String pattern) throws Exception {
        return createDateFormat(pattern, TimeZone.getDefault());
    }

    public static SimpleDateFormat createDateFormat() throws Exception {
        return createDateFormat(ISO_FORMAT_WITH_TZ, TimeZone.getDefault());
    }

    public void printSystemInfo() throws Exception {
        final String[] propertyNames = {
                "java.runtime.name", "java.runtime.version", "java.vm.name", "java.vm.version",
                "os.name", "os.version", "os.arch",
                "user.language", "user.country", "user.script", "user.variant",
                "user.language.format", "user.country.format", "user.script.format",
                "user.timezone" };

        System.out.println();
        System.out.println("System Information:");
        for (String name : propertyNames) {
            if (name == null || name.length() == 0) {
                continue;
            }
            String value = System.getProperty(name);
            if (value != null && value.length() > 0) {
                System.out.println("  " + name + " = " + value);
            }
        }

        final TimeZone defaultTZ = TimeZone.getDefault();
        final int defaultOffset = defaultTZ.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final int userOffset = TimeZone.getTimeZone(System
                .getProperty("user.timezone")).getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final Locale defaultLocale = Locale.getDefault();

        System.out.println("  default.timezone-offset (hours) = " + userOffset);
        System.out.println("  default.timezone = " + defaultTZ.getDisplayName());
        System.out.println("  default.timezone.id = " + defaultTZ.getID());
        System.out.println("  default.timezone-offset (hours) = " + defaultOffset);
        System.out.println("  default.locale = "
                + defaultLocale.getLanguage() + "_" + defaultLocale.getCountry()
                + " (" + defaultLocale.getDisplayLanguage()
                + "," + defaultLocale.getDisplayCountry() + ")");
        System.out.println("  now = " + nowInMillis + " [ms] or "
                + createDateFormat().format(now));
        System.out.println();
    }

    @Before
    public void setUp() throws Exception {
        // Remember this moment.
        now = new Date();
        nowInMillis = now.getTime(); // == System.currentTimeMillis();

        // Print out some system information.
        printSystemInfo();

        // "Europe/London" time zone is DST aware, we'll use fixed offset.
        londonTimeZone = TimeZone.getTimeZone("GMT");
        // The same applies to "America/New York" time zone ...
        newYorkTimeZone = TimeZone.getTimeZone("GMT-5");
        // ... and for the "Australia/Sydney" time zone.
        sydneyTimeZone = TimeZone.getTimeZone("GMT+10");
    }

    @Test
    public void testDateFormatting() throws Exception {
        int londonOffset = londonTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR; // in hours
        Calendar londonCalendar = Calendar.getInstance(londonTimeZone);
        londonCalendar.setTime(now);

        int newYorkOffset = newYorkTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar newYorkCalendar = Calendar.getInstance(newYorkTimeZone);
        newYorkCalendar.setTime(now);

        int sydneyOffset = sydneyTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar sydneyCalendar = Calendar.getInstance(sydneyTimeZone);
        sydneyCalendar.setTime(now);

        // Check each time zone offset.
        assertThat(londonOffset, equalTo(0));
        assertThat(newYorkOffset, equalTo(-5));
        assertThat(sydneyOffset, equalTo(10));

        // Check that calendars are not equals (due to time zone difference).
        assertThat(londonCalendar, not(equalTo(newYorkCalendar)));
        assertThat(londonCalendar, not(equalTo(sydneyCalendar)));

        // Check if they all point to the same moment in time, in milliseconds.
        assertThat(londonCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(newYorkCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(sydneyCalendar.getTimeInMillis(), equalTo(nowInMillis));

        // Check if they all point to the same moment in time, as Date.
        assertThat(londonCalendar.getTime(), equalTo(now));
        assertThat(newYorkCalendar.getTime(), equalTo(now));
        assertThat(sydneyCalendar.getTime(), equalTo(now));

        // Check if hours are all different (skip local time because
        // this test could be executed in those exact time zones).
        assertThat(newYorkCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));
        assertThat(sydneyCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));


        // Display London time in multiple forms.
        SimpleDateFormat dfLondonNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        SimpleDateFormat dfLondonWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        System.out.println("London (" + londonTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + londonOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfLondonNoTZ.format(londonCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfLondonWithTZ.format(londonCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + londonCalendar.getTime() + " / " + londonCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(londonCalendar.getTime())
                + " / " + createDateFormat().format(londonCalendar.getTime()));


        // Display New York time in multiple forms.
        SimpleDateFormat dfNewYorkNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        SimpleDateFormat dfNewYorkWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        System.out.println("New York (" + newYorkTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + newYorkOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfNewYorkNoTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfNewYorkWithTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + newYorkCalendar.getTime() + " / " + newYorkCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(newYorkCalendar.getTime())
                + " / " + createDateFormat().format(newYorkCalendar.getTime()));


        // Display Sydney time in multiple forms.
        SimpleDateFormat dfSydneyNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);
        SimpleDateFormat dfSydneyWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);
        System.out.println("Sydney (" + sydneyTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + sydneyOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfSydneyNoTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfSydneyWithTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + sydneyCalendar.getTime() + " / " + sydneyCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(sydneyCalendar.getTime())
                + " / " + createDateFormat().format(sydneyCalendar.getTime()));
    }

    @Test
    public void testDateParsing() throws Exception {
        // Create date parsers that look for time zone information in a date-time string.
        final SimpleDateFormat londonFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);

        // Create date parsers that ignore time zone information in a date-time string.
        final SimpleDateFormat londonFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);

        // We are looking for the moment this millenium started, the famous Y2K,
        // when at midnight everyone welcomed the New Year 2000, i.e. 2000-01-01 00:00:00.
        // Which of these is the right one?
        // a) "2000-01-01T00:00:00.000-00:00"
        // b) "2000-01-01T00:00:00.000-05:00"
        // c) "2000-01-01T00:00:00.000+10:00"
        // None of them? All of them?
        // For those who guessed it - yes, it is a trick question because we didn't specify
        // the "where" part, or what kind of time (local/global) we are looking for.
        // The first (a) is the local Y2K moment in London, which is at the same time global.
        // The second (b) is the local Y2K moment in New York, but London is already celebrating for 5 hours.
        // The third (c) is the local Y2K moment in Sydney, and they started celebrating 15 hours before New York did.
        // The point here is that each answer is correct because everyone thinks of that moment in terms of "celebration at midnight".
        // The key word here is "midnight"! That moment is actually a "time of day" moment illustrating our perception of time based on the movement of our Sun.

        // These are global Y2K moments, i.e. the same moment all over the world, UTC/GMT midnight.
        final String MIDNIGHT_GLOBAL = "2000-01-01T00:00:00.000-00:00";
        final Date milleniumInLondon = londonFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInNewYork = newYorkFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInSydney = sydneyFormatTZ.parse(MIDNIGHT_GLOBAL);

        // Check if they all point to the same moment in time.
        // And that parser ignores its own configured time zone and uses the information from the date-time string.
        assertThat(milleniumInNewYork, equalTo(milleniumInLondon));
        assertThat(milleniumInSydney, equalTo(milleniumInLondon));


        // These are all local Y2K moments, a.k.a. midnight at each location on Earth, with time zone information.
        final String MIDNIGHT_LONDON = "2000-01-01T00:00:00.000-00:00";
        final String MIDNIGHT_NEW_YORK = "2000-01-01T00:00:00.000-05:00";
        final String MIDNIGHT_SYDNEY = "2000-01-01T00:00:00.000+10:00";
        final Date midnightInLondonTZ = londonFormatLocal.parse(MIDNIGHT_LONDON);
        final Date midnightInNewYorkTZ = newYorkFormatLocal.parse(MIDNIGHT_NEW_YORK);
        final Date midnightInSydneyTZ = sydneyFormatLocal.parse(MIDNIGHT_SYDNEY);

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYorkTZ, not(equalTo(midnightInLondonTZ)));
        assertThat(midnightInSydneyTZ, not(equalTo(midnightInLondonTZ)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondonTZ.getTime() - midnightInNewYorkTZ.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondonTZ.getTime() - midnightInSydneyTZ.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // These are also local Y2K moments, just withouth the time zone information.
        final String MIDNIGHT_ANYWHERE = "2000-01-01T00:00:00.000";
        final Date midnightInLondon = londonFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInNewYork = newYorkFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInSydney = sydneyFormatLocal.parse(MIDNIGHT_ANYWHERE);

        // Check if these are the same as the local moments with time zone information.
        assertThat(midnightInLondon, equalTo(midnightInLondonTZ));
        assertThat(midnightInNewYork, equalTo(midnightInNewYorkTZ));
        assertThat(midnightInSydney, equalTo(midnightInSydneyTZ));

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYork, not(equalTo(midnightInLondon)));
        assertThat(midnightInSydney, not(equalTo(midnightInLondon)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondon.getTime() - midnightInNewYork.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondon.getTime() - midnightInSydney.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // Final check - if Y2K moment is in London ..
        final String Y2K_LONDON = "2000-01-01T00:00:00.000Z";
        // .. New York local time would be still 5 hours in 1999 ..
        final String Y2K_NEW_YORK = "1999-12-31T19:00:00.000-05:00";
        // .. and Sydney local time would be 10 hours in 2000.
        final String Y2K_SYDNEY = "2000-01-01T10:00:00.000+10:00";

        final String londonTime = londonFormatTZ.format(milleniumInLondon);
        final String newYorkTime = newYorkFormatTZ.format(milleniumInLondon);
        final String sydneyTime = sydneyFormatTZ.format(milleniumInLondon);

        // WHat do you think, will the test pass?
        assertThat(londonTime, equalTo(Y2K_LONDON));
        assertThat(newYorkTime, equalTo(Y2K_NEW_YORK));
        assertThat(sydneyTime, equalTo(Y2K_SYDNEY));
    }
}

Searching multiple files for multiple words

If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.

Go to Search > Find in Files (Ctrl+Shift+F for the keyboard addicted) and enter:

  • Find What = (test1|test2)
  • Filters = *.txt
  • Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.
  • Search mode = Regular Expression

How to watch and compile all TypeScript sources?

Today I designed this Ant MacroDef for the same problem as yours :

    <!--
    Recursively read a source directory for TypeScript files, generate a compile list in the
    format needed by the TypeScript compiler adding every parameters it take.
-->
<macrodef name="TypeScriptCompileDir">

    <!-- required attribute -->
    <attribute name="src" />

    <!-- optional attributes -->
    <attribute name="out" default="" />
    <attribute name="module" default="" />
    <attribute name="comments" default="" />
    <attribute name="declarations" default="" />
    <attribute name="nolib" default="" />
    <attribute name="target" default="" />

    <sequential>

        <!-- local properties -->
        <local name="out.arg"/>
        <local name="module.arg"/>
        <local name="comments.arg"/>
        <local name="declarations.arg"/>
        <local name="nolib.arg"/>
        <local name="target.arg"/>
        <local name="typescript.file.list"/>
        <local name="tsc.compile.file"/>

        <property name="tsc.compile.file" value="@{src}compile.list" />

        <!-- Optional arguments are not written to compile file when attributes not set -->
        <condition property="out.arg" value="" else='--out "@{out}"'>
            <equals arg1="@{out}" arg2="" />
        </condition>

        <condition property="module.arg" value="" else="--module @{module}">
            <equals arg1="@{module}" arg2="" />
        </condition>

        <condition property="comments.arg" value="" else="--comments">
            <equals arg1="@{comments}" arg2="" />
        </condition>

        <condition property="declarations.arg" value="" else="--declarations">
            <equals arg1="@{declarations}" arg2="" />
        </condition>

        <condition property="nolib.arg" value="" else="--nolib">
            <equals arg1="@{nolib}" arg2="" />
        </condition>

        <!-- Could have been defaulted to ES3 but let the compiler uses its own default is quite better -->
        <condition property="target.arg" value="" else="--target @{target}">
            <equals arg1="@{target}" arg2="" />
        </condition>

        <!-- Recursively read TypeScript source directory and generate a compile list -->
        <pathconvert property="typescript.file.list" dirsep="\" pathsep="${line.separator}">

            <fileset dir="@{src}">
                <include name="**/*.ts" />
            </fileset>

            <!-- In case regexp doesn't work on your computer, comment <mapper /> and uncomment <regexpmapper /> -->
            <mapper type="regexp" from="^(.*)$" to='"\1"' />
            <!--regexpmapper from="^(.*)$" to='"\1"' /-->

        </pathconvert>


        <!-- Write to the file -->
        <echo message="Writing tsc command line arguments to : ${tsc.compile.file}" />
        <echo file="${tsc.compile.file}" message="${typescript.file.list}${line.separator}${out.arg}${line.separator}${module.arg}${line.separator}${comments.arg}${line.separator}${declarations.arg}${line.separator}${nolib.arg}${line.separator}${target.arg}" append="false" />

        <!-- Compile using the generated compile file -->
        <echo message="Calling ${typescript.compiler.path} with ${tsc.compile.file}" />
        <exec dir="@{src}" executable="${typescript.compiler.path}">
            <arg value="@${tsc.compile.file}"/>
        </exec>

        <!-- Finally delete the compile file -->
        <echo message="${tsc.compile.file} deleted" />
        <delete file="${tsc.compile.file}" />

    </sequential>

</macrodef>

Use it in your build file with :

    <!-- Compile a single JavaScript file in the bin dir for release -->
    <TypeScriptCompileDir
        src="${src-js.dir}"
        out="${release-file-path}"
        module="amd"
    />

It is used in the project PureMVC for TypeScript I'm working on at the time using Webstorm.

jQuery access input hidden value

To get value, use:

$.each($('input'),function(i,val){
    if($(this).attr("type")=="hidden"){
        var valueOfHidFiled=$(this).val();
        alert(valueOfHidFiled);
    }
});

or:

var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);

To set value, use:

$('input[type=hidden]').attr('value',newValue);

Getting RSA private key from PEM BASE64 Encoded private key file

This is PKCS#1 format of a private key. Try this code. It doesn't use Bouncy Castle or other third-party crypto providers. Just java.security and sun.security for DER sequece parsing. Also it supports parsing of a private key in PKCS#8 format (PEM file that has a header "-----BEGIN PRIVATE KEY-----").

import sun.security.util.DerInputStream;
import sun.security.util.DerValue;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;

public static PrivateKey pemFileLoadPrivateKeyPkcs1OrPkcs8Encoded(File pemFileName) throws GeneralSecurityException, IOException {
        // PKCS#8 format
        final String PEM_PRIVATE_START = "-----BEGIN PRIVATE KEY-----";
        final String PEM_PRIVATE_END = "-----END PRIVATE KEY-----";

        // PKCS#1 format
        final String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----";
        final String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----";

        Path path = Paths.get(pemFileName.getAbsolutePath());

        String privateKeyPem = new String(Files.readAllBytes(path));

        if (privateKeyPem.indexOf(PEM_PRIVATE_START) != -1) { // PKCS#8 format
            privateKeyPem = privateKeyPem.replace(PEM_PRIVATE_START, "").replace(PEM_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            byte[] pkcs8EncodedKey = Base64.getDecoder().decode(privateKeyPem);

            KeyFactory factory = KeyFactory.getInstance("RSA");
            return factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));

        } else if (privateKeyPem.indexOf(PEM_RSA_PRIVATE_START) != -1) {  // PKCS#1 format

            privateKeyPem = privateKeyPem.replace(PEM_RSA_PRIVATE_START, "").replace(PEM_RSA_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(privateKeyPem));

            DerValue[] seq = derReader.getSequence(0);

            if (seq.length < 9) {
                throw new GeneralSecurityException("Could not parse a PKCS1 private key.");
            }

            // skip version seq[0];
            BigInteger modulus = seq[1].getBigInteger();
            BigInteger publicExp = seq[2].getBigInteger();
            BigInteger privateExp = seq[3].getBigInteger();
            BigInteger prime1 = seq[4].getBigInteger();
            BigInteger prime2 = seq[5].getBigInteger();
            BigInteger exp1 = seq[6].getBigInteger();
            BigInteger exp2 = seq[7].getBigInteger();
            BigInteger crtCoef = seq[8].getBigInteger();

            RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);

            KeyFactory factory = KeyFactory.getInstance("RSA");

            return factory.generatePrivate(keySpec);
        }

        throw new GeneralSecurityException("Not supported format of a private key");
    }