Programs & Examples On #Pycrypto

PyCrypto - The Python Cryptography Toolkit is a package that contains various cryptographic modules for the Python programming language.

Pip error: Microsoft Visual C++ 14.0 is required

As an alternative to installing Visual C++, there is a way by installing an additional package in Conda (this option doesn't require admin rights). This worked for me:

conda install libpython m2w64-toolchain -c msys2

How do I install PyCrypto on Windows?

After years and years, python finally agreed for a binary disribution called wheel which allows to install even binary extensions on Windows without having a compiler with simple pip install packagename. There is a list of popular packages with their status. Pycrypto is not there yet, but lxml, PySide and Scrapy for example.

Edited Nov 2015: pip uninstall pycrypto & pip install pycryptodome. It is a pycrypto fork with new features and it supports wheel. It replaces pycrypto, so existing code will continue to work (see https://pycryptodome.readthedocs.org/en/latest/src/examples.html)

ImportError: No module named Crypto.Cipher

I found the solution. Issue is probably in case sensitivity (on Windows).

Just change the name of the folder:

  • C:\Python27\Lib\site-packages\crypto
  • to: C:\Python27\Lib\site-packages\Crypto

This is how folder was named after installation of pycrypto: enter image description here

I've changed it to: enter image description here

And now the following code works fine: enter image description here

RSA encryption and decryption in Python

Here is my implementation for python 3 and pycrypto

from Crypto.PublicKey import RSA
key = RSA.generate(4096)
f = open('/home/john/Desktop/my_rsa_public.pem', 'wb')
f.write(key.publickey().exportKey('PEM'))
f.close()
f = open('/home/john/Desktop/my_rsa_private.pem', 'wb')
f.write(key.exportKey('PEM'))
f.close()

f = open('/home/john/Desktop/my_rsa_public.pem', 'rb')
f1 = open('/home/john/Desktop/my_rsa_private.pem', 'rb')
key = RSA.importKey(f.read())
key1 = RSA.importKey(f1.read())

x = key.encrypt(b"dddddd",32)

print(x)
z = key1.decrypt(x)
print(z)

Encrypt & Decrypt using PyCrypto AES 256

I have used both Crypto and PyCryptodomex library and it is blazing fast...

import base64
import hashlib
from Cryptodome.Cipher import AES as domeAES
from Cryptodome.Random import get_random_bytes
from Crypto import Random
from Crypto.Cipher import AES as cryptoAES

BLOCK_SIZE = AES.block_size

key = "my_secret_key".encode()
__key__ = hashlib.sha256(key).digest()
print(__key__)

def encrypt(raw):
    BS = cryptoAES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
    raw = base64.b64encode(pad(raw).encode('utf8'))
    iv = get_random_bytes(cryptoAES.block_size)
    cipher = cryptoAES.new(key= __key__, mode= cryptoAES.MODE_CFB,iv= iv)
    a= base64.b64encode(iv + cipher.encrypt(raw))
    IV = Random.new().read(BLOCK_SIZE)
    aes = domeAES.new(__key__, domeAES.MODE_CFB, IV)
    b = base64.b64encode(IV + aes.encrypt(a))
    return b

def decrypt(enc):
    passphrase = __key__
    encrypted = base64.b64decode(enc)
    IV = encrypted[:BLOCK_SIZE]
    aes = domeAES.new(passphrase, domeAES.MODE_CFB, IV)
    enc = aes.decrypt(encrypted[BLOCK_SIZE:])
    unpad = lambda s: s[:-ord(s[-1:])]
    enc = base64.b64decode(enc)
    iv = enc[:cryptoAES.block_size]
    cipher = cryptoAES.new(__key__, cryptoAES.MODE_CFB, iv)
    b=  unpad(base64.b64decode(cipher.decrypt(enc[cryptoAES.block_size:])).decode('utf8'))
    return b

encrypted_data =encrypt("Hi Steven!!!!!")
print(encrypted_data)
print("=======")
decrypted_data = decrypt(encrypted_data)
print(decrypted_data)

Making a request to a RESTful API using python

Using requests:

import requests
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
data = '''{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'''
response = requests.post(url, data=data)

Depending on what kind of response your API returns, you will then probably want to look at response.text or response.json() (or possibly inspect response.status_code first). See the quickstart docs here, especially this section.

Compare given date with today

Few years later, I second Bobby Jack's observation that last 24 hrs is not today!!! And I am surprised that the answer was so much upvoted...

To compare if a certain date is less, equal or greater than another, first you need to turn them "down" to beginning of the day. In other words, make sure that you're talking about same 00:00:00 time in both dates. This can be simply and elegantly done as:

strtotime("today") <=> strtotime($var)

if $var has the time part on 00:00:00 like the OP specified.

Replace <=> with whatever you need (or keep it like this in php 7)

Also, obviously, we're talking about same timezone for both. For list of supported TimeZones

gradle build fails on lint task

With 0.7.0 there comes extended support for Lint, however, it does not work always properly. (Eg. the butterknife library)

Solution is to disable aborting build on found lint errors

I took the inspiration from https://android.googlesource.com/platform/tools/base/+/e6a5b9c7c1bca4da402de442315b5ff1ada819c7

(implementation: https://android.googlesource.com/platform/tools/base/+/e6a5b9c7c1bca4da402de442315b5ff1ada819c7/build-system/gradle/src/main/groovy/com/android/build/gradle/internal/model/DefaultAndroidProject.java )

(discussion: https://plus.google.com/+AndroidDevelopers/posts/ersS6fMLxw1 )

android {
  // your build config
  defaultConfig { ... }
  signingConfigs { ... }
  compileOptions { ... }
  buildTypes { ... }
  // This is important, it will run lint checks but won't abort build
  lintOptions {
      abortOnError false
  }
}

And if you need to disable just particular Lint rule and keep the build failing on others, use this:

/*
 * Use only 'disable' or only 'enable', those configurations exclude each other
 */
android {
  lintOptions {
    // use this line to check all rules except those listed
    disable 'RuleToDisable', 'SecondRuleToDisable'
    // use this line to check just listed rules
    enable 'FirstRuleToCheck', 'LastRuleToCheck'
  }
}

How to Extract Year from DATE in POSTGRESQL

This line solved my same problem in postgresql:

SELECT DATE_PART('year', column_name::date) from tableName;

If you want month, then simply replacing year with month solves that as well and likewise.

React Native android build failed. SDK location not found

Copy your system's other android project local.properties and paste in android folder of React-native project it will work.

sdk.dir=C\:\\Users\\paul\\AppData\\Local\\Android\\Sdk

AngularJS : When to use service instead of factory

Factory and Service are the most commonly used method. The only difference between them is that the Service method works better for objects that need inheritance hierarchy, while the Factory can produce JavaScript primitives and functions.

The Provider function is the core method and all the other ones are just syntactic sugar on it. You need it only if you are building a reusable piece of code that needs global configuration.

There are five methods to create services: Value, Factory, Service, Provider and Constant. You can learn more about this here angular service, this article explain all this methods with practical demo examples.

.

php: check if an array has duplicates

Keep it simple, silly! ;)

Simple OR logic...

function checkDuplicatesInArray($array){
    $duplicates=FALSE;
    foreach($array as $k=>$i){
        if(!isset($value_{$i})){
            $value_{$i}=TRUE;
        }
        else{
            $duplicates|=TRUE;          
        }
    }
    return ($duplicates);
}

Regards!

How to Sort Date in descending order From Arraylist Date in android?

Create Arraylist<Date> of Date class. And use Collections.sort() for ascending order.

See sort(List<T> list)

Sorts the specified list into ascending order, according to the natural ordering of its elements.

For Sort it in descending order See Collections.reverseOrder()

Collections.sort(yourList, Collections.reverseOrder());

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

html button to send email

This method doesn't seem to work in my browser, and looking around indicates that the whole subject of specifying headers to a mailto link/action is sparsely supported, but maybe this can help...

HTML:

<form id="fr1">
    <input type="text" id="tb1" />
    <input type="text" id="tb2" />
    <input type="button" id="bt1" value="click" />
</form>

JavaScript (with jQuery):

$(document).ready(function() {
    $('#bt1').click(function() {
        $('#fr1').attr('action',
                       'mailto:[email protected]?subject=' +
                       $('#tb1').val() + '&body=' + $('#tb2').val());
        $('#fr1').submit();
    });
});

Notice what I'm doing here. The form itself has no action associated with it. And the submit button isn't really a submit type, it's just a button type. Using JavaScript, I'm binding to that button's click event, setting the form's action attribute, and then submitting the form.

It's working in so much as it submits the form to a mailto action (my default mail program pops up and opens a new message to the specified address), but for me (Safari, Mail.app) it's not actually specifying the Subject or Body in the resulting message.

HTML isn't really a very good medium for doing this, as I'm sure others are pointing out while I type this. It's possible that this may work in some browsers and/or some mail clients. However, it's really not even a safe assumption anymore that users will have a fat mail client these days. I can't remember the last time I opened mine. HTML's mailto is a bit of legacy functionality and, these days, it's really just as well that you perform the mail action on the server-side if possible.

Set content of HTML <span> with Javascript

The Maximally Standards Compliant way to do it is to create a text node containing the text you want and append it to the span (removing any currently extant text nodes).

The way I would actually do it is to use jQuery's .text().

UPDATE and REPLACE part of a string

UPDATE table_name
SET field_name = '0'
WHERE field_name IS Null

Force "portrait" orientation mode

I think you want to add android:configChanges="orientation|keyboardHidden" to your activity? Otherwise the activity is restarted on config-change. The onConfigurationChanged would not be called then, only the onCreate

Add new row to excel Table (VBA)

I actually just found that if you want to add multiple rows below the selection in your table Selection.ListObject.ListRows.Add AlwaysInsert:=True works really well. I just duplicated the code five times to add five rows to my table

How to find the most recent file in a directory using .NET, and without looping?

Expanding on the first one above, if you want to search for a certain pattern you may use the following code:

string pattern = "*.txt";
var dirInfo = new DirectoryInfo(directory);
var file = (from f in dirInfo.GetFiles(pattern) orderby f.LastWriteTime descending select f).First();

Very Simple, Very Smooth, JavaScript Marquee

hiya simple demo from recommendations in above comments: http://jsfiddle.net/FWWEn/

with pause functionality on mouseover: http://jsfiddle.net/zrW5q/

hope this helps, have a nice one, cheers!

html

<h1>Hello World!</h1>
<h2>I'll marquee twice</h2>
<h3>I go fast!</h3>
<h4>Left to right</h4>
<h5>I'll defer that question</h5>?

Jquery code

 (function($) {
        $.fn.textWidth = function(){
             var calc = '<span style="display:none">' + $(this).text() + '</span>';
             $('body').append(calc);
             var width = $('body').find('span:last').width();
             $('body').find('span:last').remove();
            return width;
        };

        $.fn.marquee = function(args) {
            var that = $(this);
            var textWidth = that.textWidth(),
                offset = that.width(),
                width = offset,
                css = {
                    'text-indent' : that.css('text-indent'),
                    'overflow' : that.css('overflow'),
                    'white-space' : that.css('white-space')
                },
                marqueeCss = {
                    'text-indent' : width,
                    'overflow' : 'hidden',
                    'white-space' : 'nowrap'
                },
                args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false }, args),
                i = 0,
                stop = textWidth*-1,
                dfd = $.Deferred();

            function go() {
                if(!that.length) return dfd.reject();
                if(width == stop) {
                    i++;
                    if(i == args.count) {
                        that.css(css);
                        return dfd.resolve();
                    }
                    if(args.leftToRight) {
                        width = textWidth*-1;
                    } else {
                        width = offset;
                    }
                }
                that.css('text-indent', width + 'px');
                if(args.leftToRight) {
                    width++;
                } else {
                    width--;
                }
                setTimeout(go, args.speed);
            };
            if(args.leftToRight) {
                width = textWidth*-1;
                width++;
                stop = offset;
            } else {
                width--;            
            }
            that.css(marqueeCss);
            go();
            return dfd.promise();
        };
    })(jQuery);

$('h1').marquee();
$('h2').marquee({ count: 2 });
$('h3').marquee({ speed: 5 });
$('h4').marquee({ leftToRight: true });
$('h5').marquee({ count: 1, speed: 2 }).done(function() { $('h5').css('color', '#f00'); })?

Adding Python Path on Windows 7

Try adding this python.bat file to System32 folder and the command line will now run python when you type in python

python.bat

@C:\Python27\python.exe %*

Source:

https://github.com/KartikTalwar/dotfiles/blob/master/bat/python.bat

UTF-8, UTF-16, and UTF-32

I tried to give a simple explanation in my blogpost.

UTF-32

requires 32 bits (4 bytes) to encode any character. For example, in order to represent the "A" character code-point using this scheme, you'll need to write 65 in 32-bit binary number:

00000000 00000000 00000000 01000001 (Big Endian)

If you take a closer look, you'll note that the most-right seven bits are actually the same bits when using the ASCII scheme. But since UTF-32 is fixed width scheme, we must attach three additional bytes. Meaning that if we have two files that only contain the "A" character, one is ASCII-encoded and the other is UTF-32 encoded, their size will be 1 byte and 4 bytes correspondingly.

UTF-16

Many people think that as UTF-32 uses fixed width 32 bit to represent a code-point, UTF-16 is fixed width 16 bits. WRONG!

In UTF-16 the code point maybe represented either in 16 bits, OR 32 bits. So this scheme is variable length encoding system. What is the advantage over the UTF-32? At least for ASCII, the size of files won't be 4 times the original (but still twice), so we're still not ASCII backward compatible.

Since 7-bits are enough to represent the "A" character, we can now use 2 bytes instead of 4 like the UTF-32. It'll look like:

00000000 01000001

UTF-8

You guessed right.. In UTF-8 the code point maybe represented using either 32, 16, 24 or 8 bits, and as the UTF-16 system, this one is also variable length encoding system.

Finally we can represent "A" in the same way we represent it using ASCII encoding system:

01001101

A small example where UTF-16 is actually better than UTF-8:

Consider the Chinese letter "?" - its UTF-8 encoding is:

11101000 10101010 10011110

While its UTF-16 encoding is shorter:

10001010 10011110

In order to understand the representation and how it's interpreted, visit the original post.

Can a relative sitemap url be used in a robots.txt?

Good technical & logical question my dear friend. No in robots.txt file you can't go with relative URL of the sitemap; you need to go with the complete URL of the sitemap.

It's better to go with "sitemap: https://www.example.com/sitemap_index.xml"

In the above URL after the colon gives space. I also like to support Deepak.

Filter Extensions in HTML form upload

The accept attribute specifies a comma-separated list of content types (MIME types) that the target of the form will process correctly. Unfortunately this attribute is ignored by all the major browsers, so it does not affect the browser's file dialog in any way.

Insert a line break in mailto body

As per RFC2368 which defines mailto:, further reinforced by an example in RFC1738, it is explicitly stated that the only valid way to generate a line break is with %0D%0A.

This also applies to all url schemes such as gopher, smtp, sdp, imap, ldap, etc..

Import a custom class in Java

If all of your classes are in the same package, you shouldn't need to import them.

Simply instantiate the object like so:

CustomObject myObject = new CustomObject();

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

If you're using react-native then please try the below commands first before running your project:

  1. npm install --save-dev jetifier
  2. npx jetify

Now run your project again. Hope this will work.

add maven repository to build.gradle

You have to add repositories to your build file. For maven repositories you have to prefix repository name with maven{}

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "http://maven.restlet.org" }
  mavenCentral()
}

How to get http headers in flask?

Let's see how we get the params, headers and body in Flask. I'm gonna explain with the help of postman.

enter image description here

The params keys and values are reflected in the API endpoint. for example key1 and key2 in the endpoint : https://127.0.0.1/upload?key1=value1&key2=value2

from flask import Flask, request
app = Flask(__name__)

@app.route('/upload')
def upload():

  key_1 = request.args.get('key1')
  key_2 = request.args.get('key2')
  print(key_1)
  #--> value1
  print(key_2)
  #--> value2

After params, let's now see how to get the headers:

enter image description here

  header_1 = request.headers.get('header1')
  header_2 = request.headers.get('header2')
  print(header_1)
  #--> header_value1
  print(header_2)
  #--> header_value2

Now let's see how to get the body

enter image description here

  file_name = request.files['file'].filename
  ref_id = request.form['referenceId']
  print(ref_id)
  #--> WWB9838yb3r47484

so we fetch the uploaded files with request.files and text with request.form

Android change SDK version in Eclipse? Unable to resolve target android-x

If you're using eclipse you can open default.properties file in your workspace and change the project target to the new sdk (target=android-8 for 2.2). I accidentally selected the 1.5 sdk for my version and didn't catch it until much later, but updating that and restarting eclipse seemed to have done the trick.

Postgres user does not exist?

The solution is simple:
log in as root
and after:

su - postgres

psql

Export to csv in jQuery

By using just jQuery, you cannot avoid a server call.

However, to achieve this result, I'm using Downloadify, which lets me save files without having to make another server call. Doing this reduces server load and makes a good user experience.

To get a proper CSV you just have to take out all the unnecessary tags and put a ',' between the data.

How to declare a global variable in a .js file

As mentioned above, there are issues with using the top-most scope in your script file. Here is another issue: The script file might be run from a context that is not the global context in some run-time environment.

It has been proposed to assign the global to window directly. But that is also run-time dependent and does not work in Node etc. It goes to show that portable global variable management needs some careful consideration and extra effort. Maybe they will fix it in future ECMS versions!

For now, I would recommend something like this to support proper global management for all run-time environments:

/**
 * Exports the given object into the global context.
 */
var exportGlobal = function(name, object) {
    if (typeof(global) !== "undefined")  {
        // Node.js
        global[name] = object;
    }
    else if (typeof(window) !== "undefined") {
        // JS with GUI (usually browser)
        window[name] = object;
    }
    else {
        throw new Error("Unkown run-time environment. Currently only browsers and Node.js are supported.");
    }
};


// export exportGlobal itself
exportGlobal("exportGlobal", exportGlobal);

// create a new global namespace
exportGlobal("someothernamespace", {});

It's a bit more typing, but it makes your global variable management future-proof.

Disclaimer: Part of this idea came to me when looking at previous versions of stacktrace.js.

I reckon, one can also use Webpack or other tools to get more reliable and less hackish detection of the run-time environment.

SELECT using 'CASE' in SQL

Try this.

SELECT 
  CASE 
     WHEN FRUIT = 'A' THEN 'APPLE'
     WHEN FRUIT = 'B' THEN 'BANANA'
     ELSE 'UNKNOWN FRUIT'
  END AS FRUIT
FROM FRUIT_TABLE;

TypeError: $(...).on is not a function

If you are using old version of jQuery(< 1.7) then you can use "bind" instead of "on". This will only work in case you are using old version, since as of jQuery 3.0, "bind" has been deprecated.

php random x digit number

you can generate any x-digit random number with mt_rand() function. mt_rand() much faster with rand() function syntax : mt_rand() or mt_rand($min , $max).

read more

example : <?php echo mt_rand(); ?>

How to remove a TFS Workspace Mapping?

I ran into the same problem, and was able to fix it by manually deleting all the files in the TFS cache, located here:

%LocalAppData%\Microsoft\Team Foundation\3.0\Cache

or 4.0, 5.0, etc.

How to convert a Bitmap to Drawable in android?

And you can try this:

public static Bitmap mirrorBitmap(Bitmap bInput)
    {
        Bitmap  bOutput;
        Matrix matrix = new Matrix();
        matrix.preScale(-1.0f, 1.0f);
        bOutput = Bitmap.createBitmap(bInput, 0, 0, bInput.getWidth(), bInput.getHeight(), matrix, true);
        return bOutput;
    }

Python Anaconda - How to Safely Uninstall

I simply:

rm -rf ~/anaconda3

...this removed conda also.

Then:

mousepad ~/.bashrc

...and removed the path line added at the very bottom (clearly identified by Anaconda as 'added by Anaconda'.

Worth noting that anaconda3 created a backup of my .bashrc file before modification, and named it as:

./bashrc-anaconda3.bak

...so I could always have just renamed this and deleted my modified .bashrc

What does "javax.naming.NoInitialContextException" mean?

Just read the docs:

This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.

This exception can be thrown during any interaction with the InitialContext, not only when the InitialContext is constructed. For example, the implementation of the initial context might lazily retrieve the context only when actual methods are invoked on it. The application should not have any dependency on when the existence of an initial context is determined.

But this is explained much better in the docs for InitialContext

how to make a new line in a jupyter markdown cell

Just add <br> where you would like to make the new line.

$S$: a set of shops
<br>
$I$: a set of items M wants to get

Because jupyter notebook markdown cell is a superset of HTML.
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html

Note that newlines using <br> does not persist when exporting or saving the notebook to a pdf (using "Download as > PDF via LaTeX"). It is probably treating each <br> as a space.

How can I remove time from date with Moment.js?

The correct way would be to specify the input as per your requirement which will give you more flexibility.

The present definition includes the following

LTS : 'h:mm:ss A', LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY h:mm A', LLLL : 'dddd, MMMM D, YYYY h:mm A'

You can use any of these or change the input passed into moment().format(). For example, for your case you can pass moment.utc(dateTime).format('MMMM D, YYYY').

Percentage Height HTML 5/CSS

bobince's answer will let you know in which cases "height: XX%;" will or won't work.

If you want to create an element with a set ratio (height: % of it's own width), the best way to do that is by effectively setting the height using padding-bottom. Example for square:

<div class="square-container">
  <div class="square-content">
    <!-- put your content in here -->
  </div>
</div>

.square-container {  /* any display: block; element */
  position: relative;
  height: 0;
  padding-bottom: 100%; /* of parent width */
}
.square-content {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
}

The square container will just be made of padding, and the content will expand to fill the container. Long article from 2009 on this subject: http://alistapart.com/article/creating-intrinsic-ratios-for-video

jquery drop down menu closing by clicking outside

Selected answer works for one drop down menu only. For multiple solution would be:

$('body').click(function(event){
   $dropdowns.not($dropdowns.has(event.target)).hide();
});

Auto-indent spaces with C in vim?

and always remember this venerable explanation of Spaces + Tabs:

http://www.jwz.org/doc/tabs-vs-spaces.html

Calling method using JavaScript prototype

If you know your super class by name, you can do something like this:

function Base() {
}

Base.prototype.foo = function() {
  console.log('called foo in Base');
}

function Sub() {
}

Sub.prototype = new Base();

Sub.prototype.foo = function() {
  console.log('called foo in Sub');
  Base.prototype.foo.call(this);
}

var base = new Base();
base.foo();

var sub = new Sub();
sub.foo();

This will print

called foo in Base
called foo in Sub
called foo in Base

as expected.

How to check for Is not Null And Is not Empty string in SQL server?

If you only want to match "" as an empty string

WHERE DATALENGTH(COLUMN) > 0 

If you want to count any string consisting entirely of spaces as empty

WHERE COLUMN <> '' 

Both of these will not return NULL values when used in a WHERE clause. As NULL will evaluate as UNKNOWN for these rather than TRUE.

CREATE TABLE T 
  ( 
     C VARCHAR(10) 
  ); 

INSERT INTO T 
VALUES      ('A'), 
            (''),
            ('    '), 
            (NULL); 

SELECT * 
FROM   T 
WHERE  C <> ''

Returns just the single row A. I.e. The rows with NULL or an empty string or a string consisting entirely of spaces are all excluded by this query.

SQL Fiddle

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

On Ubuntu 18.04 with MariaDb and Nginx, I solved it with updating file /usr/share/phpmyadmin/libraries/sql.lib.php as follows:

|| (count($analyzed_sql_results['select_expr']) == 1

The answer mentioned by @Nguyen throws a 500 error saying:

FastCGI sent in stderr: "PHP message: PHP Parse error:  syntax error, unexpected ')', expecting ';' in /usr/share/phpmyadmin/libraries/sql.lib.php on line 614"

mysql update multiple columns with same now()

If you really need to be sure that now() has the same value you can run two queries (that will answer to your second question too, in that case you are asking to update last_monitor = to last_update but last_update hasn't been updated yet)

you could do something like:

mysql> update table set last_update=now() where id=1;
mysql> update table set last_monitor = last_update where id=1;

anyway I think that mysql is clever enough to ask for now() only once per query.

Javascript: Setting location.href versus location

Even if both work, I would use the latter. location is an object, and assigning a string to an object doesn't bode well for readability or maintenance.

MySQL - Select the last inserted row easiest way

SELECT MAX(ID) from bugs WHERE user=Me

java.io.IOException: Invalid Keystore format

go to build clean the project then rebuild your project it worked for me.

How to capture the android device screen content?

if you want to do screen capture from Java code in Android app AFAIK you must have Root provileges.

Kotlin: How to get and set a text to TextView in Android using Kotlin?

Yes its late - but may help someone on reference

xml with EditText, Button and TextView

onClick on Button will update the value from EditText to TextView

        <EditText
            android:id="@+id/et_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <Button
            android:id="@+id/btn_submit_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/txt_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

Look at the code do the action in your class

Don't need to initialize the id's of components like in Java. You can do it by their xml Id's

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sample)

        btn_submit_id.setOnClickListener {
            txt_id.setText(et_id.text);
        }
    }

also you can set value in TextView like,

textview.text = "your value"

Mocking methods of local scope objects with Mockito

You could avoid changing the code (although I recommend Boris' answer) and mock the constructor, like in this example for mocking the creation of a File object inside a method. Don't forget to put the class that will create the file in the @PrepareForTest.

package hello.easymock.constructor;

import java.io.File;

import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
    
@RunWith(PowerMockRunner.class)
@PrepareForTest({File.class})
public class ConstructorExampleTest {
        
    @Test
    public void testMockFile() throws Exception {

        // first, create a mock for File
        final File fileMock = EasyMock.createMock(File.class);
        EasyMock.expect(fileMock.getAbsolutePath()).andReturn("/my/fake/file/path");
        EasyMock.replay(fileMock);

        // then return the mocked object if the constructor is invoked
        Class<?>[] parameterTypes = new Class[] { String.class };
        PowerMock.expectNew(File.class, parameterTypes , EasyMock.isA(String.class)).andReturn(fileMock);
        PowerMock.replay(File.class); 
    
        // try constructing a real File and check if the mock kicked in
        final String mockedFilePath = new File("/real/path/for/file").getAbsolutePath();
        Assert.assertEquals("/my/fake/file/path", mockedFilePath);
    }
}

Is it necessary to assign a string to a variable before comparing it to another?

Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:

NSString *myString = [[NSString alloc] initWithFormat:@"SomeText"];

Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.

Next time you want a string variable you can use the "@" symbol in a much more convenient way:

NSString *myString = @"SomeText";

This will be autoreleased when you've finished with it so you'll avoid memory leaks too...

Hope that helps!

Checking network connection

Just to update what unutbu said for new code in Python 3.2

def check_connectivity(reference):
    try:
        urllib.request.urlopen(reference, timeout=1)
        return True
    except urllib.request.URLError:
        return False

And, just to note, the input here (reference) is the url that you want to check: I suggest choosing something that connects fast where you live -- i.e. I live in South Korea, so I would probably set reference to http://www.naver.com.

Trigger validation of all fields in Angular Form submit

In case someone comes back to this later... None of the above worked for me. So I dug down into the guts of angular form validation and found the function they call to execute validators on a given field. This property is conveniently called $validate.

If you have a named form myForm, you can programmatically call myForm.my_field.$validate() to execute field validation. For example:

<div ng-form name="myForm">
    <input required name="my_field" type="text" ng-blur="myForm.my_field.$validate()">
</div>

Note that calling $validate has implications for your model. From the angular docs for ngModelCtrl.$validate:

Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid $modelValue, i.e. either the last parsed value or the last value set from the scope.

So if you're planning on doing something with the invalid model value (like popping a message telling them so), then you need to make sure allowInvalid is set to true for your model.

How to restore the permissions of files and directories within git if they have been modified?

Thanks @muhqu for his great answer. In my case not all changes files had permissions changed which prevented the command to work.

$ git diff -p -R --no-ext-diff --no-color | grep -E "^(diff|(old|new) mode)" --color=never
diff --git b/file1 a/file1
diff --git b/file2 a/file2
old mode 100755
new mode 100644
$ git diff -p -R --no-ext-diff --no-color | grep -E "^(diff|(old|new) mode)" --color=never | git apply
warning: file1 has type 100644, expected 100755

The patch would then stop and files would be left untouched.

In case some people have similar problem I solved this by tweaking the command to grep only files with permission changed:

grep -E "^old mode (100644|100755)" -B1 -A1

or for the git alias

git config --global --add alias.permission-reset '!git diff -p -R --no-ext-diff --no-color | grep -E "^old mode (100644|100755)" -B1 -A1 --color=never | git apply'

Spring Data and Native Query with pagination

My apologies in advance, this is pretty much summing up the original question and the comment from Janar, however...

I run into the same problem: I found the Example 50 of Spring Data as the solution for my need of having a native query with pagination but Spring was complaining on startup that I could not use pagination with native queries.

I just wanted to report that I managed to run successfully the native query I needed, using pagination, with the following code:

    @Query(value="SELECT a.* "
            + "FROM author a left outer join mappable_natural_person p on a.id = p.provenance_id "
            + "WHERE p.update_time is null OR (p.provenance_name='biblio_db' and a.update_time>p.update_time)"
            + "ORDER BY a.id \n#pageable\n", 
        /*countQuery="SELECT count(a.*) "
            + "FROM author a left outer join mappable_natural_person p on a.id = p.provenance_id "
            + "WHERE p.update_time is null OR (p.provenance_name='biblio_db' and a.update_time>p.update_time) \n#pageable\n",*/
        nativeQuery=true)
public List<Author> findAuthorsUpdatedAndNew(Pageable pageable);

The countQuery (that is commented out in the code block) is needed to use Page<Author> as the return type of the query, the newlines around the "#pageable" comment are needed to avoid the runtime error on the number of expected parameters (workaround of the workaround). I hope this bug will be fixed soon...

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

Best way to incorporate Volley (or other library) into Android Studio project

UPDATE:

compile 'com.android.volley:volley:1.0.0'

OLD ANSWER: You need the next in your build.gradle of your app module:

dependencies {
        compile 'com.mcxiaoke.volley:library:1.0.19'
        (Rest of your dependencies)

    }

This is not the official repo but is a highly trusted one.

Laravel: Get Object From Collection By Attribute

Use the built in collection methods contain and find, which will search by primary ids (instead of array keys). Example:

if ($model->collection->contains($primaryId)) {
    var_dump($model->collection->find($primaryId);
}

contains() actually just calls find() and checks for null, so you could shorten it down to:

if ($myModel = $model->collection->find($primaryId)) {
    var_dump($myModel);
}

What's the meaning of System.out.println in Java?

From the javadoc about System, here's what the doc says:

public final class System
extends Object

The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

Since:
JDK1.0

Regarding System.out

public static final PrintStream out

The "standard" output stream class Prinstream  belongs to java.io package. This stream is already open and ready to accept output data. 
When the JVM is initialized, the method initializeSystemClass() is called that does exactly what it’s name says – it initializes the System class and sets the out variable. The initializeSystemClass() method actually calls another method to set the out variable – this method is called setOut().
Typically this stream corresponds to display output or another output destination specified by the host environment or user.

Regarding println();

class PrintStream{
public void println();
}

For simple stand-alone Java applications, a typical way to write a line of output data is:

System.out.println(data);

How do I break out of a loop in Scala?

I don't know how much Scala style has changed in the past 9 years, but I found it interesting that most of the existing answers use vars, or hard to read recursion. The key to exiting early is to use a lazy collection to generate your possible candidates, then check for the condition separately. To generate the products:

val products = for {
  i <- (999 to 1 by -1).view
  j <- (i to 1 by -1).view
} yield (i*j)

Then to find the first palindrome from that view without generating every combination:

val palindromes = products filter {p => p.toString == p.toString.reverse}
palindromes.head

To find the largest palindrome (although the laziness doesn't buy you much because you have to check the entire list anyway):

palindromes.max

Your original code is actually checking for the first palindrome that is larger than a subsequent product, which is the same as checking for the first palindrome except in a weird boundary condition which I don't think you intended. The products are not strictly monotonically decreasing. For example, 998*998 is greater than 999*997, but appears much later in the loops.

Anyway, the advantage of the separated lazy generation and condition check is you write it pretty much like it is using the entire list, but it only generates as much as you need. You sort of get the best of both worlds.

How to get std::vector pointer to the raw data?

something.data() will return a pointer to the data space of the vector.

What is the meaning of <> in mysql query?

In MySQL, <> means Not Equal To, just like !=.

mysql> SELECT '.01' <> '0.01';
        -> 1
mysql> SELECT .01 <> '0.01';
        -> 0
mysql> SELECT 'zapp' <> 'zappp';
        -> 1

see the docs for more info

How do I delete all the duplicate records in a MySQL table without temp tables

Instead of drop table TableA, you could delete all registers (delete from TableA;) and then populate original table with registers coming from TableA_Verify (insert into TAbleA select * from TAbleA_Verify). In this way you won't lost all references to original table (indexes,... )

CREATE TABLE TableA_Verify AS SELECT DISTINCT * FROM TableA;

DELETE FROM TableA;

INSERT INTO TableA SELECT * FROM TAbleA_Verify;

DROP TABLE TableA_Verify;

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

I had the same error in nodejs. But adding signatureVersion in s3 constructor helped me:

const s3 = new AWS.S3({
  apiVersion: '2006-03-01',
  signatureVersion: 'v4',
});

how to run the command mvn eclipse:eclipse

Besides the powerful options on the "Run Configurations.." on a well configured project you'll see the maven tasks on the Run As as well.

enter image description here

Easy way to pull latest of all git submodules

Note: This is from 2009 and may have been good then but there are better options now.

We use this. It's called git-pup:

#!/bin/bash
# Exists to fully update the git repo that you are sitting in...

git pull && git submodule init && git submodule update && git submodule status

Just put it in a suitable bin directory (/usr/local/bin). If on Windows, you may need to modify the syntax to get it to work :)

Update:

In response to the comment by the original author about pulling in all of the HEADs of all of the submodules -- that is a good question.

I am pretty sure that git does not have a command for this internally. In order to do so, you would need to identify what HEAD really is for a submodule. That could be as simple as saying master is the most up to date branch, etc...

Following this, create a simple script that does the following:

  1. check git submodule status for "modified" repositories. The first character of the output lines indicates this. If a sub-repo is modified, you may NOT want to proceed.
  2. for each repo listed, cd into it's directory and run git checkout master && git pull. Check for errors.
  3. At the end, I suggest you print a display to the user to indicate the current status of the submodules -- perhaps prompt them to add all and commit?

I'd like to mention that this style is not really what git submodules were designed for. Typically, you want to say "LibraryX" is at version "2.32" and will stay that way until I tell it to "upgrade".

That is, in a sense, what you are doing with the described script, but just more automatically. Care is required!

Update 2:

If you are on a windows platform, you may want to look at using Python to implement the script as it is very capable in these areas. If you are on unix/linux, then I suggest just a bash script.

Need any clarifications? Just post a comment.

Purpose of installing Twitter Bootstrap through npm?

  1. Use npm/bower to install bootstrap if you want to recompile it/change less files/test. With grunt it would be easier to do this, as shown on http://getbootstrap.com/getting-started/#grunt. If you only want to add precompiled libraries feel free to manually include files to project.

  2. No, you have to do this by yourself or use separate grunt tool. For example 'grunt-contrib-concat' How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

Best way to check if MySQL results returned in PHP?

One way to do it is to check what mysql_num_rows returns. A minimal complete example would be the following:

if ($result = mysql_query($sql) && mysql_num_rows($result) > 0) {
    // there are results in $result
} else {
    // no results
}

But it's recommended that you check the return value of mysql_query and handle it properly in the case it's false (which would be caused by an error); probably by also calling mysql_error and logging the error somewhere.

How to import data from one sheet to another

VLookup

You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4". VLOOKUP example

External Reference

To reference a cell of the same Workbook use the following pattern:

<Sheetname>!<Cell>

Example:

Table1!A1

To reference a cell of a different Workbook use this pattern:

[<Workbook_name>]<Sheetname>!<Cell>

Example:

[MyWorkbook]Table1!A1

Unable to execute dex: method ID not in [0, 0xffff]: 65536

As already stated, you have too many methods (more than 65k) in your project and libs.

Prevent the Problem: Reduce the number of methods with Play Services 6.5+ and support-v4 24.2+

Since often the Google Play services is one of the main suspects in "wasting" methods with its 20k+ methods. Google Play services version 6.5 or later, it is possible for you to include Google Play services in your application using a number of smaller client libraries. For example, if you only need GCM and maps you can choose to use these dependencies only:

dependencies {
    compile 'com.google.android.gms:play-services-base:6.5.+'
    compile 'com.google.android.gms:play-services-maps:6.5.+'
}

The full list of sub libraries and it's responsibilities can be found in the official google doc.

Update: Since Support Library v4 v24.2.0 it was split up into the following modules:

support-compat, support-core-utils, support-core-ui, support-media-compat and support-fragment

dependencies {
    compile 'com.android.support:support-fragment:24.2.+'
}

Do note however, if you use support-fragment, it will have dependencies to all the other modules (ie. if you use android.support.v4.app.Fragment there is no benefit)

See here the official release notes for support-v4 lib


Enable MultiDexing

Since Lollipop (aka build tools 21+) it is very easy to handle. The approach is to work around the 65k methods per dex file problem to create multiple dex files for your app. Add the following to your gradle build file (this is taken from the official google doc on applications with more than 65k methods):

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.0"

    defaultConfig {
        ...
        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

The second step is to either prepare your Application class or if you don't extend Application use the MultiDexApplication in your Android Manifest:

Either add this to your Application.java

@Override
  protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
  }

or use the provided application from the mutlidex lib

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

Prevent OutOfMemory with MultiDex

As further tip, if you run into OutOfMemory exceptions during the build phase you could enlarge the heap with

android {
    ...
    dexOptions {
        javaMaxHeapSize "4g"
    }
}

which would set the heap to 4 gigabytes.

See this question for more detail on the dex heap memory issue.


Analyze the source of the Problem

To analyze the source of the methods the gradle plugin https://github.com/KeepSafe/dexcount-gradle-plugin can help in combination with the dependency tree provided by gradle with e.g.

.\gradlew app:dependencies

See this answer and question for more information on method count in android

/bin/sh: apt-get: not found

The image you're using is Alpine based, so you can't use apt-get because it's Ubuntu's package manager.

To fix this just use:

apk update and apk add

pytest cannot import module while python can

Another special case:

I had the problem using tox. So my program ran fine, but unittests via tox kept complaining. After installing packages (needed for the program) you need to additionally specify the packages used in the unittests in the tox.ini

[testenv]
deps =
    package1
    package2 
...

PHP how to get local IP of system

It is very simple and above answers are complicating things. Simply you can get both local and public ip addresses using this method.

   <?php 
$publicIP = file_get_contents("http://ipecho.net/plain");
echo $publicIP;

$localIp = gethostbyname(gethostname());
echo $localIp;

?>

What's the yield keyword in JavaScript?

Yeild keyword in javaScript function makes it generator,

what is generator in javaScript?

A generator is a function that produces a sequence of results instead of a single value, i.e you generate ?a series of values

Meaning generators helps us work asynchronously with the help iterators, Oh now what the hack iterators are? really?

Iterators are mean through which we are able to access items one at a time

from where iterator help us accessing item one at a time? it help us accessing items through generator functions,

generator functions are those in which we use yeild keyword, yield keyword help us in pausing and resuming execution of function

here is quick example

function *getMeDrink() {

    let question1 = yield 'soda or beer' // execution will pause here because of yield

 if (question1 == 'soda') {

            return 'here you get your soda'

    }

    if (question1 == 'beer') {

        let question2 = yield 'Whats your age' // execution will pause here because of yield

        if (question2 > 18) {

            return "ok you are eligible for it"

        } else {

            return 'Shhhh!!!!'

        }
    }
}


let _getMeDrink = getMeDrink() // initialize it

_getMeDrink.next().value  // "soda or beer"

_getMeDrink.next('beer').value  // "Whats your age"

_getMeDrink.next('20').value  // "ok you are eligible for it"

_getMeDrink.next().value // undefined

let me brifly explain what is going on

you noticed execution is being paused at each yeild keyword and we are able to access first yield with help of iterator .next()

this iterates to all yield keywords one at a time and then returns undefined when there is no more yield keywords left in simple words you can say yield keyword is break point where function each time pauses and only resume when call it using iterator

for our case: _getMeDrink.next() this is example of iterator that is helping us accessing each break point in function

Example of Generators: async/await

if you see implementation of async/await you will see generator functions & promises are used to make async/await work

please point out any suggestions is welcomed

how to get session id of socket.io client in Client

I just had the same problem/question and solved it like this (only client code):

var io = io.connect('localhost');

io.on('connect', function () {
    console.log(this.socket.sessionid);
});

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

This command with --user 0 do the job:

adb uninstall --user 0 <package_name>

Laravel Eloquent inner join with multiple conditions

This is not politically correct but works

   ->leftJoin("players as p","n.item_id", "=", DB::raw("p.id_player and n.type='player'"))

How can I pass some data from one controller to another peer controller

Definitely use a service to share data between controllers, here is a working example. $broadcast is not the way to go, you should avoid using the eventing system when there is a more appropriate way. Use a 'service', 'value' or 'constant' (for global constants).

http://plnkr.co/edit/ETWU7d0O8Kaz6qpFP5Hp

Here is an example with an input so you can see the data mirror on the page: http://plnkr.co/edit/DbBp60AgfbmGpgvwtnpU

var testModule = angular.module('testmodule', []);

testModule
   .controller('QuestionsStatusController1',
    ['$rootScope', '$scope', 'myservice',
    function ($rootScope, $scope, myservice) {
       $scope.myservice = myservice;   
    }]);

testModule
   .controller('QuestionsStatusController2',
    ['$rootScope', '$scope', 'myservice',
    function ($rootScope, $scope, myservice) {
      $scope.myservice = myservice;
    }]);

testModule
    .service('myservice', function() {
      this.xxx = "yyy";
    });

need to test if sql query was successful

This has proven the safest mechanism for me to test for failure on insert or update:

$result = $db->query(' ... ');
if ((gettype($result) == "object" && $result->num_rows == 0) || !$result) {
   failure 
}

Defining constant string in Java?

simply use

final String WELCOME_MESSAGE = "Hello, welcome to the server";

the main part of this instruction is the 'final' keyword.

How can I apply styles to multiple classes at once?

Don’t Repeat Your CSS

 a.abc, a.xyz{
    margin-left:20px;
 }

OR

 a{
    margin-left:20px;
 }

variable is not declared it may be inaccessible due to its protection level

I got this error briefly after renaming the App_Code folder. Actually, I accidentally dragged the whole folder to the App_data folder. VS 2015 didn't complain it was difficult to spot what had gone wrong.

How to save LogCat contents to file?

In addition to answer by Dinesh Prajapati, Use

 adb -d logcat <your package name>:<log level>

where -d is for device and you may also choose -e instead for emulator log and log level is a/d/i/v/e/w etc.

Now your command goes like:

adb -d logcat com.example.example:V > logfileName_WithPath.txt

How to create a GUID in Excel?

This is not a problem with the function at all.

It took me a bit of digging, but the problem is in copying and pasting. Try copying this: RANDBETWEEN(0,6553??5) string, posted in your original question, and paste it into a Hex Editor, then you'll see that there are actually two null characters in the 65535:

00000000  52 41 4E 44 42 45 54 57 45 45 4E 28 30 2C 36 35  RANDBETWEEN(0,65
00000010  35 33 00 00 35 29                                53?..?5)

Uncaught ReferenceError: jQuery is not defined

you need to put it after wp_head(); Because that loads your jQuery and you need to load jQuery first and then your js

How to append a date in batch files

@SETLOCAL ENABLEDELAYEDEXPANSION

@REM Use WMIC to retrieve date and time
@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    IF NOT "%%~F"=="" (
        SET /A SortDate = 10000 * %%F + 100 * %%D + %%A
        set YEAR=!SortDate:~0,4!
        set MON=!SortDate:~4,2!
        set DAY=!SortDate:~6,2!
        @REM Add 1000000 so as to force a prepended 0 if hours less than 10
        SET /A SortTime = 1000000 + 10000 * %%B + 100 * %%C + %%E
        set HOUR=!SortTime:~1,2!
        set MIN=!SortTime:~3,2!
        set SEC=!SortTime:~5,2!
    )
)
@echo on
@echo DATE=%DATE%, TIME=%TIME%
@echo HOUR=!HOUR! MIN=!MIN! SEC=!SEC!
@echo YR=!YEAR! MON=!MON! DAY=!DAY! 
@echo DATECODE= '!YEAR!!MON!!DAY!!HOUR!!MIN!' 

Output:

DATE=2015-05-20, TIME= 1:30:38.59
HOUR=01 MIN=30 SEC=38
YR=2015 MON=05 DAY=20
DATECODE= '201505200130'

Modifying a query string without reloading the page

I've used the following JavaScript library with great success:

https://github.com/balupton/jquery-history

It supports the HTML5 history API as well as a fallback method (using #) for older browsers.

This library is essentially a polyfill around `history.pushState'.

I just assigned a variable, but echo $variable shows something else

Additional to putting the variable in quotation, one could also translate the output of the variable using tr and converting spaces to newlines.

$ echo $var | tr " " "\n"
foo
bar
baz

Although this is a little more convoluted, it does add more diversity with the output as you can substitute any character as the separator between array variables.

Node.js spawn child process and get terminal output live

PHP-like passthru

import { spawn } from 'child_process';

export default async function passthru(exe, args, options) {
    return new Promise((resolve, reject) => {
        const env = Object.create(process.env);
        const child = spawn(exe, args, {
            ...options,
            env: {
                ...env,
                ...options.env,
            },
        });
        child.stdout.setEncoding('utf8');
        child.stderr.setEncoding('utf8');
        child.stdout.on('data', data => console.log(data));
        child.stderr.on('data', data => console.log(data));
        child.on('error', error => reject(error));
        child.on('close', exitCode => {
            console.log('Exit code:', exitCode);
            resolve(exitCode);
        });
    });
}

Usage

const exitCode = await passthru('ls', ['-al'], { cwd: '/var/www/html' })

VBA Excel - Insert row below with same format including borders and frames

well, using the Macro record, and doing it manually, I ended up with this code .. which seems to work .. (although it's not a one liner like yours ;)

lrow = Selection.Row()
Rows(lrow).Select
Selection.Copy
Rows(lrow + 1).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False
Selection.ClearContents

(I put the ClearContents in there because you indicated you wanted format, and I'm assuming you didn't want the data ;) )

NTFS performance and large volumes of files and directories

I had real experience with about 100 000 files (each several MBs) on NTFS in a directory while copying one online library.

It takes about 15 minutes to open the directory with Explorer or 7-zip.

Writing site copy with winhttrack will always get stuck after some time. It dealt also with directory, containing about 1 000 000 files. I think the worst thing is that the MFT can only by traversed sequentially.

Opening the same under ext2fsd on ext3 gave almost the same timing. Probably moving to reiserfs (not reiser4fs) can help.

Trying to avoid this situation is probably the best.

For your own programs using blobs w/o any fs could be beneficial. That's the way Facebook does for storing photos.

Uploading multiple files using formData()

To upload multiple files with angular form data, make sure you have this in your component.html

Upload Documents

                <div class="row">


                  <div class="col-md-4">
                     &nbsp; <small class="text-center">  Driver  Photo</small>
                    <div class="form-group">
                      <input  (change)="onFileSelected($event, 'profilepic')"  type="file" class="form-control" >
                    </div>
                  </div>

                  <div class="col-md-4">
                     &nbsp; <small> Driver ID</small>
                    <div class="form-group">
                      <input  (change)="onFileSelected($event, 'id')"  type="file" class="form-control" >
                    </div>
                  </div>

                  <div class="col-md-4">
                    &nbsp; <small>Driving Permit</small>
                    <div class="form-group">
                      <input type="file"  (change)="onFileSelected($event, 'drivingpermit')" class="form-control"  />
                    </div>
                  </div>
                </div>



                <div class="row">
                    <div class="col-md-6">
                       &nbsp; <small>Car Registration</small>
                      <div class="form-group">
                        <div class="input-group mb-4">
                            <input class="form-control" 
                (change)="onFileSelected($event, 'carregistration')" type="file"> <br>
                        </div>
                      </div>
                    </div>

                    <div class="col-md-6">
                        <small id="li"> Car Insurance</small>
                      <div class="form-group">
                        <div class="input-group mb-4">
                          <input class="form-control" (change)="onFileSelected($event, 

                         'insurancedocs')"   type="file">
                        </div>
                      </div>
                    </div>

                  </div>


                <div style="align-items:c" class="modal-footer">
                    <button type="button" class="btn btn-secondary" data- 
                  dismiss="modal">Close</button>
                    <button class="btn btn-primary"  (click)="uploadFiles()">Upload 
                  Files</button>
                  </div>
              </form>

In your componenet.ts file declare array selected files like this

selectedFiles = [];

// array of selected files

onFileSelected(event, type) {
    this.selectedFiles.push({ type, file: event.target.files[0] });
  }

//in the upload files method, append your form data like this

uploadFiles() {
    const formData = new FormData(); 

    this.selectedFiles.forEach(file => {
      formData.append(file.type, file.file, file.file.name); 
    });
    formData.append("driverid", this.driverid);

    this.driverService.uploadDriverDetails(formData).subscribe(
      res => {
        console.log(res); 

      },
      error => console.log(error.message)
    );
  }

NOTE: I hope this solution works for you friends

How to insert a character in a string at a certain position?

For Kotlin dudes ;) from the accepted answer (@MikeThomsen's)

fun String.insert(index: Int, string: String): String {
    return this.substring(0, index) + string + this.substring(index, this.length)
}

Test ?

"ThisTest".insert(4, "Is").should.equal("ThisIsTest")

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

Generate war file from tomcat webapp folder

Its just like creating a WAR file of your project, you can do it in several ways (from Eclipse, command line, maven).

If you want to do from command line, the command is

jar -cvf my_web_app.war * 

Which means, "compress everything in this directory into a file named my_web_app.war" (c=create, v=verbose, f=file)

How do I apply CSS3 transition to all properties except background-position?

Here's a solution that also works on Firefox:

transition: all 0.3s ease, background-position 1ms;

I made a small demo: http://jsfiddle.net/aWzwh/

No output to console from a WPF application?

Old post, but I ran into this so if you're trying to output something to Output in a WPF project in Visual Studio, the contemporary method is:

Include this:

using System.Diagnostics;

And then:

Debug.WriteLine("something");

How to get an enum value from a string value in Java?

Adding on to the top rated answer, with a helpful utility...

valueOf() throws two different Exceptions in cases where it doesn't like its input.

  • IllegalArgumentException
  • NullPointerExeption

If your requirements are such that you don't have any guarantee that your String will definitely match an enum value, for example if the String data comes from a database and could contain old version of the enum, then you'll need to handle these often...

So here's a reusable method I wrote which allows us to define a default Enum to be returned if the String we pass doesn't match.

private static <T extends Enum<T>> T valueOf( String name , T defaultVal) {
        try {
            return Enum.valueOf(defaultVal.getDeclaringClass() , name);
        } catch (IllegalArgumentException | NullPointerException e) {
            return defaultVal;
        }
    }

Use it like this:

public enum MYTHINGS {
    THINGONE,
    THINGTWO
}

public static void main(String [] asd) {
  valueOf("THINGTWO" , MYTHINGS.THINGONE);//returns MYTHINGS.THINGTWO
  valueOf("THINGZERO" , MYTHINGS.THINGONE);//returns MYTHINGS.THINGONE
}

Google API for location, based on user IP address

It looks like Google actively frowns on using IP-to-location mapping:

https://developers.google.com/maps/articles/geolocation?hl=en

That article encourages using the W3C geolocation API. I was a little skeptical, but it looks like almost every major browser already supports the geolocation API:

http://caniuse.com/geolocation

putting a php variable in a HTML form value

value="<?php echo htmlspecialchars($name); ?>"

Killing a process created with Python's subprocess.Popen()

process.terminate() doesn't work when using shell=True. This answer will help you.

lodash: mapping array to object

Another way with lodash 4.17.2

_.chain(params)
    .keyBy('name')
    .mapValues('input')
    .value();

or

_.mapValues(_.keyBy(params, 'name'), 'input')

or with _.reduce

_.reduce(
    params,
    (acc, { name, input }) => ({ ...acc, [name]: input }),
    {}
)

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

If it is something to do with the data in your database, why not utilize database isolation locking to achieve?

BeautifulSoup: extract text from anchor tag

print(link_addres.contents[0])

It will print the context of the anchor tags

example:

 statement_title = statement.find('h2',class_='briefing-statement__title')
 statement_title_text = statement_title.a.contents[0]

c# datatable insert column at position 0

    //Example to define how to do :

    DataTable dt = new DataTable();   

    dt.Columns.Add("ID");
    dt.Columns.Add("FirstName");
    dt.Columns.Add("LastName");
    dt.Columns.Add("Address");
    dt.Columns.Add("City");
           //  The table structure is:
            //ID    FirstName   LastName    Address     City

       //Now we want to add a PhoneNo column after the LastName column. For this we use the                               
             //SetOrdinal function, as iin:
        dt.Columns.Add("PhoneNo").SetOrdinal(3);

            //3 is the position number and positions start from 0.`enter code here`

               //Now the table structure will be:
              // ID      FirstName   LastName    PhoneNo    Address     City

Bootstrap control with multiple "data-toggle"

HTML (ejs dianmic web page): this is a table list of all users and from nodejs generate the table. NodeJS provide dinamic "<%= user.id %>". simply change for any value like "54"

<span type="button" data-href='/admin/user/del/<%= user.id %>' class="item" 
 data-toggle="modal" data-target="#confirm_delete">
    <div data-toggle="tooltip" data-placement="top" title="Delete" data- 
     toggle="modal">
       <i class="zmdi zmdi-delete"></i> 
    </div>
</span>
<div class="modal fade" id="confirm_delete" tabindex="-1" role="dialog" aria-labelledby="staticModalLabel" aria-hidden="true"
         data-backdrop="static">
  <div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="staticModalLabel">Static Modal</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button>
      </div>
      <div class="modal-body">
        <p> This is a static modal, backdrop click will not close it. </p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
          <form method="POST" class="btn-ok">
            <input  type="submit" class="btn btn-danger" value="Confirm"></input>
        </form>
      </div>
    </div>
  </div>
</div>
<!-- end modal static --> 

JS:

    $(document).ready(function(){
        $('#confirm_delete').on('show.bs.modal', function(e) {
            $(this).find('.btn-ok').attr('action', $(e.relatedTarget).data('href'));
        });
    });

The difference between sys.stdout.write and print?

My question is whether or not there are situations in which sys.stdout.write() is preferable to print

If you're writing a command line application that can write to both files and stdout then it is handy. You can do things like:

def myfunc(outfile=None):
    if outfile is None:
        out = sys.stdout
    else:
        out = open(outfile, 'w')
    try:
        # do some stuff
        out.write(mytext + '\n')
        # ...
    finally:
        if outfile is not None:
            out.close()

It does mean you can't use the with open(outfile, 'w') as out: pattern, but sometimes it is worth it.

How to get default gateway in Mac OSX

You can try with:

route -n get default

It is not the same as GNU/Linux's route -n (or even ip route show) but is useful for checking the default route information. Also, you can check the route that packages will take to a particular host. E.g.

route -n get www.yahoo.com

The output would be similar to:

   route to: 98.137.149.56
destination: default
       mask: 128.0.0.0
    gateway: 5.5.0.1
  interface: tun0
      flags: <UP,GATEWAY,DONE,STATIC,PRCLONING>
 recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire
       0         0         0         0         0         0      1500         0

IMHO netstat -nr is what you need. Even MacOSX's Network utility app(*) uses the output of netstat to show routing information. Network utility screenshot displaying routing table information

I hope this helps :)

(*) You can start Network utility with open /Applications/Utilities/Network\ Utility.app

MSSQL Regular expression

Thank you all for your help.

This is what I have used in the end:

SELECT *, 
  CASE WHEN [url] NOT LIKE '%[^-A-Za-z0-9/.+$]%' 
    THEN 'Valid' 
    ELSE 'No valid' 
  END [Validate]
FROM 
  *table*
  ORDER BY [Validate]

Send file using POST from a Python script

I am trying to test django rest api and its working for me:

def test_upload_file(self):
        filename = "/Users/Ranvijay/tests/test_price_matrix.csv"
        data = {'file': open(filename, 'rb')}
        client = APIClient()
        # client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
        response = client.post(reverse('price-matrix-csv'), data, format='multipart')

        print response
        self.assertEqual(response.status_code, status.HTTP_200_OK)

How can I scroll a div to be visible in ReactJS?

With reacts Hooks:

  1. Import
import ReactDOM from 'react-dom';
import React, {useRef} from 'react';
  1. Make new hook:
const divRef = useRef<HTMLDivElement>(null);
  1. Add new Div
<div ref={divRef}/>
  1. Scroll function:
const scrollToDivRef  = () => {
    let node = ReactDOM.findDOMNode(divRef.current) as Element;
    node.scrollIntoView({block: 'start', behavior: 'smooth'});
}

What is the most robust way to force a UIView to redraw?

I had a problem with a big delay between calling setNeedsDisplay and drawRect: (5 seconds). It turned out I called setNeedsDisplay in a different thread than the main thread. After moving this call to the main thread the delay went away.

Hope this is of some help.

AngularJS multiple filter with custom filter function

In view file (HTML or EJS)

<div ng-repeat="item in vm.itemList  | filter: myFilter > </div>

and In Controller

$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}

How do I download a package from apt-get without installing it?

Try

apt-get -d install <packages>

It is documented in man apt-get.

Just for clarification; the downloaded packages are located in the apt package cache at

/var/cache/apt/archives

How to start activity in another application?

If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest

android:exported="true"

Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.

finish();

The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class in the code, so compile will fail.

I searched on the web and found something like this below, and it works well.

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);

You can also use the setClassName method:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();

You can also pass the values from one app to another app :

Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
    launchIntent.putExtra("AppID", "MY-CHILD-APP1");
    launchIntent.putExtra("UserID", "MY-APP");
    launchIntent.putExtra("Password", "MY-PASSWORD");
    startActivity(launchIntent);
    finish();
} else {
    Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

how to pass command line arguments to main method dynamically

If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.

Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3

The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.

Consider a program ArgsTest.java:

package test;

import java.io.IOException;

    public class ArgsTest {

        public static void main(String[] args) throws IOException {

            System.out.println("Program Arguments:");
            for (String arg : args) {
                System.out.println("\t" + arg);
            }

            System.out.println("System Properties from VM Arguments");
            String sysProp1 = "sysProp1";
            System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
            String sysProp2 = "sysProp2";
            System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));

        }
    }

If given input as,

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3 

in the commandline, in project bin folder would give the following result:

Program Arguments:
  pro1
  pro2
  pro3
System Properties from VM Arguments
  Name:sysProp1, Value:sp1
  Name:sysProp2, Value:sp2

How to get a substring between two strings in PHP?

Try this, Its work for me, get data between test word.

$str = "Xdata test HD01 test 1data";  
$result = explode('test',$str);   
print_r($result);
echo $result[1];

How do I restrict an input to only accept numbers?

There are a few ways to do this.

You could use type="number":

<input type="number" />

Alternatively - I created a reuseable directive for this that uses a regular expression.

Html

<div ng-app="myawesomeapp">
    test: <input restrict-input="^[0-9-]*$" maxlength="20" type="text" class="test" />
</div>

Javascript

;(function(){
    var app = angular.module('myawesomeapp',[])
    .directive('restrictInput', [function(){

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var ele = element[0];
                var regex = RegExp(attrs.restrictInput);
                var value = ele.value;

                ele.addEventListener('keyup',function(e){
                    if (regex.test(ele.value)){
                        value = ele.value;
                    }else{
                        ele.value = value;
                    }
                });
            }
        };
    }]);    
}());

Windows.history.back() + location.reload() jquery

window.history.back() does not support reload or refresh of the page. But you can use following if you are okay with an extra refresh

window.history.back()
window.location.reload()

However a real complete solution would be as follows: I wrote a service to keep track of previous page and then navigate to that page with reload:true

Here is how i did it.

'use strict';

angular.module('tryme5App')
    .factory('RouterTracker', function RouterTracker($rootScope) {
          var routeHistory = [];
          var service = {
            getRouteHistory: getRouteHistory
          };

          $rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
              routeHistory = [];
              routeHistory.push({route: from, routeParams: fromParams});
          });

          function getRouteHistory() {
            return routeHistory;
          }

          return service;       
    });

Make sure you have included this js file from you index.html

<script src="scripts/components/util/route.service.js"></script>

Now from you stateprovider or controller you can access this service and navigate

var routeHistory = RouterTracker.getRouteHistory();    
console.log(routeHistory[0].route.name)
$state.go(routeHistory[0].route.name, null, { reload: true });

or alternatively even perform checks and conditional routing

var routeHistory = RouterTracker.getRouteHistory();    
console.log(routeHistory[0].route.name)
if(routeHistory[0].route.name == 'seat') {
      $state.go('seat', null, { reload: true });
} else {
      window.history.back()
}

Make sure you have added RouterTracker as an argument in your function in my case it was :

.state('seat.new', {
                parent: 'seat',
                url: '/new',
                data: {
                    authorities: ['ROLE_USER'],
                },
                onEnter: ['$stateParams', '$state', '$uibModal', 'RouterTracker', function($stateParams, $state, $uibModal, RouterTracker) {
  $uibModal.open({
      //....Open dialog.....
 }).result.then(function(result) {
            var routeHistory = RouterTracker.getRouteHistory();    
            console.log(routeHistory[0].route.name)
            $state.go(routeHistory[0].route.name, null, { reload: true });
 }, function() {
                    $state.go('^');
 })

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

Give you something different, when you encounter this kind of error, cannot create bean datasource in a test case.

It might be caused by some reasons:

  1. No datasource, you will need to create your datasource, h2 in-memory datasource or whatever, or you can choose the way like exclude={datasource··}.
  2. You have your datasource, like MySQL, but it still not work. It was caused by class AutoConfigureTestDatabase, It will choose a datasource for you which may cause ambiguity.

Solution: add @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) to avoid replace the default datasource.

JavaScript: How to find out if the user browser is Chrome?

all answers are wrong. "Opera" and "Chrome" are same in all cases.

(edited part)

here is the right answer

if (window.chrome && window.chrome.webstore) {
    // this is Chrome
}

How do I select an element that has a certain class?

h2.myClass refers to all h2 with class="myClass".

.myClass h2 refers to all h2 that are children of (i.e. nested in) elements with class="myClass".

If you want the h2 in your HTML to appear blue, change the CSS to the following:

.myClass h2 {
    color: blue;
}

If you want to be able to reference that h2 by a class rather than its tag, you should leave the CSS as it is and give the h2 a class in the HTML:

<h2 class="myClass">This header should be BLUE to match the element.class selector</h2>

Download & Install Xcode version without Premium Developer Account

I am able to download it using apple's download website today. https://developer.apple.com/download/

I do not have a paid apple developer account. Before I was only able to see xcode 8.3.3 but somehow today xcode 9 beta also appeared.

"Untrusted App Developer" message when installing enterprise iOS Application

For iOS 13.6

Go to settings -> General -> Device Management -> Click on Trust « Apple Development » -> Click on the red trust button and you’re all set! Enjoy

Cannot access a disposed object - How to fix?

Another place you could stop the timer is the FormClosing event - this happens before the form is actually closed, so is a good place to stop things before they might access unavailable resources.

Difference between opening a file in binary vs text

The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n on input, and conversely on output.


From the C99 standard (the N869 draft document), §7.19.2/2,

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

And in §7.19.3/2

Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.

About use of fseek, in §7.19.9.2/4:

For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

About use of ftell, in §17.19.9.4:

The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

I think that’s the most important, but there are some more details.

android edittext onchange listener

I have done it using AutotextView:

AutotextView textView = (AutotextView) findViewById(R.id.autotextview);
textView.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        seq = cs;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) {

    }

    @Override
    public void afterTextChanged(Editable arg0) {
        new SearchTask().execute(seq.toString().trim());
    }

});

Extract and delete all .gz in a directory- Linux

If you want to extract a single file use:

gunzip file.gz

It will extract the file and remove .gz file.

How to check if an app is installed from a web-page on an iPhone?

As of 2017, it seems there's no reliable way to detect an app is installed, and the redirection trick won't work everywhere.

For those like me who needs to deep link directly from emails (quite common), it is worth noting the following:

  • Sending emails with appScheme:// won't work fine because the links will be filtered in Gmail

  • Redirecting automatically to appScheme:// is blocked by Chrome: I suspect Chrome requires the redirection to be synchronous to an user interaction (like a click)

  • You can now deep link without appScheme:// and it's better but it requires a modern platform and additional setup. Android iOS


It is worth noting that other people already thought about this in depth. If you look at how Slack implements his "magic link" feature, you can notice that:

  • It sends an email with a regular http link (ok with Gmail)
  • The web page have a big button that links to appScheme:// (ok with Chrome)

How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?

For Windows, you can check the Java home location. If it contains (x86) it is 32-bit otherwise 64-bit:

public static boolean is32Bit()
{
    val javaHome = System.getProperty("java.home");
    return javaHome.contains("(x86)");
}

public static boolean is64Bit()
{
    return !is32Bit();
}

Example paths:

C:\Program Files (x86)\Java\jdk1.8.0_181\bin\java.exe # 32-bit
C:\Program Files\Java\jdk-10.0.2\bin\java.exe # 64-bit

Why care about a Windows only solution?

If you need to know which bit version you're running on, you're likely fiddling around with native code on Windows so platform-independence is out of the window anyway.

HttpWebRequest using Basic authentication

First thing, for me ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 worked instead of Ssl3.

Secondly, I had to send the Basic Auth request along with some data (form-urlencoded). Here is the complete sample which worked for me perfectly, after trying many solutions.

Disclaimer: The code below is a mixture of solutions found on this link and some other stackoverflow links, thanks for the useful information.

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        String username = "user_name";
        String password = "password";
        String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));

        //Form Data
        var formData = "var1=val1&var2=val2";
        var encodedFormData = Encoding.ASCII.GetBytes(formData);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("THE_URL");
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = "POST";
        request.ContentLength = encodedFormData.Length;
        request.Headers.Add("Authorization", "Basic " + encoded);
        request.PreAuthenticate = true;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(encodedFormData, 0, encodedFormData.Length);
        }

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.

You asked if it is possible to change the circular dependency checking in those slf4j classes.

The simple answer is no.

  • It is unconditional ... as implemented.
  • It is implemented in a static initializer block ... so you can't override the implementation, and you can't stop it happening.

So the only way to change this would be to download the source code, modify the core classes to "fix" them, build and use them. That is probably a bad idea (in general) and probably not solution in this case; i.e. you risk triggering the stack overflow problem that the message warns about.

Reference:


The real solution (as you identified in your Answer) is to use the right JARs. My understanding is that the circularity that was detected is real and potentially problematic ... and unnecessary.

java.lang.OutOfMemoryError: Java heap space in Maven

To temporarily work around this problem, I found the following to be the quickest way:

export JAVA_TOOL_OPTIONS="-Xmx1024m -Xms1024m"

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

It is possible to avoid constructor annotations with jdk8 where optionally the compiler will introduce metadata with the names of the constructor parameters. Then with jackson-module-parameter-names module Jackson can use this constructor. You can see an example at post Jackson without annotations

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

As accepted answer has provided required info, and for more info about using and disabling App Transport Security one can find more on this.

For Per-Domain Exceptions add these to the Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>yourserver.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow HTTP requests-->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

But What If I Don’t Know All the Insecure Domains I Need to Use? Use following key in your Info.plist

<key>NSAppTransportSecurity</key>
<dict>
  <!--Include to allow all connections (DANGER)-->
  <key>NSAllowsArbitraryLoads</key>
      <true/>
</dict>

For more detail you can get from this link.

Map enum in JPA with fixed values?

My own solution to solve this kind of Enum JPA mapping is the following.

Step 1 - Write the following interface that we will use for all enums that we want to map to a db column:

public interface IDbValue<T extends java.io.Serializable> {

    T getDbVal();

}

Step 2 - Implement a custom generic JPA converter as follows:

import javax.persistence.AttributeConverter;

public abstract class EnumDbValueConverter<T extends java.io.Serializable, E extends Enum<E> & IDbValue<T>>
        implements AttributeConverter<E, T> {

    private final Class<E> clazz;

    public EnumDbValueConverter(Class<E> clazz){
        this.clazz = clazz;
    }

    @Override
    public T convertToDatabaseColumn(E attribute) {
        if (attribute == null) {
            return null;
        }
        return attribute.getDbVal();
    }

    @Override
    public E convertToEntityAttribute(T dbData) {
        if (dbData == null) {
            return null;
        }
        for (E e : clazz.getEnumConstants()) {
            if (dbData.equals(e.getDbVal())) {
                return e;
            }
        }
        // handle error as you prefer, for example, using slf4j:
        // log.error("Unable to convert {} to enum {}.", dbData, clazz.getCanonicalName());
        return null;
    }

}

This class will convert the enum value E to a database field of type T (e.g. String) by using the getDbVal() on enum E, and vice versa.

Step 3 - Let the original enum implement the interface we defined in step 1:

public enum Right implements IDbValue<Integer> {
    READ(100), WRITE(200), EDITOR (300);

    private final Integer dbVal;

    private Right(Integer dbVal) {
        this.dbVal = dbVal;
    }

    @Override
    public Integer getDbVal() {
        return dbVal;
    }
}

Step 4 - Extend the converter of step 2 for the Right enum of step 3:

public class RightConverter extends EnumDbValueConverter<Integer, Right> {
    public RightConverter() {
        super(Right.class);
    }
}

Step 5 - The final step is to annotate the field in the entity as follows:

@Column(name = "RIGHT")
@Convert(converter = RightConverter.class)
private Right right;

Conclusion

IMHO this is the cleanest and most elegant solution if you have many enums to map and you want to use a particular field of the enum itself as mapping value.

For all others enums in your project that need similar mapping logic, you only have to repeat steps 3 to 5, that is:

  • implement the interface IDbValue on your enum;
  • extend the EnumDbValueConverter with only 3 lines of code (you may also do this within your entity to avoid creating a separated class);
  • annotate the enum attribute with @Convert from javax.persistence package.

Hope this helps.

Overwriting my local branch with remote branch

git reset --hard

This is to revert all your local changes to the origin head

How can I implement a theme from bootswatch or wrapbootstrap in an MVC 5 project?

First, if you are able to locate your

bootstrap.css file

and

bootstrap.min.js file

in your computer, then what you just do is

First download your favorite theme i.e. from http://bootswatch.com/

Copy the downloaded bootstrap.css and bootstrap.min.js files

Then in your computer locate the existing files and replace them with the new downloaded files.

NOTE: ensure your downloaded files are renamed to what is in your folder

i.e.

enter image description here

Then you are good to go.

sometimes result may not display immediately. your may need to run the css on your browser as a way of refreshing

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

That's odd. Does your program compile and run successfully and only fail on 'Publish' or does it fail on every compile now?

Also, have you perhaps changed the file's properties' Build Action to something other than Compile?

Update multiple rows in same query using PostgreSQL

In addition to other answers, comments and documentation, the datatype cast can be placed on usage. This allows an easier copypasting:

update test as t set
    column_a = c.column_a::number
from (values
    ('123', 1),
    ('345', 2)  
) as c(column_b, column_a) 
where t.column_b = c.column_b::text;

pass **kwargs argument to another function with **kwargs

The ** syntax tells Python to collect keyword arguments into a dictionary. The save2 is passing it down as a non-keyword argument (a dictionary object). The openX is not seeing any keyword arguments so the **args doesn't get used. It's instead getting a third non-keyword argument (the dictionary). To fix that change the definition of the openX function.

def openX(filename, mode, kwargs):
    pass

Basic HTTP authentication with Node and Express 4

Express has removed this functionality and now recommends you use the basic-auth library.

Here's an example of how to use:

var http = require('http')
var auth = require('basic-auth')

// Create server
var server = http.createServer(function (req, res) {
  var credentials = auth(req)

  if (!credentials || credentials.name !== 'aladdin' || credentials.pass !== 'opensesame') {
    res.statusCode = 401
    res.setHeader('WWW-Authenticate', 'Basic realm="example"')
    res.end('Access denied')
  } else {
    res.end('Access granted')
  }
})

// Listen
server.listen(3000)

To send a request to this route you need to include an Authorization header formatted for basic auth.

Sending a curl request first you must take the base64 encoding of name:pass or in this case aladdin:opensesame which is equal to YWxhZGRpbjpvcGVuc2VzYW1l

Your curl request will then look like:

 curl -H "Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l" http://localhost:3000/

How to convert Django Model object to dict with its fields and values?

@Zags solution was gorgeous!

I would add, though, a condition for datefields in order to make it JSON friendly.

Bonus Round

If you want a django model that has a better python command-line display, have your models child class the following:

from django.db import models
from django.db.models.fields.related import ManyToManyField

class PrintableModel(models.Model):
    def __repr__(self):
        return str(self.to_dict())

    def to_dict(self):
        opts = self._meta
        data = {}
        for f in opts.concrete_fields + opts.many_to_many:
            if isinstance(f, ManyToManyField):
                if self.pk is None:
                    data[f.name] = []
                else:
                    data[f.name] = list(f.value_from_object(self).values_list('pk', flat=True))
            elif isinstance(f, DateTimeField):
                if f.value_from_object(self) is not None:
                    data[f.name] = f.value_from_object(self).timestamp()
            else:
                data[f.name] = None
            else:
                data[f.name] = f.value_from_object(self)
        return data

    class Meta:
        abstract = True

So, for example, if we define our models as such:

class OtherModel(PrintableModel): pass

class SomeModel(PrintableModel):
    value = models.IntegerField()
    value2 = models.IntegerField(editable=False)
    created = models.DateTimeField(auto_now_add=True)
    reference1 = models.ForeignKey(OtherModel, related_name="ref1")
    reference2 = models.ManyToManyField(OtherModel, related_name="ref2")

Calling SomeModel.objects.first() now gives output like this:

{'created': 1426552454.926738,
'value': 1, 'value2': 2, 'reference1': 1, u'id': 1, 'reference2': [1]}

How to check identical array in most efficient way?

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

MySQL Insert into multiple tables? (Database normalization?)

try this

$sql= " INSERT INTO users (username, password) VALUES('test', 'test') ";
mysql_query($sql);
$user_id= mysql_insert_id();
if(!empty($user_id) {

$sql=INSERT INTO profiles (userid, bio, homepage) VALUES($user_id,'Hello world!', 'http://www.stackoverflow.com');
/* or 
 $sql=INSERT INTO profiles (userid, bio, homepage) VALUES(LAST_INSERT_ID(),'Hello   world!', 'http://www.stackoverflow.com'); */
 mysql_query($sql);
};

References
PHP
MYSQL

JavaScript: How do I print a message to the error console?

A note about 'throw()' mentioned above. It seems that it stops execution of the page completely (I checked in IE8) , so it's not very useful for logging "on going processes" (like to track a certain variable...)

My suggestion is perhaps to add a textarea element somewhere in your document and to change (or append to) its value (which would change its text) for logging information whenever needed...

Laravel Eloquent LEFT JOIN WHERE NULL

You can also specify the columns in a select like so:

$c = Customer::select('*', DB::raw('customers.id AS id, customers.first_name AS first_name, customers.last_name AS last_name'))
->leftJoin('orders', function($join) {
  $join->on('customers.id', '=', 'orders.customer_id') 
})->whereNull('orders.customer_id')->first();

Angular 2 / 4 / 5 - Set base href dynamically

Based on your (@sharpmachine) answer, I was able to further refactor it a little, so that we don't have to hack out a function in index.html.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, Location } from '@angular/common';

import { AppComponent } from './';
import { getBaseLocation } from './shared/common-functions.util';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpModule,
  ],
  bootstrap: [AppComponent],
  providers: [
    appRoutingProviders,
    {
        provide: APP_BASE_HREF,
        useFactory: getBaseLocation
    },
  ]
})
export class AppModule { }

And, ./shared/common-functions.util.ts contains:

export function getBaseLocation() {
    let paths: string[] = location.pathname.split('/').splice(1, 1);
    let basePath: string = (paths && paths[0]) || 'my-account'; // Default: my-account
    return '/' + basePath;
}

How get all values in a column using PHP?

Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.


This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php

$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $storeArray[] =  $row['names'];  
}
// now $storeArray will have all the names.

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

you can use the download attribute on an a tag ...

<a href="data:image/jpeg;base64,/9j/4AAQSkZ..." download="filename.jpg"></a>

see more: https://developer.mozilla.org/en/HTML/element/a#attr-download

Save and load MemoryStream to/from a file

Save into a file

Car car = new Car();
car.Name = "Some fancy car";
MemoryStream stream = Serializer.SerializeToStream(car);
System.IO.File.WriteAllBytes(fileName, stream.ToArray());

Load from a file

using (var stream = new MemoryStream(System.IO.File.ReadAllBytes(fileName)))
{
    Car car = (Car)Serializer.DeserializeFromStream(stream);
}

where

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Serialization
{
    public class Serializer
    {
        public static MemoryStream SerializeToStream(object o)
        {
            MemoryStream stream = new MemoryStream();
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, o);
            return stream;
        }

        public static object DeserializeFromStream(MemoryStream stream)
        {
            IFormatter formatter = new BinaryFormatter();
            stream.Seek(0, SeekOrigin.Begin);
            object o = formatter.Deserialize(stream);
            return o;
        }
    }
}

Originally the implementation of this class has been posted here

and

[Serializable]
public class Car
{
    public string Name;
}

How to use Switch in SQL Server

This is a select statement, so each branch of the case must return something. If you want to perform actions, just use an if.

Write-back vs Write-Through caching?

Write-back and write-through describe policies when a write hit occurs, that is when the cache has the requested information. In these examples, we assume a single processor is writing to main memory with a cache.

Write-through: The information is written to the cache and memory, and the write finishes when both have finished. This has the advantage of being simpler to implement, and the main memory is always consistent (in sync) with the cache (for the uniprocessor case - if some other device modifies main memory, then this policy is not enough), and a read miss never results in writes to main memory. The obvious disadvantage is that every write hit has to do two writes, one of which accesses slower main memory.

Write-back: The information is written to a block in the cache. The modified cache block is only written to memory when it is replaced (in effect, a lazy write). A special bit for each cache block, the dirty bit, marks whether or not the cache block has been modified while in the cache. If the dirty bit is not set, the cache block is "clean" and a write miss does not have to write the block to memory.

The advantage is that writes can occur at the speed of the cache, and if writing within the same block only one write to main memory is needed (when the previous block is being replaced). The disadvantages are that this protocol is harder to implement, main memory can be not consistent (not in sync) with the cache, and reads that result in replacement may cause writes of dirty blocks to main memory.

The policies for a write miss are detailed in my first link.

These protocols don't take care of the cases with multiple processors and multiple caches, as is common in modern processors. For this, more complicated cache coherence mechanisms are required. Write-through caches have simpler protocols since a write to the cache is immediately reflected in memory.

Good resources:

Android Material Design Button Styles

I've just created an android library, that allows you to easily modify the button color and the ripple color

https://github.com/xgc1986/RippleButton

<com.xgc1986.ripplebutton.widget.RippleButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn"
    android:text="Android button modified in layout"
    android:textColor="@android:color/white"
    app:buttonColor="@android:color/black"
    app:rippleColor="@android:color/white"/>

You don't need to create an style for every button you want wit a different color, allowing you to customize the colors randomly

Emulate/Simulate iOS in Linux

On linux you can check epiphany-browser, resizes the windows you'll get same bugs as in ios. Both browsers uses Webkit.

Ubuntu/Mint:

sudo apt install epiphany-browser

Plot multiple lines (data series) each with unique color in R

If your data is in wide format matplot is made for this and often forgotten about:

 dat <- matrix(runif(40,1,20),ncol=4) # make data
 matplot(dat, type = c("b"),pch=1,col = 1:4) #plot
 legend("topleft", legend = 1:4, col=1:4, pch=1) # optional legend

There is also the added bonus for those unfamiliar with things like ggplot that most of the plotting paramters such as pch etc. are the same using matplot() as plot(). enter image description here

How to find a number in a string using JavaScript?

// stringValue can be anything in which present any number
`const stringValue = 'last_15_days';
// /\d+/g is regex which is used for matching number in string
// match helps to find result according to regex from string and return match value
 const result = stringValue.match(/\d+/g);
 console.log(result);`

output will be 15

If You want to learn more about regex here are some links:

https://www.w3schools.com/jsref/jsref_obj_regexp.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

https://www.tutorialspoint.com/javascript/javascript_regexp_object.htm

Bootstrap 3 - set height of modal window according to screen size

I assume you want to make modal use as much screen space as possible on phones. I've made a plugin to fix this UX problem of Bootstrap modals on mobile phones, you can check it out here - https://github.com/keaukraine/bootstrap-fs-modal

All you will need to do is to apply modal-fullscreen class and it will act similar to native screens of iOS/Android.

Remote JMX connection

I have the same issue and I change any hostname that matches the local host name to 0.0.0.0, it seems to work after I do that.

How to enter a formula into a cell using VBA?

I would do it like this:

Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)

In case you have some more complex formula it will be handy

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

If you use module with c++ code and have the same issue you could try

Build -> Refresh Linked C++ Projects

Also, you should open some file from this module and do

Build -> Make module "YourNativeLibModuleName"

Removing MySQL 5.7 Completely

First of all, do a backup of your needed databases with mysqldump

Note: If you want to restore later, just backup your relevant databases, and not the WHOLE, because the whole database might actually be the reason you need to purge and reinstall).

In total, do this:

sudo service mysql stop  #or mysqld
sudo killall -9 mysql
sudo killall -9 mysqld
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser -f mysql
sudo rm -rf /var/lib/mysql
sudo apt-get purge mysql-server-core-5.7
sudo apt-get purge mysql-client-core-5.7
sudo rm -rf /var/log/mysql
sudo rm -rf /etc/mysql

All above commands in single line (just copy and paste):

sudo service mysql stop && sudo killall -9 mysql && sudo killall -9 mysqld && sudo apt-get remove --purge mysql-server mysql-client mysql-common && sudo apt-get autoremove && sudo apt-get autoclean && sudo deluser mysql && sudo rm -rf /var/lib/mysql && sudo apt-get purge mysql-server-core-5.7 && sudo apt-get purge mysql-client-core-5.7 && sudo rm -rf /var/log/mysql && sudo rm -rf /etc/mysql

How to ignore ansible SSH authenticity checking?

The most problems appear when you want to add new host to dynamic inventory (via add_host module) in playbook. I don't want to disable fingerprint host checking permanently so solutions like disabling it in a global config file are not ok for me. Exporting var like ANSIBLE_HOST_KEY_CHECKING before running playbook is another thing to do before running that need to be remembered.

It's better to add local config file in the same dir where playbook is. Create file named ansible.cfg and paste following text:

[defaults]
host_key_checking = False

No need to remember to add something in env vars or add to ansible-playbook options. It's easy to put this file to ansible git repo.

How can I make an svg scale with its parent container?

You'll want to do a transform as such:

with JavaScript:

document.getElementById(yourtarget).setAttribute("transform", "scale(2.0)");

With CSS:

#yourtarget {
  transform:scale(2.0);
  -webkit-transform:scale(2.0);
}

Wrap your SVG Page in a Group tag as such and target it to manipulate the whole page:

<svg>
  <g id="yourtarget">
    your svg page
  </g>
</svg>

Note: Scale 1.0 is 100%

JQuery - Get select value

var nationality = $("#dancerCountry").val(); should work. Are you sure that the element selector is working properly? Perhaps you should try:

var nationality = $('select[name="dancerCountry"]').val();

Eclipse comment/uncomment shortcut?


Comments In Java class


  1. Toggle/Single line Comment ( Ctrl+/ ) - Add/remove line comments (//…) from the current line.
  2. Add Block Comment ( Ctrl+Shift+\ ) - Wrap the selected lines in a block comment (/*… */).
  3. Remove Block Comment ( Ctrl+Shift+/ ) - Remove a block comment (/*… */) surrounding the selected lines.
  4. Add Javadoc Comment ( Alt+Shift+J ) - Add a Javadoc comment to the active field/method/class.

Comments In HTML/XML/Config file


  1. Add Block Comment ( Ctrl+Shift+/ ) - Wrap the selected lines in a block comment (< !-- -->).
  2. Remove Block Comment (Ctrl+Shift+\) - Remove a block comment (< !-- -->) surrounding the selected lines.

Optimal number of threads per core

The answer depends on the complexity of the algorithms used in the program. I came up with a method to calculate the optimal number of threads by making two measurements of processing times Tn and Tm for two arbitrary number of threads ‘n’ and ‘m’. For linear algorithms, the optimal number of threads will be N = sqrt ( (mn(Tm*(n-1) – Tn*(m-1)))/(nTn-mTm) ) .

Please read my article regarding calculations of the optimal number for various algorithms: pavelkazenin.wordpress.com

How to plot all the columns of a data frame in R

There is very simple way to plot all columns from a data frame using separate panels or the same panel:

plot.ts(data)

Which yields (where X1 - X4 are column names):

enter image description here

Have look at ?plot.ts for all the options.

If you wan't more control over your plotting function and not use a loop, you could also do something like:

par(mfcol = c(ncol(data), 1))
Map(function(x,y) plot(x, main =y), data, names(data))

How to present UIActionSheet iOS Swift?

You can use following code for open actionSheet in Swift

        let alert = UIAlertController(title: enter your title, message: "Enter your messgage. ", preferredStyle: UIAlertControllerStyle.Alert)

        alert.addTextFieldWithConfigurationHandler(configurationTextField)

        alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler:{ (UIAlertAction)in
            print("User click Cancel button")
        }))

        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
            print("User click Ok button")


        }))
        self.presentViewController(alert, animated: true, completion: {
            print("completion block")
        })

PHP Echo text Color

How about writing out some escape sequences?

echo "\033[01;31m Request has been sent. Please wait for my reply! \033[0m";

Won't work through browser though, only from console ;))

C++ STL Vectors: Get iterator from index?

way mentioned by @dirkgently ( v.begin() + index ) nice and fast for vectors

but std::advance( v.begin(), index ) most generic way and for random access iterators works constant time too.

EDIT
differences in usage:

std::vector<>::iterator it = ( v.begin() + index );

or

std::vector<>::iterator it = v.begin();
std::advance( it, index );

added after @litb notes.

How to create a floating action button (FAB) in android, using AppCompat v21?

@Justin Pollard xml code works really good. As a side note you can add a ripple effect with the following xml lines.

    <item>
    <ripple
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?android:colorControlHighlight" >
        <item android:id="@android:id/mask">
            <shape android:shape="oval" >
                <solid android:color="#FFBB00" />
            </shape>
        </item>
        <item>
            <shape android:shape="oval" >
                <solid android:color="@color/ColorPrimary" />
            </shape>
        </item>
    </ripple>
</item>

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

You should also be able to use..

swfobject.getFlashPlayerVersion().major === 0

with the swfobject-Plugin.

C#: Assign same value to multiple variables in single statement

It's as simple as:

num1 = num2 = 5;

When using an object property instead of variable, it is interesting to know that the get accessor of the intermediate value is not called. Only the set accessor is invoked for all property accessed in the assignation sequence.

Take for example a class that write to the console everytime the get and set accessor are invoked.

static void Main(string[] args)
{
    var accessorSource = new AccessorTest(5);
    var accessor1 = new AccessorTest();
    var accessor2 = new AccessorTest();

    accessor1.Value = accessor2.Value = accessorSource.Value;

    Console.ReadLine();
}

public class AccessorTest
{
    public AccessorTest(int value = default(int))
    {
        _Value = value;
    }

    private int _Value;

    public int Value
    {
        get
        {
            Console.WriteLine("AccessorTest.Value.get {0}", _Value);
            return _Value;
        }
        set
        {
            Console.WriteLine("AccessorTest.Value.set {0}", value);
            _Value = value;
        }
    }
}

This will output

AccessorTest.Value.get 5
AccessorTest.Value.set 5
AccessorTest.Value.set 5

Meaning that the compiler will assign the value to all properties and it will not re-read the value every time it is assigned.

How is a non-breaking space represented in a JavaScript string?

Remember that .text() strips out markup, thus I don't believe you're going to find &nbsp; in a non-markup result.

Made in to an answer....

var p = $('<p>').html('&nbsp;');
if (p.text() == String.fromCharCode(160) && p.text() == '\xA0')
    alert('Character 160');

Shows an alert, as the ASCII equivalent of the markup is returned instead.

How to do parallel programming in Python?

This can be done very elegantly with Ray.

To parallelize your example, you'd need to define your functions with the @ray.remote decorator, and then invoke them with .remote.

import ray

ray.init()

# Define the functions.

@ray.remote
def solve1(a):
    return 1

@ray.remote
def solve2(b):
    return 2

# Start two tasks in the background.
x_id = solve1.remote(0)
y_id = solve2.remote(1)

# Block until the tasks are done and get the results.
x, y = ray.get([x_id, y_id])

There are a number of advantages of this over the multiprocessing module.

  1. The same code will run on a multicore machine as well as a cluster of machines.
  2. Processes share data efficiently through shared memory and zero-copy serialization.
  3. Error messages are propagated nicely.
  4. These function calls can be composed together, e.g.,

    @ray.remote
    def f(x):
        return x + 1
    
    x_id = f.remote(1)
    y_id = f.remote(x_id)
    z_id = f.remote(y_id)
    ray.get(z_id)  # returns 4
    
  5. In addition to invoking functions remotely, classes can be instantiated remotely as actors.

Note that Ray is a framework I've been helping develop.

Make sure that the controller has a parameterless public constructor error

If you have an interface in your controller

public myController(IXInterface Xinstance){}

You must register them to Dependency Injection container.

container.Bind<IXInterface>().To<XClass>().InRequestScope();

How to give credentials in a batch script that copies files to a network location?

You can also map the share to a local drive as follows:

net use X: "\\servername\share" /user:morgan password

Hibernate error - QuerySyntaxException: users is not mapped [from users]

There is possibility you forgot to add mapping for created Entity into hibernate.cfg.xml, same error.

Dynamic type languages versus static type languages

It depends on context. There a lot benefits that are appropriate to dynamic typed system as well as for strong typed. I'm of opinion that the flow of dynamic types language is faster. The dynamic languages are not constrained with class attributes and compiler thinking of what is going on in code. You have some kinda freedom. Furthermore, the dynamic language usually is more expressive and result in less code which is good. Despite of this, it's more error prone which is also questionable and depends more on unit test covering. It's easy prototype with dynamic lang but maintenance may become nightmare.

The main gain over static typed system is IDE support and surely static analyzer of code. You become more confident of code after every code change. The maintenance is peace of cake with such tools.

Passing a Bundle on startActivity()?

You can pass values from one activity to another activity using the Bundle. In your current activity, create a bundle and set the bundle for the particular value and pass that bundle to the intent.

Intent intent = new Intent(this,NewActivity.class);
Bundle bundle = new Bundle();
bundle.putString(key,value);
intent.putExtras(bundle);
startActivity(intent);

Now in your NewActivity, you can get this bundle and retrive your value.

Bundle bundle = getArguments();
String value = bundle.getString(key);

You can also pass data through the intent. In your current activity, set intent like this,

Intent intent = new Intent(this,NewActivity.class);
intent.putExtra(key,value);
startActivity(intent);

Now in your NewActivity, you can get that value from intent like this,

String value = getIntent().getExtras().getString(key);

How do I insert values into a Map<K, V>?

The two errors you have in your code are very different.

The first problem is that you're initializing and populating your Map in the body of the class without a statement. You can either have a static Map and a static {//TODO manipulate Map} statement in the body of the class, or initialize and populate the Map in a method or in the class' constructor.

The second problem is that you cannot treat a Map syntactically like an array, so the statement data["John"] = "Taxi Driver"; should be replaced by data.put("John", "Taxi Driver"). If you already have a "John" key in your HashMap, its value will be replaced with "Taxi Driver".

Right way to reverse a pandas DataFrame?

This works:

    for i,r in data[::-1].iterrows():
        print(r['Odd'], r['Even'])

How are environment variables used in Jenkins with Windows Batch Command?

I should this On Windows, environment variable expansion is %BUILD_NUMBER%

How to get process ID of background process?

this is what I have done. Check it out, hope it can help.

#!/bin/bash
#
# So something to show.
echo "UNO" >  UNO.txt
echo "DOS" >  DOS.txt
#
# Initialize Pid List
dPidLst=""
#
# Generate background processes
tail -f UNO.txt&
dPidLst="$dPidLst $!"
tail -f DOS.txt&
dPidLst="$dPidLst $!"
#
# Report process IDs
echo PID=$$
echo dPidLst=$dPidLst
#
# Show process on current shell
ps -f
#
# Start killing background processes from list
for dPid in $dPidLst
do
        echo killing $dPid. Process is still there.
        ps | grep $dPid
        kill $dPid
        ps | grep $dPid
        echo Just ran "'"ps"'" command, $dPid must not show again.
done

Then just run it as: ./bgkill.sh with proper permissions of course

root@umsstd22 [P]:~# ./bgkill.sh
PID=23757
dPidLst= 23758 23759
UNO
DOS
UID        PID  PPID  C STIME TTY          TIME CMD
root      3937  3935  0 11:07 pts/5    00:00:00 -bash
root     23757  3937  0 11:55 pts/5    00:00:00 /bin/bash ./bgkill.sh
root     23758 23757  0 11:55 pts/5    00:00:00 tail -f UNO.txt
root     23759 23757  0 11:55 pts/5    00:00:00 tail -f DOS.txt
root     23760 23757  0 11:55 pts/5    00:00:00 ps -f
killing 23758. Process is still there.
23758 pts/5    00:00:00 tail
./bgkill.sh: line 24: 23758 Terminated              tail -f UNO.txt
Just ran 'ps' command, 23758 must not show again.
killing 23759. Process is still there.
23759 pts/5    00:00:00 tail
./bgkill.sh: line 24: 23759 Terminated              tail -f DOS.txt
Just ran 'ps' command, 23759 must not show again.
root@umsstd22 [P]:~# ps -f
UID        PID  PPID  C STIME TTY          TIME CMD
root      3937  3935  0 11:07 pts/5    00:00:00 -bash
root     24200  3937  0 11:56 pts/5    00:00:00 ps -f

Name [jdbc/mydb] is not bound in this Context

You need a ResourceLink in your META-INF/context.xml file to make the global resource available to the web application.

 <ResourceLink name="jdbc/mydb"
             global="jdbc/mydb"
              type="javax.sql.DataSource" />

How to debug Apache mod_rewrite

Based on Ben's answer you you could do the following when running apache on Linux (Debian in my case).

First create the file rewrite-log.load

/etc/apache2/mods-availabe/rewrite-log.load

RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3

Then enter

$ a2enmod rewrite-log

followed by

$ service apache2 restart

And when you finished with debuging your rewrite rules

$ a2dismod rewrite-log && service apache2 restart

TypeError: 'int' object is not callable

Stop stomping on round somewhere else by binding an int to it.

Google Chrome Printing Page Breaks

Beware of CSS : display:inline-block when printing.

None of the CCS property to go to next page would work for me in Chrome and Firefox if my table was inside a div with the style display:inline-block

For example, the following doesn't work :

<div style='display:inline-block'>
  <table style='page-break-before:always'>
    ...
  </table>
  <table style='page-break-before:always'>
    ...
  </table>
</div>

But the following work :

<div>
  <table style='page-break-before:always'>
    ...
  </table>
  <table style='page-break-before:always'>
    ...
  </table>
</div>

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

I put some animated gif in a form called FormWait and then I called it as:

// show the form
new Thread(() => new FormWait().ShowDialog()).Start();

// do the heavy stuff here

// get the form reference back and close it
FormWait f = new FormWait();
f = (FormWait)Application.OpenForms["FormWait"];
f.Close();

SSRS the definition of the report is invalid

I just had this same problem during a SSRS development of a Custom Report for MS CRM Dynamics 2011.

The reason because it occurred is because I am using some Hidden Parameters and for some of them I forget to give a default value.

So, because of I have few time to finish the report I forget to put the default value for some Parameters and I risked to lost more time to fix it.

Luckily I found it very fast because the error shows the textbox and the paragraph with the first wrong parameter but it didn't shows the name of the parameter:

"I cannot post the image of the error because this website don't allows me"

In general during SSRS developments it's very important to remember: - To put the report parameters in the correct sequence (the referred ones for first es. parameters inherited from master report or parameters essentials for sub-datasets) - To assign a default value to the Hide and Internal Parameters.

Comparing the contents of two files in Sublime Text

UPDATE
(Given the upvotes, I feel there is a need for a complete step-by-step explanation...)

  1. In the Menu bar click on File->Open Folder...
  2. Select a folder (the actual folder does not really matter, this step is just to make the FOLDERS sidebar available)
  3. If there is no Side Bar shown yet, make it appear via View -> Side Bar -> Show Side Bar
  4. Use this FOLDERS-titled Side Bar to navigate to the first file you want to compare.
  5. Select it (click on it), hold down ctrl and select the second file.
  6. Having two files selected, right click on one of the two and select Diff Files...

There should be a new Tab now showing the comparison.


Original short answer:
Note that:

The "Diff files" only appears with the "folders" sidebar (to open a folder: File->Open Folder) , not with "open files" sidebar.

Empty or Null value display in SSRS text boxes

Call a custom function?

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

You could always put a case statement in there to handle different types of 'blank' data.

Bootstrap col-md-offset-* not working

In bootstrap 3 the format is

col-md-6 col-md-offset-3

For the same grid in Bootstrap 4 the format is

col-md-6 offset-md-3

Count unique values using pandas groupby

I know it has been a while since this was posted, but I think this will help too. I wanted to count unique values and filter the groups by number of these unique values, this is how I did it:

df.groupby('group').agg(['min','max','count','nunique']).reset_index(drop=False)

Git says remote ref does not exist when I delete remote branch

For windows

git branch --remotes| %{ $_.Trim().Split("/")[1] }| ?{ $_ -ne 'master' } | | ?{ $_ -ne 'otherBranch' } | %{ git push origin --delete $_ }