Programs & Examples On #Timelapse

How can I quantify difference between two images?

A trivial thing to try:

Resample both images to small thumbnails (e.g. 64 x 64) and compare the thumbnails pixel-by-pixel with a certain threshold. If the original images are almost the same, the resampled thumbnails will be very similar or even exactly the same. This method takes care of noise that can occur especially in low-light scenes. It may even be better if you go grayscale.

Using sed and grep/egrep to search and replace

Honestly, much as I love sed for appropriate tasks, this is definitely a task for perl -- it's truly more powerful for this kind of one-liners, especially to "write it back to where it comes from" (perl's -i switch does it for you, and optionally also lets you keep the old version around e.g. with a .bak appended, just use -i.bak instead).

perl -i.bak -pe 's/\.jpg|\.png|\.gif/.jpg/

rather than intricate work in sed (if even possible there) or awk...

How to sort rows of HTML table that are called from MySQL

That's actually pretty easy, here's a possible approach:

<table>
    <tr>
        <th>
            <a href="?orderBy=type">Type:</a>
        </th>
        <th>
            <a href="?orderBy=description">Description:</a>
        </th>
        <th>
            <a href="?orderBy=recorded_date">Recorded Date:</a>
        </th>
        <th>
            <a href="?orderBy=added_date">Added Date:</a>
        </th>
    </tr>
</table>
<?php
$orderBy = array('type', 'description', 'recorded_date', 'added_date');

$order = 'type';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
    $order = $_GET['orderBy'];
}

$query = 'SELECT * FROM aTable ORDER BY '.$order;

// retrieve and show the data :)
?>

That'll do the trick! :)

Remove characters from NSString?

If you want to support more than one space at a time, or support any whitespace, you can do this:

NSString* noSpaces =
    [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
                           componentsJoinedByString:@""];

How to pass a value from Vue data to href?

Or you can do that with ES6 template literal:

<a :href="`/job/${r.id}`"

Convert hex string (char []) to int?

One quick & dirty solution:

// makes a number from two ascii hexa characters
int ahex2int(char a, char b){

    a = (a <= '9') ? a - '0' : (a & 0x7) + 9;
    b = (b <= '9') ? b - '0' : (b & 0x7) + 9;

    return (a << 4) + b;
}

You have to be sure your input is correct, no validation included (one could say it is C). Good thing it is quite compact, it works with both 'A' to 'F' and 'a' to 'f'.

The approach relies on the position of alphabet characters in the ASCII table, let's peek e.g. to Wikipedia (https://en.wikipedia.org/wiki/ASCII#/media/File:USASCII_code_chart.png). Long story short, the numbers are below the characters, so the numeric characters (0 to 9) are easily converted by subtracting the code for zero. The alphabetic characters (A to F) are read by zeroing other than last three bits (effectively making it work with either upper- or lowercase), subtracting one (because after the bit masking, the alphabet starts on position one) and adding ten (because A to F represent 10th to 15th value in hexadecimal code). Finally, we need to combine the two digits that form the lower and upper nibble of the encoded number.

Here we go with same approach (with minor variations):

#include <stdio.h>

// takes a null-terminated string of hexa characters and tries to 
// convert it to numbers
long ahex2num(unsigned char *in){

    unsigned char *pin = in; // lets use pointer to loop through the string
    long out = 0;  // here we accumulate the result

    while(*pin != 0){
        out <<= 4; // we have one more input character, so 
                   // we shift the accumulated interim-result one order up
        out +=  (*pin < 'A') ? *pin & 0xF : (*pin & 0x7) + 9; // add the new nibble
        pin++; // go ahead
    }

    return out;
}

// main function will test our conversion fn
int main(void) {

    unsigned char str[] = "1800785";  // no 0x prefix, please
    long num;

    num = ahex2num(str);  // call the function

    printf("Input: %s\n",str);  // print input string
    printf("Output: %x\n",num);  // print the converted number back as hexa
    printf("Check: %ld = %ld \n",num,0x1800785);  // check the numeric values matches

    return 0;
}

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

Replace None with NaN in pandas dataframe

You can use DataFrame.fillna or Series.fillna which will replace the Python object None, not the string 'None'.

import pandas as pd
import numpy as np

For dataframe:

df = df.fillna(value=np.nan)

For column or series:

df.mycol.fillna(value=np.nan, inplace=True)

Convert a PHP script into a stand-alone windows executable

I had problems with most of the tools in other answers as they are all very outdated.

If you need a solution that will "just work", pack a bare-bones version of php with your project in a WinRar SFX archive, set it to extract everything to a temporary directory and execute php your_script.php.

To run a basic script, the only files required are php.exe and php5.dll (or php5ts.dll depending on version).

To add extensions, pack them along with a php.ini file:

[PHP]
extension_dir = "."
extension=php_curl.dll
extension=php_xxxx.dll
...

Setting background images in JFrame

You can use the Background Panel class. It does the custom painting as explained above but gives you options to display the image scaled, tiled or normal size. It also explains how you can use a JLabel with an image as the content pane for the frame.

How to pass a PHP variable using the URL

I found this solution in "Super useful bits of PHP, Form and JavaScript code" at Skytopia.

Inside "page1.php" or "page1.html":

// Send the variables myNumber=1 and myFruit="orange" to the new PHP page...
<a href="page2c.php?myNumber=1&myFruit=orange">Send variables via URL!</a> 

    //or as I needed it.
    <a href='page2c.php?myNumber={$row[0]}&myFruit={$row[1]}'>Send variables</a>

Inside "page2c.php":

<?php
    // Retrieve the URL variables (using PHP).
    $num = $_GET['myNumber'];
    $fruit = $_GET['myFruit'];
    echo "Number: ".$num."  Fruit: ".$fruit;
?>

Spring application context external properties?

You can try something like this:

<context:property-placeholder 
        location="${ext.properties.dir:classpath:}/servlet.properties" />

And define ext.properties.dir property in your application server / jvm, otherwise the default properties location "classpath:/" (i.e., classes dir of .jar or .war) would be used:

-Dext.properties.dir=file:/usr/local/etc/

BTW, very useful blog post.

Remove last characters from a string in C#. An elegant way?

This will return to you a string excluding everything after the comma

str = str.Substring(0, str.IndexOf(','));

Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:

commaPos = str.IndexOf(',');
if(commaPos != -1)
    str = str.Substring(0, commaPos)

I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:

myInt = (int)double.Parse(myString)

This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.

Select values of checkbox group with jQuery

You can have a javascript variable which stores the number of checkboxes that are emitted, i.e in the <head> of the page:

<script type="text/javascript">
var num_cboxes=<?php echo $number_of_checkboxes;?>;
</script>

So if there are 10 checkboxes, starting from user_group-1 to user_group-10, in the javascript code you would get their value in this way:

var values=new Array();
for (x=1; x<=num_cboxes; x++)
{
   values[x]=$("#user_group-" + x).val();
}

How to send a simple email from a Windows batch file?

It works for me, by using double quotes around variables.

I am using batch script to call powershell Send-MailMessage

Batch Script:send_email.bat

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  -command 'E:\path\send_email.ps1

Pwershell Script send_email.ps1

Send-MailMessage -From "noreply@$env:computername" -To '<[email protected]>' -Subject 'Blah Blah' -SmtpServer  'smtp.domain.com'  -Attachments 'E:\path\file.log' -BODY "Blah Blah on Host: $env:computername "

In Rails, how do you render JSON using a view?

Just to update this answer for the sake of others who happen to end up on this page.

In Rails 3, you just need to create a file at views/users/show.json.erb. The @user object will be available to the view (just like it would be for html.) You don't even need to_json anymore.

To summarize, it's just

# users contoller
def show
  @user = User.find( params[:id] )
  respond_to do |format|
    format.html
    format.json
  end
end

and

/* views/users/show.json.erb */
{
    "name" : "<%= @user.name %>"
}

How to make a GUI for bash scripts?

If you have Qt/KDE installed, you can use kdialog, which pops up a Qt dialog window. You can easily specify to display a Yes/No dialog, OK/Cancel, simple text input, password input etc. You then have access to the return values from these dialogs at the shell.

.append(), prepend(), .after() and .before()

Imagine the DOM (HTML page) as a tree right. The HTML elements are the nodes of this tree.

The append() adds a new node to the child of the node you called it on.

Example:$("#mydiv").append("<p>Hello there</p>") 

creates a child node <p> to <div>

The after() adds a new node as a sibling or at the same level or child to the parent of the node you called it on.

Convert datetime object to a String of date only in Python

It is possible to convert a datetime object into a string by working directly with the components of the datetime object.

from datetime import date  

myDate = date.today()    
#print(myDate) would output 2017-05-23 because that is today
#reassign the myDate variable to myDate = myDate.month 
#then you could print(myDate.month) and you would get 5 as an integer
dateStr = str(myDate.month)+ "/" + str(myDate.day) + "/" + str(myDate.year)    
# myDate.month is equal to 5 as an integer, i use str() to change it to a 
# string I add(+)the "/" so now I have "5/" then myDate.day is 23 as
# an integer i change it to a string with str() and it is added to the "5/"   
# to get "5/23" and then I add another "/" now we have "5/23/" next is the 
# year which is 2017 as an integer, I use the function str() to change it to 
# a string and add it to the rest of the string.  Now we have "5/23/2017" as 
# a string. The final line prints the string.

print(dateStr)  

Output --> 5/23/2017

Tensorflow image reading & display

Load names with tf.train.match_filenames_once get the number of files to iterate over with tf.size open session and enjoy ;-)

import tensorflow as tf
import numpy as np
import matplotlib;
from PIL import Image

matplotlib.use('Agg')
import matplotlib.pyplot as plt


filenames = tf.train.match_filenames_once('./images/*.jpg')
count_num_files = tf.size(filenames)
filename_queue = tf.train.string_input_producer(filenames)

reader=tf.WholeFileReader()
key,value=reader.read(filename_queue)
img = tf.image.decode_jpeg(value)

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    num_files = sess.run(count_num_files)
    for i in range(num_files):
        image=img.eval()
        print(image.shape)
        Image.fromarray(np.asarray(image)).save('te.jpeg')

How to export data with Oracle SQL Developer?

In version 3, they changed "export" to "unload". It still functions more or less the same.

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

Personally I sanitize all my data with some PHP libraries before going into the database so there's no need for another XSS filter for me.

From AngularJS 1.0.8

directives.directive('ngBindHtmlUnsafe', [function() {
    return function(scope, element, attr) {
        element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
        scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
            element.html(value || '');
        });
    }
}]);

To use:

<div ng-bind-html-unsafe="group.description"></div>

To disable $sce:

app.config(['$sceProvider', function($sceProvider) {
    $sceProvider.enabled(false);
}]);

How to write file in UTF-8 format?

file_get_contents / file_put_contents will not magically convert encoding.

You have to convert the string explicitly; for example with iconv() or mb_convert_encoding().

Try this:

$data = file_get_contents($npath);
$data = mb_convert_encoding($data, 'UTF-8', 'OLD-ENCODING');
file_put_contents('tempfolder/'.$a, $data);

Or alternatively, with PHP's stream filters:

$fd = fopen($file, 'r');
stream_filter_append($fd, 'convert.iconv.UTF-8/OLD-ENCODING');
stream_copy_to_stream($fd, fopen($output, 'w'));

ImportError: No module named sklearn.cross_validation

Past : from sklearn.cross_validation (This package is deprecated in 0.18 version from 0.20 onwards it is changed to from sklearn import model_selection).

Present: from sklearn import model_selection

Example 2:

Past : from sklearn.cross_validation import cross_val_score (Version 0.18 which is deprecated)

Present : from sklearn.model_selection import cross_val_score

Text vertical alignment in WPF TextBlock

A Textblock itself can't do vertical alignment

The best way to do this that I've found is to put the textblock inside a border, so the border does the alignment for you.

<Border BorderBrush="{x:Null}" Height="50">
    <TextBlock TextWrapping="Wrap" Text="Some Text" VerticalAlignment="Center"/>
</Border>

Note: This is functionally equivalent to using a grid, it just depends how you want the controls to fit in with the rest of your layout as to which one is more suitable

npm install gives error "can't find a package.json file"

I'm not sure what you're trying to do here:

npm install alone in your home directory shouldn't do much -- it's not the root of a node app, so there's nothing to install, since there's no package.json.

There are two possible solutions:

1) cd to a node app and run npm install there. OR

2) if you're trying to install something as a command to use in the shell (You don't have a node application), npm install -g packagename. -g flag tells it to install in global namespace.

Differences in string compare methods in C#

Good explanation and practices about string comparison issues may be found in the article New Recommendations for Using Strings in Microsoft .NET 2.0 and also in Best Practices for Using Strings in the .NET Framework.


Each of mentioned method (and other) has particular purpose. The key difference between them is what sort of StringComparison Enumeration they are using by default. There are several options:

  • CurrentCulture
  • CurrentCultureIgnoreCase
  • InvariantCulture
  • InvariantCultureIgnoreCase
  • Ordinal
  • OrdinalIgnoreCase

Each of above comparison type targets different use case:

  • Ordinal
    • Case-sensitive internal identifiers
    • Case-sensitive identifiers in standards like XML and HTTP
    • Case-sensitive security-related settings
  • OrdinalIgnoreCase
    • Case-insensitive internal identifiers
    • Case-insensitive identifiers in standards like XML and HTTP
    • File paths (on Microsoft Windows)
    • Registry keys/values
    • Environment variables
    • Resource identifiers (handle names, for example)
    • Case insensitive security related settings
  • InvariantCulture or InvariantCultureIgnoreCase
    • Some persisted linguistically-relevant data
    • Display of linguistic data requiring a fixed sort order
  • CurrentCulture or CurrentCultureIgnoreCase
    • Data displayed to the user
    • Most user input

Note, that StringComparison Enumeration as well as overloads for string comparison methods, exists since .NET 2.0.


String.CompareTo Method (String)

Is in fact type safe implementation of IComparable.CompareTo Method. Default interpretation: CurrentCulture.

Usage:

The CompareTo method was designed primarily for use in sorting or alphabetizing operations

Thus

Implementing the IComparable interface will necessarily use this method

String.Compare Method

A static member of String Class which has many overloads. Default interpretation: CurrentCulture.

Whenever possible, you should call an overload of the Compare method that includes a StringComparison parameter.

String.Equals Method

Overriden from Object class and overloaded for type safety. Default interpretation: Ordinal. Notice that:

The String class's equality methods include the static Equals, the static operator ==, and the instance method Equals.


StringComparer class

There is also another way to deal with string comparisons especially aims to sorting:

You can use the StringComparer class to create a type-specific comparison to sort the elements in a generic collection. Classes such as Hashtable, Dictionary, SortedList, and SortedList use the StringComparer class for sorting purposes.

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

Copy multiple files in Python

Look at shutil in the Python docs, specifically the copytree command.

If the destination directory already exists, try:

shutil.copytree(source, destination, dirs_exist_ok=True)

Pass array to where in Codeigniter Active Record

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,

$this->db->where_in()
ex :  $this->db->where_in('id', array('1','2','3'));

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate

$this->db->or_where_in()
ex :  $this->db->where_in('id', array('1','2','3'));

There can be only one auto column

The full error message sounds:

ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key

So add primary key to the auto_increment field:

CREATE TABLE book (
   id INT AUTO_INCREMENT primary key NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Best way to do multiple constructors in PHP

as stated in the other comments, as php does not support overloading, usually the "type checking tricks" in constructor are avoided and the factory pattern is used intead

ie.

$myObj = MyClass::factory('fromInteger', $params);
$myObj = MyClass::factory('fromRow', $params);

Delaying AngularJS route change until model loaded to prevent flicker

You can use $routeProvider resolve property to delay route change until data is loaded.

angular.module('app', ['ngRoute']).
  config(['$routeProvider', function($routeProvider, EntitiesCtrlResolve, EntityCtrlResolve) {
    $routeProvider.
      when('/entities', {
        templateUrl: 'entities.html', 
        controller: 'EntitiesCtrl', 
        resolve: EntitiesCtrlResolve
      }).
      when('/entity/:entityId', {
        templateUrl: 'entity.html', 
        controller: 'EntityCtrl', 
        resolve: EntityCtrlResolve
      }).
      otherwise({redirectTo: '/entities'});
}]);

Notice that the resolve property is defined on route.

EntitiesCtrlResolve and EntityCtrlResolve is constant objects defined in same file as EntitiesCtrl and EntityCtrl controllers.

// EntitiesCtrl.js

angular.module('app').constant('EntitiesCtrlResolve', {
  Entities: function(EntitiesService) {
    return EntitiesService.getAll();
  }
});

angular.module('app').controller('EntitiesCtrl', function(Entities) {
  $scope.entities = Entities;

  // some code..
});

// EntityCtrl.js

angular.module('app').constant('EntityCtrlResolve', {
  Entity: function($route, EntitiesService) {
    return EntitiesService.getById($route.current.params.projectId);
  }
});

angular.module('app').controller('EntityCtrl', function(Entity) {
  $scope.entity = Entity;

  // some code..
});

How to get all child inputs of a div element (jQuery)

If you are using a framework like Ruby on Rails or Spring MVC you may need to use divs with square braces or other chars, that are not allowed you can use document.getElementById and this solution still works if you have multiple inputs with the same type.

var div = document.getElementById(divID);
$(div).find('input:text, input:password, input:file, select, textarea')
        .each(function() {
            $(this).val('');
        });
$(div).find('input:radio, input:checkbox').each(function() {
    $(this).removeAttr('checked');
    $(this).removeAttr('selected');
});

This examples shows how to clear the inputs, for you example you'll need to change it.

Merge or combine by rownames

Using merge and renaming your t vector as tt (see the PS of Andrie) :

merge(tt,z,by="row.names",all.x=TRUE)[,-(5:8)]

Now if you would work with dataframes instead of matrices, this would even become a whole lot easier :

z <- as.data.frame(z)
tt <- as.data.frame(tt)
merge(tt,z["symbol"],by="row.names",all.x=TRUE)

How to get file URL using Storage facade in laravel 5?

The Path to your Storage disk would be :

$storagePath  = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix()

I don't know any shorter solutions to that...

You could share the $storagePath to your Views and then just call

$storagePath."/myImg.jpg";

How to save a BufferedImage as a File

Create and save a java.awt.image.bufferedImage to file:

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );

            File f = new File("MyFile.png");
            int r = 5;
            int g = 25;
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

Notes:

  1. Creates a file called MyFile.png.
  2. Image is 500 by 500 pixels.
  3. Overwrites the existing file.
  4. The color of the image is black with a blue stripe across the top.

How to create a function in SQL Server

This one get everything between the "." characters. Please note this won't work for more complex URLs like "www.somesite.co.uk" Ideally the function would check for how many instances of the "." character and choose the substring accordingly.

CREATE FUNCTION dbo.GetURL (@URL VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
    DECLARE @Work VARCHAR(250)

    SET @Work = @URL

    SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, LEN(@work))   
    SET @Work = SUBSTRING(@work, 0, CHARINDEX('.', @work))

    --Alternate:
    --SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, CHARINDEX('.', @work) + 1)   

    RETURN @work
END

When do I use the PHP constant "PHP_EOL"?

On some system may be useful to use this constant because if, for example, you are sending an email, you can use PHP_EOL to have a cross-system script working on more systems... but even if it's useful sometime you can find this constant undefined, modern hosting with latest php engine do not have this problem but I think that a good thing is write a bit code that saves this situation:

<?php
  if (!defined('PHP_EOL')) {
    if (strtoupper(substr(PHP_OS,0,3) == 'WIN')) {
      define('PHP_EOL',"\r\n");
    } elseif (strtoupper(substr(PHP_OS,0,3) == 'MAC')) {
      define('PHP_EOL',"\r");
    } elseif (strtoupper(substr(PHP_OS,0,3) == 'DAR')) {
      define('PHP_EOL',"\n");
    } else {
      define('PHP_EOL',"\n");
    }
  }
?>

So you can use PHP_EOL without problems... obvious that PHP_EOL should be used on script that should work on more systems at once otherwise you can use \n or \r or \r\n...

Note: PHP_EOL can be

1) on Unix    LN    == \n
2) on Mac     CR    == \r
3) on Windows CR+LN == \r\n

Hope this answer help.

How to specify multiple conditions in an if statement in javascript

just add them within the main bracket of the if statement like

if ((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) {
            PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}

Logically this can be rewritten in a better way too! This has exactly the same meaning

if (Type == 2 && (PageCount == 0 || PageCount == '')) {

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

Its quite simple using the "Git Parameter Plug-in".

Add Name like "SELECT_BRANCH" ## Make sure for this variable as this would be used later. Then Parameter Type : Branch

Then reach out to SCM : Select : Git and branch specifier : ${SELECT_BRANCH}

To verify, execute below in shell in jenkins:

echo ${SELECT_BRANCH}

env.enter image description here

enter image description here

Vertically align text next to an image?

Actually, in this case it's quite simple: apply the vertical align to the image. Since it's all in one line, it's really the image you want aligned, not the text.

_x000D_
_x000D_
<!-- moved "vertical-align:middle" style from span to img -->_x000D_
<div>_x000D_
  <img style="vertical-align:middle" src="https://placehold.it/60x60">_x000D_
  <span style="">Works.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Tested in FF3.

Now you can use flexbox for this type of layout.

_x000D_
_x000D_
.box {_x000D_
   display: flex;_x000D_
   align-items:center;_x000D_
}
_x000D_
<div class="box">_x000D_
    <img src="https://placehold.it/60x60">_x000D_
    <span style="">Works.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Connecting to local SQL Server database using C#

You try with this string connection

Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database1.mdf;Database=dbname; Trusted_Connection=Yes;

How to add button inside input

I found a great code for you:

HTML

<form class="form-wrapper cf">
    <input type="text" placeholder="Search here..." required>
    <button type="submit">Search</button>
</form>

CSS

/*Clearing Floats*/
.cf:before, .cf:after {
    content:"";
    display:table;
}

.cf:after {
    clear:both;
}

.cf {
    zoom:1;
}    
/* Form wrapper styling */
.form-wrapper {
    width: 450px;
    padding: 15px;
    margin: 150px auto 50px auto;
    background: #444;
    background: rgba(0,0,0,.2);
    border-radius: 10px;
    box-shadow: 0 1px 1px rgba(0,0,0,.4) inset, 0 1px 0 rgba(255,255,255,.2);
}

/* Form text input */

.form-wrapper input {
    width: 330px;
    height: 20px;
    padding: 10px 5px;
    float: left;   
    font: bold 15px 'lucida sans', 'trebuchet MS', 'Tahoma';
    border: 0;
    background: #eee;
    border-radius: 3px 0 0 3px;     
}

.form-wrapper input:focus {
    outline: 0;
    background: #fff;
    box-shadow: 0 0 2px rgba(0,0,0,.8) inset;
}

.form-wrapper input::-webkit-input-placeholder {
   color: #999;
   font-weight: normal;
   font-style: italic;
}

.form-wrapper input:-moz-placeholder {
    color: #999;
    font-weight: normal;
    font-style: italic;
}

.form-wrapper input:-ms-input-placeholder {
    color: #999;
    font-weight: normal;
    font-style: italic;
}   

/* Form submit button */
.form-wrapper button {
    overflow: visible;
    position: relative;
    float: right;
    border: 0;
    padding: 0;
    cursor: pointer;
    height: 40px;
    width: 110px;
    font: bold 15px/40px 'lucida sans', 'trebuchet MS', 'Tahoma';
    color: #fff;
    text-transform: uppercase;
    background: #d83c3c;
    border-radius: 0 3px 3px 0;     
    text-shadow: 0 -1px 0 rgba(0, 0 ,0, .3);
}  

.form-wrapper button:hover {    
    background: #e54040;
}  

.form-wrapper button:active,
.form-wrapper button:focus {  
    background: #c42f2f;
    outline: 0;  
}

.form-wrapper button:before { /* left arrow */
    content: '';
    position: absolute;
    border-width: 8px 8px 8px 0;
    border-style: solid solid solid none;
    border-color: transparent #d83c3c transparent;
    top: 12px;
    left: -6px;
}

.form-wrapper button:hover:before {
    border-right-color: #e54040;
}

.form-wrapper button:focus:before,
.form-wrapper button:active:before {
        border-right-color: #c42f2f;
}     

.form-wrapper button::-moz-focus-inner { /* remove extra button spacing for Mozilla Firefox */
    border: 0;
    padding: 0;
}    

Demo: On fiddle Source: Speckyboy

Make XAMPP / Apache serve file outside of htdocs folder

You can set Apache to serve pages from anywhere with any restrictions but it's normally distributed in a more secure form.

Editing your apache files (http.conf is one of the more common names) will allow you to set any folder so it appears in your webroot.

EDIT:

alias myapp c:\myapp\

I've edited my answer to include the format for creating an alias in the http.conf file which is sort of like a shortcut in windows or a symlink under un*x where Apache 'pretends' a folder is in the webroot. This is probably going to be more useful to you in the long term.

How to save CSS changes of Styles panel of Chrome Developer Tools?

Tincr Chrome extension is easier to install (no need to run node server) AND also comes with LiveReload like functionality out the box! Talk about bi-directional editing! :)

Tin.cr Website

Chrome Web Store Link

Andy's Blog Article

git diff file against its last change

If you are fine using a graphical tool this works very well:

gitk <file>

gitk now shows all commits where the file has been updated. Marking a commit will show you the diff against the previous commit in the list. This also works for directories, but then you also get to select the file to diff for the selected commit. Super useful!

What does getActivity() mean?

Two likely definitions:

Open new Terminal Tab from command line (Mac OS X)

Here's how it's done by bash_it:

function tab() {
  osascript 2>/dev/null <<EOF
    tell application "System Events"
      tell process "Terminal" to keystroke "t" using command down
    end
    tell application "Terminal"
      activate
      do script with command "cd \"$PWD\"; $*" in window 1
    end tell
EOF
}

After adding this to your .bash_profile, you'd use the tab command to open the current working directory in a new tab.

See: https://github.com/revans/bash-it/blob/master/plugins/available/osx.plugin.bash#L3

How can I style even and odd elements?

Below is the example of even and odd css color apply

<html>
<head>
<style> 
p:nth-child(even) {
    background: red;
}
p:nth-child(odd) {
    background: green;
}
</style>
</head>
<body>

<p>The first Odd.</p>
<p>The second Even.</p>
<p>The third Odd.</p>
<p>The fourth Even.</p>


</body>
</html>

iOS: UIButton resize according to text length

If your button was made with Interface Builder, and you're changing the title in code, you can do this:

[self.button setTitle:@"Button Title" forState:UIControlStateNormal];
[self.button sizeToFit];

m2e error in MavenArchiver.getManifest()

I had the same problem with a spring boot project. the solution was to downgrade the jar maven-jar-plugin from 3.2 to 2.6 . i had just to add this to the project pom:

<properties>        
    <maven-jar-plugin.version>2.6</maven-jar-plugin.version>
</properties>

Calling constructors in c++ without new

The compiler may well optimize the second form into the first form, but it doesn't have to.

#include <iostream>

class A
{
    public:
        A() { std::cerr << "Empty constructor" << std::endl; }
        A(const A&) { std::cerr << "Copy constructor" << std::endl; }
        A(const char* str) { std::cerr << "char constructor: " << str << std::endl; }
        ~A() { std::cerr << "destructor" << std::endl; }
};

void direct()
{
    std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
    A a(__FUNCTION__);
    static_cast<void>(a); // avoid warnings about unused variables
}

void assignment()
{
    std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
    A a = A(__FUNCTION__);
    static_cast<void>(a); // avoid warnings about unused variables
}

void prove_copy_constructor_is_called()
{
    std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
    A a(__FUNCTION__);
    A b = a;
    static_cast<void>(b); // avoid warnings about unused variables
}

int main()
{
    direct();
    assignment();
    prove_copy_constructor_is_called();
    return 0;
}

Output from gcc 4.4:

TEST: direct
char constructor: direct
destructor

TEST: assignment
char constructor: assignment
destructor

TEST: prove_copy_constructor_is_called
char constructor: prove_copy_constructor_is_called
Copy constructor
destructor
destructor

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

1.open your xampp dir ( c:/xampp )

2.to phpMyadmin dir [C:\xampp\phpMyAdmin]

3.open [ config.inc.php ] file with any text editor

$cfg['Servers'][$i]['auth_type'] = 'config'; //replace 'config' to ‘cookie’
$cfg['Servers'][$i]['AllowNoPassword'] = true; //change ‘true’ to ‘false’.

last : save the file .

here is a video link in case you want to see it in Action [ click Here ]

Define a global variable in a JavaScript function

If you read the comments there's a nice discussion around this particular naming convention.

It seems that since my answer has been posted the naming convention has gotten more formal. People who teach, write books, etc. speak about var declaration, and function declaration.

Here is the additional Wikipedia post that supports my point: Declarations and definitions ...and to answer the main question. Declare variable before your function. This will work and it will comply to the good practice of declaring your variables at the top of the scope :)

How to define constants in Visual C# like #define in C?

static class Constants
{
    public const int MIN_LENGTH = 5;
    public const int MIN_WIDTH  = 5; 
    public const int MIN_HEIGHT = 6;
}

// elsewhere
public CBox()
{
    length = Constants.MIN_LENGTH; 
    width  = Constants.MIN_WIDTH; 
    height = Constants.MIN_HEIGHT;  
}

Can I call methods in constructor in Java?

Can I put my method readConfig() into constructor?

Invoking a not overridable method in a constructor is an acceptable approach.
While if the method is only used by the constructor you may wonder if extracting it into a method (even private) is really required.

If you choose to extract some logic done by the constructor into a method, as for any method you have to choose a access modifier that fits to the method requirement but in this specific case it matters further as protecting the method against the overriding of the method has to be done at risk of making the super class constructor inconsistent.

So it should be private if it is used only by the constructor(s) (and instance methods) of the class.
Otherwise it should be both package-private and final if the method is reused inside the package or in the subclasses.

which would give me benefit of one time calling or is there another mechanism to do that ?

You don't have any benefit or drawback to use this way.
I don't encourage to perform much logic in constructors but in some cases it may make sense to init multiple things in a constructor.
For example the copy constructor may perform a lot of things.
Multiple JDK classes illustrate that.
Take for example the HashMap copy constructor that constructs a new HashMap with the same mappings as the specified Map parameter :

public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        if (table == null) { // pre-size
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        else if (s > threshold)
            resize();
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
            K key = e.getKey();
            V value = e.getValue();
            putVal(hash(key), key, value, false, evict);
        }
    }
}

Extracting the logic of the map populating in putMapEntries() is a good thing because it allows :

  • reusing the method in other contexts. For example clone() and putAll() use it too
  • (minor but interesting) giving a meaningful name that conveys the performed logic

jQuery Datepicker close datepicker after selected date

actually you don't need to replace this all....

there are 2 ways to do this. One is to use autoclose property, the other (alternativ) way is to use the on change property thats fired by the input when selecting a Date.

HTML

<div class="container">
    <div class="hero-unit">
        <input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">
    </div>
    <div class="hero-unit">
        <input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">
    </div>
</div>

jQuery

$(document).ready(function () {
    $('#example1').datepicker({
        format: "dd/mm/yyyy",
        autoclose: true
    });

    //Alternativ way
    $('#example2').datepicker({
      format: "dd/mm/yyyy"
    }).on('change', function(){
        $('.datepicker').hide();
    });

});

this is all you have to do :)

HERE IS A FIDDLE to see whats happening.

Fiddleupdate on 13 of July 2016: CDN wasnt present anymore

According to your EDIT:

$('#example1').datepicker().on('changeDate', function (ev) {
    $('#example1').Close();
});

Here you take the Input (that has no Close-Function) and create a Datepicker-Element. If the element changes you want to close it but you still try to close the Input (That has no close-function).

Binding a mouseup event to the document state may not be the best idea because you will fire all containing scripts on each click!

Thats it :)

EDIT: August 2017 (Added a StackOverFlowFiddle aka Snippet. Same as in Top of Post)

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    $('#example1').datepicker({_x000D_
        format: "dd/mm/yyyy",_x000D_
        autoclose: true_x000D_
    });_x000D_
_x000D_
    //Alternativ way_x000D_
    $('#example2').datepicker({_x000D_
      format: "dd/mm/yyyy"_x000D_
    }).on('change', function(){_x000D_
        $('.datepicker').hide();_x000D_
    });_x000D_
});
_x000D_
.hero-unit{_x000D_
  float: left;_x000D_
  width: 210px;_x000D_
  margin-right: 25px;_x000D_
}_x000D_
.hero-unit input{_x000D_
  width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>_x000D_
<div class="container">_x000D_
    <div class="hero-unit">_x000D_
        <input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">_x000D_
    </div>_x000D_
    <div class="hero-unit">_x000D_
        <input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

EDIT: December 2018 Obviously Bootstrap-Datepicker doesnt work with jQuery 3.x see this to fix

Why can't I push to this bare repository?

I use SourceTree git client, and I see that their initial commit/push command is:

git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master

How do I cancel a build that is in progress in Visual Studio?

For users of Lenovo Thinkpad T470s like me, you can simulate the break key by hitting Ctrl+Fn+P, which cancels the build.

Invalid syntax when using "print"?

That is because in Python 3, they have replaced the print statement with the print function.

The syntax is now more or less the same as before, but it requires parens:

From the "what's new in python 3" docs:

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

How to see an HTML page on Github as a normal rendered HTML page to see preview in browser, without downloading?

I have found another way:

  1. Click on the "Raw" button if you haven't already
  2. Ctrl+A, Ctrl+C
  3. Open "Developer Tools" with F12
  4. In the "Inspector" right-click on the tag and choose "Edit HTML"
  5. Ctrl+A, Ctrl+V
  6. Ctr+Return

Tested on Firefox but it should work in other browsers too

is there something like isset of php in javascript/jQuery?

http://phpjs.org/functions/isset:454

phpjs project is a trusted source. Lots of js equivalent php functions available there. I have been using since a long time and found no issues so far.

How to store and retrieve a dictionary with redis

You can do it by hmset (multiple keys can be set using hmset).

hmset("RedisKey", dictionaryToSet)

import redis
conn = redis.Redis('localhost')

user = {"Name":"Pradeep", "Company":"SCTL", "Address":"Mumbai", "Location":"RCP"}

conn.hmset("pythonDict", user)

conn.hgetall("pythonDict")

{'Company': 'SCTL', 'Address': 'Mumbai', 'Location': 'RCP', 'Name': 'Pradeep'}

Python JSON dump / append to .txt with each variable on new line

Your question is a little unclear. If you're generating hostDict in a loop:

with open('data.txt', 'a') as outfile:
    for hostDict in ....:
        json.dump(hostDict, outfile)
        outfile.write('\n')

If you mean you want each variable within hostDict to be on a new line:

with open('data.txt', 'a') as outfile:
    json.dump(hostDict, outfile, indent=2)

When the indent keyword argument is set it automatically adds newlines.

What's the difference between JavaScript and Java?

They have nothing to do with each other.

Java is statically typed, compiles, runs on its own VM.

Javascript is dynamically typed, interpreted, and runs in a browser. It also has first-class functions and anonymous functions, which Java does not. It has direct access to web-page elements, which makes it useful for doing client-side processing.

They are also somewhat similar in syntax, but that's about it.

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

Here is a list of this you should look into when dealing with PHPMailer:

  1. Enable openSSL by un-commenting extension=php_openssl.dll in your PHP.ini
  2. Use $mail->SMTPSecure = 'tls'; and $mail->Port = 587;
  3. Enable debugging for if you are going wrong somewhere else like incorrect username and password etc.

Foreach loop, determine which is the last iteration of the loop

You can make an extension method specially dedicated to this:

public static class EnumerableExtensions {
    public static bool IsLast<T>(this List<T> items, T item)
        {
            if (items.Count == 0)
                return false;
            T last = items[items.Count - 1];
            return item.Equals(last);
        }
    }

and you can use it like this:

foreach (Item result in Model.Results)
{
    if(Model.Results.IsLast(result))
    {
        //do something in the code
    }
}

How to submit form on change of dropdown list?

other than using this.form.submit() you also submiting by id or name. example i have form like this : <form action="" name="PostName" id="IdName">

  1. By Name : <select onchange="PostName.submit()">

  2. By Id : <select onchange="IdName.submit()">

How can I style a PHP echo text?

You cannot style a variable such as $ip['countryName']

You can only style elements like p,div, etc, or classes and ids.

If you want to style $ip['countryName'] there are several ways.

You can echo it within an element:

echo '<p id="style">'.$ip['countryName'].'</p>';
echo '<span id="style">'.$ip['countryName'].'</span>';
echo '<div id="style">'.$ip['countryName'].'</div>';

If you want to style both the variables the same style, then set a class like:

echo '<p class="style">'.$ip['cityName'].'</p>';
echo '<p class="style">'.$ip['countryName'].'</p>';

You could also embed the variables within your actual html rather than echoing them out within the code.

$city = $ip['cityName'];  
$country = $ip['countryName'];
?>
<div class="style"><?php echo $city ?></div>
<div class="style"><?php echo $country?></div>

Java Project: Failed to load ApplicationContext

I had the same problem, and I was using the following plugin for tests:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.9</version>
    <configuration>
        <useFile>true</useFile>
        <includes>
            <include>**/*Tests.java</include>
            <include>**/*Test.java</include>
        </includes>
        <excludes>
            <exclude>**/Abstract*.java</exclude>
        </excludes>
        <junitArtifactName>junit:junit</junitArtifactName>
        <parallel>methods</parallel>
        <threadCount>10</threadCount>
    </configuration>
</plugin>

The test were running fine in the IDE (eclipse sts), but failed when using command mvn test.

After a lot of trial and error, I figured the solution was to remove parallel testing, the following two lines from the plugin configuration above:

    <parallel>methods</parallel>
    <threadCount>10</threadCount>

Hope that this helps someone out!

Can Selenium interact with an existing browser session?

I got a solution in python, I modified the webdriver class bassed on PersistenBrowser class that I found.

https://github.com/axelPalmerin/personal/commit/fabddb38a39f378aa113b0cb8d33391d5f91dca5

replace the webdriver module /usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py

Ej. to use:

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

runDriver = sys.argv[1]
sessionId = sys.argv[2]

def setBrowser():
    if eval(runDriver):
        webdriver = w.Remote(command_executor='http://localhost:4444/wd/hub',
                     desired_capabilities=DesiredCapabilities.CHROME,
                     )
    else:
        webdriver = w.Remote(command_executor='http://localhost:4444/wd/hub',
                             desired_capabilities=DesiredCapabilities.CHROME,
                             session_id=sessionId)

    url = webdriver.command_executor._url
    session_id = webdriver.session_id
    print url
    print session_id
    return webdriver

How to delete a folder in C++?

Delete folder (sub_folders and files) in Windows (VisualC++) not using Shell APIs, this is the best working sample:

#include <string>
#include <iostream>

#include <windows.h>
#include <conio.h>


int DeleteDirectory(const std::string &refcstrRootDirectory,
                    bool              bDeleteSubdirectories = true)
{
  bool            bSubdirectory = false;       // Flag, indicating whether
                                               // subdirectories have been found
  HANDLE          hFile;                       // Handle to directory
  std::string     strFilePath;                 // Filepath
  std::string     strPattern;                  // Pattern
  WIN32_FIND_DATA FileInformation;             // File information


  strPattern = refcstrRootDirectory + "\\*.*";
  hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);
  if(hFile != INVALID_HANDLE_VALUE)
  {
    do
    {
      if(FileInformation.cFileName[0] != '.')
      {
        strFilePath.erase();
        strFilePath = refcstrRootDirectory + "\\" + FileInformation.cFileName;

        if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
          if(bDeleteSubdirectories)
          {
            // Delete subdirectory
            int iRC = DeleteDirectory(strFilePath, bDeleteSubdirectories);
            if(iRC)
              return iRC;
          }
          else
            bSubdirectory = true;
        }
        else
        {
          // Set file attributes
          if(::SetFileAttributes(strFilePath.c_str(),
                                 FILE_ATTRIBUTE_NORMAL) == FALSE)
            return ::GetLastError();

          // Delete file
          if(::DeleteFile(strFilePath.c_str()) == FALSE)
            return ::GetLastError();
        }
      }
    } while(::FindNextFile(hFile, &FileInformation) == TRUE);

    // Close handle
    ::FindClose(hFile);

    DWORD dwError = ::GetLastError();
    if(dwError != ERROR_NO_MORE_FILES)
      return dwError;
    else
    {
      if(!bSubdirectory)
      {
        // Set directory attributes
        if(::SetFileAttributes(refcstrRootDirectory.c_str(),
                               FILE_ATTRIBUTE_NORMAL) == FALSE)
          return ::GetLastError();

        // Delete directory
        if(::RemoveDirectory(refcstrRootDirectory.c_str()) == FALSE)
          return ::GetLastError();
      }
    }
  }

  return 0;
}


int main()
{
  int         iRC                  = 0;
  std::string strDirectoryToDelete = "c:\\mydir";


  // Delete 'c:\mydir' without deleting the subdirectories
  iRC = DeleteDirectory(strDirectoryToDelete, false);
  if(iRC)
  {
    std::cout << "Error " << iRC << std::endl;
    return -1;
  }

  // Delete 'c:\mydir' and its subdirectories
  iRC = DeleteDirectory(strDirectoryToDelete);
  if(iRC)
  {
    std::cout << "Error " << iRC << std::endl;
    return -1;
  }

  // Wait for keystroke
  _getch();

  return 0;
}

Source: http://www.codeguru.com/forum/showthread.php?t=239271

How to get city name from latitude and longitude coordinates in Google Maps?

I´m in Brazil. Because of the regional details sometimes the city cames in differents ways. I think its the same in India and other countries. So, to prevent errors I make this verification:

private fun getAddress(latLng: LatLng): String {
    // 1
    val geocoder = Geocoder(this)
    val addresses: List<Address>?
    var city = "no"

    try {

        addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)

        if (null != addresses && !addresses.isEmpty()) { //prevent from error
             //sometimes the city comes in locality, sometimes in subAdminArea.
            if (addresses[0].locality == null) {

                city = addresses[0].subAdminArea
            } else {
                city = addresses[0].locality
            }

            }
    } catch (e: IOException) {
        Log.e("MapsActivity", e.localizedMessage)
    }

    return city
    }

You can also check if city returns "no". If so, wasn´t possible to get the user location. Hope it helps.

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

HOW TO FORCE UNLOCK for locked tables in MySQL:

Breaking locks like this may cause atomicity in the database to not be enforced on the sql statements that caused the lock.

This is hackish, and the proper solution is to fix your application that caused the locks. However, when dollars are on the line, a swift kick will get things moving again.

1) Enter MySQL

mysql -u your_user -p

2) Let's see the list of locked tables

mysql> show open tables where in_use>0;

3) Let's see the list of the current processes, one of them is locking your table(s)

mysql> show processlist;

4) Kill one of these processes

mysql> kill <put_process_id_here>;

Absolute vs relative URLs

Should I use absolute or relative URLs?

If by absolute URLs you mean URLs including scheme (e.g. http / https) and the hostname (e.g. yourdomain.com) don't ever do that (for local resources) because it will be terrible to maintain and debug.

Let's say you have used absolute URL everywhere in your code like <img src="http://yourdomain.com/images/example.png">. Now what will happen when you are going to:

  • switch to another scheme (e.g. http -> https)
  • switch domain names (test.yourdomain.com -> yourdomain.com)

In the first example what will happen is that you will get warnings about unsafe content being requested on the page. Because all your URLs are hardcoded to use http(://yourdomain.com/images/example.png). And when running your pages over https the browser expects all resources to be loaded over https to prevent leaking of information.

In the second example when putting your site live from the test environment it would mean all resources are still pointing to your test domain instead of your live domain.

So to answer your question about whether to use absolute or relative URLs: always use relative URLs (for local resources).

What are the differences between the different URLs?

First lets have a look at the different types of urls that we can use:

  • http://yourdomain.com/images/example.png
  • //yourdomain.com/images/example.png
  • /images/example.png
  • images/example.png

What resources do these URLs try to access on the server?

In the examples below I assume the website is running from the following location on the server /var/www/mywebsite.

http://yourdomain.com/images/example.png

The above (absolute) URL tries to access the resource /var/www/website/images/example.png. This type of URL is something you would always want to avoid for requesting resources from your own website for reason outlined above. However it does have its place. For example if you have a website http://yourdomain.com and you want to request a resource from an external domain over https you should use this. E.g. https://externalsite.com/path/to/image.png.

//yourdomain.com/images/example.png

This URL is relative based on the current scheme used and should almost always be used when including external resources (images, javascripts etc).

What this type of URL does is use the current scheme of the page it is on. This means that you are on the page http://yourdomain.com and on that page is an image tag <img src="//yourdomain.com/images/example.png"> the URL of the image would resolve in http://yourdomain.com/images/example.png.
When you would have been on the page http**s**://yourdomain.com and on that page is an image tag <img src="//yourdomain.com/images/example.png"> the URL of the image would resolve in https://yourdomain.com/images/example.png.

This prevent loading resources over https when it is not needed and automatically makes sure the resource is requested over https when it is needed.

The above URL resolves in the same manner on the server side as the previous URL:

The above (absolute) URL tries to access the resource /var/www/website/images/example.png.

/images/example.png

For local resources this is the prefered way of referencing them. This is a relative URL based on the document root (/var/www/mywebsite) of your website. This means when you have <img src="/images/example.png"> it will always resolve to /var/www/mywebsite/images/example.png.

If at some point you decide to switch domain it will still work because it is relative.

images/example.png

This is also a relative URL although a bit different than the previous one. This URL is relative to the current path. What this means is that it will resolve to different paths depending on where you are in the site.

For example when you are on the page http://yourdomain.com and you use <img src="images/example.png"> it would resolve on the server to /var/www/mywebsite/images/example.png as expected, however when your are on the page http://yourdomain.com/some/path and you use the exact same image tag it suddenly will resolve to /var/www/mywebsite/some/path/images/example.png.

When to use what?

When requesting external resources you most likely want to use an URL relative to the scheme (unless you want to force a different scheme) and when dealing with local resources you want to use relative URLs based on the document root.

An example document:

<!DOCTYPE html>
<html>
    <head>
        <title>Example</title>
        <link href='//fonts.googleapis.com/css?family=Lato:300italic,700italic,300,700' rel='stylesheet' type='text/css'>
        <link href="/style/style.css" rel="stylesheet" type="text/css" media="screen"></style>
    </head>
    <body>
        <img src="/images/some/localimage.png" alt="">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
    </body>
</html>

Some (kinda) duplicates

Check cell for a specific letter or set of letters

Some options without REGEXMATCH, since you might want to be case insensitive and not want say blast or ablative to trigger a YES. Using comma as the delimiter, as in the OP, and for the moment ignoring the IF condition:

First very similar to @user1598086's answer:

=FIND("bla",A1)

Is case sensitive but returns #VALUE! rather than NO and a number rather than YES (both of which can however be changed to NO/YES respectively).

=SEARCH("bla",A1)  

Case insensitive, so treats Black and black equally. Returns as above.

The former (for the latter equivalent) to indicate whether bla present after the first three characters in A1:

=FIND("bla",A1,4)  

Returns a number for blazer, black but #VALUE! for blazer, blue.

To find Bla only when a complete word on its own (ie between spaces - not at the start or end of a 'sentence'):

=SEARCH(" Bla ",A1) 

Since the return in all cases above is either a number ("found", so YES preferred) or #VALUE! we can use ISERROR to test for #VALUE! within an IF formula, for instance taking the first example above:

 =if(iserror(FIND("bla",A1)),"NO","YES")  

Longer than the regexmatch but the components are easily adjustable.

jQuery class within class selector

is just going to look for a div with class="outer inner", is that correct?

No, '.outer .inner' will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner' (no space) would give the results you're thinking of.

'.outer > .inner' will look for immediate children of an element with the .outer class for elements with the .inner class.

Both '.outer .inner' and '.outer > .inner' should work for your example, although the selectors are fundamentally different and you should be wary of this.

':app:lintVitalRelease' error when generating signed apk

I have faced same issue when creating signed apk from android studio. I just change little bit change on build.gradle file inside android {}

lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

Receiving login prompt using integrated windows authentication

Can be browser related. If you are using IE, you can go to Advanced Settings and check you the "Enable Windows Integrated Authentication" checkbox is checked.

Find and replace strings in vim on multiple lines

In vim if you are confused which all lines will be affected, Use below

 :%s/foo/bar/gc  

Change each 'foo' to 'bar', but ask for confirmation first. Press 'y' for yes and 'n' for no. Dont forget to save after that

:wq

How to debug PDO database queries?

Sure you can debug using this mode {{ PDO::ATTR_ERRMODE }} Just add new line before your query then you will show the debug lines.

$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$db->query('SELECT *******');  

How to compress an image via Javascript in the browser?

In short:

  • Read the files using the HTML5 FileReader API with .readAsArrayBuffer
  • Create a Blob with the file data and get its url with window.URL.createObjectURL(blob)
  • Create new Image element and set it's src to the file blob url
  • Send the image to the canvas. The canvas size is set to desired output size
  • Get the scaled-down data back from canvas via canvas.toDataURL("image/jpeg",0.7) (set your own output format and quality)
  • Attach new hidden inputs to the original form and transfer the dataURI images basically as normal text
  • On backend, read the dataURI, decode from Base64, and save it

Source: code.

How to check if an email address is real or valid using PHP

You can't verify (with enough accuracy to rely on) if an email actually exists using just a single PHP method. You can send an email to that account, but even that alone won't verify the account exists (see below). You can, at least, verify it's at least formatted like one

if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
    //Email is valid
}

You can add another check if you want. Parse the domain out and then run checkdnsrr

if(checkdnsrr($domain)) {
     // Domain at least has an MX record, necessary to receive email
}

Many people get to this point and are still unconvinced there's not some hidden method out there. Here are some notes for you to consider if you're bound and determined to validate email:

  1. Spammers also know the "connection trick" (where you start to send an email and rely on the server to bounce back at that point). One of the other answers links to this library which has this caveat

    Some mail servers will silently reject the test message, to prevent spammers from checking against their users' emails and filter the valid emails, so this function might not work properly with all mail servers.

    In other words, if there's an invalid address you might not get an invalid address response. In fact, virtually all mail servers come with an option to accept all incoming mail (here's how to do it with Postfix). The answer linking to the validation library neglects to mention that caveat.

  2. Spam blacklists. They blacklist by IP address and if your server is constantly doing verification connections you run the risk of winding up on Spamhaus or another block list. If you get blacklisted, what good does it do you to validate the email address?

  3. If it's really that important to verify an email address, the accepted way is to force the user to respond to an email. Send them a full email with a link they have to click to be verified. It's not spammy, and you're guaranteed that any responses have a valid address.

How to edit a JavaScript alert box title?

No, it is not possible. You can use a custom javascript alert box.

Found a nice one using jQuery

jQuery Alert Dialogs (Alert, Confirm, & Prompt Replacements)

How to convert Set to Array?

via https://speakerdeck.com/anguscroll/es6-uncensored by Angus Croll

It turns out, we can use spread operator:

var myArr = [...mySet];

Or, alternatively, use Array.from:

var myArr = Array.from(mySet);

Can we instantiate an abstract class directly?

No, you can never instantiate an abstract class. That's the purpose of an abstract class. The getProvider method you are referring to returns a specific implementation of the abstract class. This is the abstract factory pattern.

How to scan a folder in Java?

import java.io.File;
public class Test {
    public static void main( String [] args ) {
        File actual = new File(".");
        for( File f : actual.listFiles()){
            System.out.println( f.getName() );
        }
    }
}

It displays indistinctly files and folders.

See the methods in File class to order them or avoid directory print etc.

http://java.sun.com/javase/6/docs/api/java/io/File.html

How can I stop the browser back button using JavaScript?

In my case this was a shopping order. So I disabled the button. When the user clicked back, the button was disabled still. When they clicked back one more time, and then clicked a page button to go forward. I knew their order was submitted and skipped to another page.

In the case when the page actually refreshed which would make the button (theoretically), available; I was then able to react in the page load that the order was already submitted and redirected then too.

How to easily import multiple sql files into a MySQL database?

I know it's been a little over two years... but I was looking for a way to do this, and wasn't overly happy with the solution posted (it works fine, but I wanted a little more information as the import happens). When combining all the SQL files in to one, you don't get any sort of progress updates.

So I kept digging for an answer and thought this might be a good place to post what I found for future people looking for the same answer. Here's a command line in Windows that will import multiple SQL files from a folder. You run this from the command line while in the directory where mysql.exe is located.

for /f %f in ('dir /b <dir>\<mask>') do mysql --user=<user> --password=<password> <dbname> < <dir>\%f

With some assumed values (as an example):

for /f %f in ('dir /b c:\sqlbackup\*.sql') do mysql --user=mylogin --password=mypass mydb < c:\sqlbackup\%f

If you had two sets of SQL backups in the folder, you could change the *.sql to something more specific (like mydb_*.sql).

What does !important mean in CSS?

It means, essentially, what it says; that 'this is important, ignore subsequent rules, and any usual specificity issues, apply this rule!'

In normal use a rule defined in an external stylesheet is overruled by a style defined in the head of the document, which, in turn, is overruled by an in-line style within the element itself (assuming equal specificity of the selectors). Defining a rule with the !important 'attribute' (?) discards the normal concerns as regards the 'later' rule overriding the 'earlier' ones.

Also, ordinarily, a more specific rule will override a less-specific rule. So:

a {
    /* css */
}

Is normally overruled by:

body div #elementID ul li a {
    /* css */
}

As the latter selector is more specific (and it doesn't, normally, matter where the more-specific selector is found (in the head or the external stylesheet) it will still override the less-specific selector (in-line style attributes will always override the 'more-', or the 'less-', specific selector as it's always more specific.

If, however, you add !important to the less-specific selector's CSS declaration, it will have priority.

Using !important has its purposes (though I struggle to think of them), but it's much like using a nuclear explosion to stop the foxes killing your chickens; yes, the foxes will be killed, but so will the chickens. And the neighbourhood.

It also makes debugging your CSS a nightmare (from personal, empirical, experience).

Changing the child element's CSS when the parent is hovered

If you're using Twitter Bootstrap styling and base JS for a drop down menu:

.child{ display:none; }
.parent:hover .child{ display:block; }

This is the missing piece to create sticky-dropdowns (that aren't annoying)

  • The behavior is to:
    1. Stay open when clicked, close when clicking again anywhere else on the page
    2. Close automatically when the mouse scrolls out of the menu's elements.

Retrieving the last record in each group - MySQL

Here is another way to get the last related record using GROUP_CONCAT with order by and SUBSTRING_INDEX to pick one of the record from the list

SELECT 
  `Id`,
  `Name`,
  SUBSTRING_INDEX(
    GROUP_CONCAT(
      `Other_Columns` 
      ORDER BY `Id` DESC 
      SEPARATOR '||'
    ),
    '||',
    1
  ) Other_Columns 
FROM
  messages 
GROUP BY `Name` 

Above query will group the all the Other_Columns that are in same Name group and using ORDER BY id DESC will join all the Other_Columns in a specific group in descending order with the provided separator in my case i have used || ,using SUBSTRING_INDEX over this list will pick the first one

Fiddle Demo

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

Here is what I do on my projects in jupyter notebook,

import sys
sys.path.append("../") # go to parent dir
from customFunctions import *

Then, to affect changes in customFunctions.py,

%load_ext autoreload
%autoreload 2

How to commit and rollback transaction in sql server?

Avoid direct references to '@@ERROR'. It's a flighty little thing that can be lost.

Declare @ErrorCode int;
... perform stuff ...
Set @ErrorCode = @@ERROR;
... other stuff ...
if @ErrorCode ...... 

How to alert using jQuery

Don't do this, but this is how you would do it:

$(".overdue").each(function() { 
    alert("Your book is overdue"); 
});

The reason I say "don't do it" is because nothing is more annoying to users, in my opinion, than repeated pop-ups that cannot be stopped. Instead, just use the length property and let them know that "You have X books overdue".

How to rename a class and its corresponding file in Eclipse?

Right click on the class->select Refactor->Rename

Does Spring @Transactional attribute work on a private method?

Yes, it is possible to use @Transactional on private methods, but as others have mentioned this won't work out of the box. You need to use AspectJ. It took me some time to figure out how to get it working. I will share my results.

I chose to use compile-time weaving instead of load-time weaving because I think it's an overall better option. Also, I'm using Java 8 so you may need to adjust some parameters.

First, add the dependency for aspectjrt.

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.8.8</version>
</dependency>

Then add the AspectJ plugin to do the actual bytecode weaving in Maven (this may not be a minimal example).

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <version>1.8</version>
    <configuration>
        <complianceLevel>1.8</complianceLevel>
        <source>1.8</source>
        <target>1.8</target>
        <aspectLibraries>
            <aspectLibrary>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
            </aspectLibrary>
        </aspectLibraries>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>compile</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Finally add this to your config class

@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)

Now you should be able to use @Transactional on private methods.

One caveat to this approach: You will need to configure your IDE to be aware of AspectJ otherwise if you run the app via Eclipse for example it may not work. Make sure you test against a direct Maven build as a sanity check.

Remove Object from Array using JavaScript

With ES 6 arrow function

let someArray = [
                 {name:"Kristian", lines:"2,5,10"},
                 {name:"John", lines:"1,19,26,96"}
                ];
let arrayToRemove={name:"Kristian", lines:"2,5,10"};
someArray=someArray.filter((e)=>e.name !=arrayToRemove.name && e.lines!= arrayToRemove.lines)

How do I read input character-by-character in Java?

Wrap your input stream in a buffered reader then use the read method to read one byte at a time until the end of stream.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Reader {

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

        BufferedReader buffer = new BufferedReader(
                 new InputStreamReader(System.in));
        int c = 0;
        while((c = buffer.read()) != -1) {
            char character = (char) c;          
            System.out.println(character);          
        }       
    }   
}

mvn command is not recognized as an internal or external command

I had the same problem. But just restarting my computer after setting up the Maven path resolved the issue.

Variable Name: M2_Home Variable Value:C:\Apache\apache-maven-3.3.9

Variable Name: Path Variable Value:C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;%JAVA_HOME%\bin\;%M2_HOME%\bin\

Use tab to indent in textarea

The above answers all wipe undo history. For anyone looking for a solution that doesn't do that, I spent the last hour coding up the following for Chrome:

jQuery.fn.enableTabs = function(TAB_TEXT){
    // options
    if(!TAB_TEXT)TAB_TEXT = '\t';
    // text input event for character insertion
    function insertText(el, text){
        var te = document.createEvent('TextEvent');
        te.initTextEvent('textInput', true, true, null, text, 9, "en-US");
        el.dispatchEvent(te);
    }
    // catch tab and filter selection
    jQuery(this).keydown(function(e){
        if((e.which || e.keyCode)!=9)return true;
        e.preventDefault();
        var contents = this.value,
            sel_start = this.selectionStart,
            sel_end = this.selectionEnd,
            sel_contents_before = contents.substring(0, sel_start),
            first_line_start_search = sel_contents_before.lastIndexOf('\n'),
            first_line_start = first_line_start_search==-1 ? 0 : first_line_start_search+1,
            tab_sel_contents = contents.substring(first_line_start, sel_end),
            tab_sel_contents_find = (e.shiftKey?new RegExp('\n'+TAB_TEXT, 'g'):new RegExp('\n', 'g')),
            tab_sel_contents_replace = (e.shiftKey?'\n':'\n'+TAB_TEXT);
            tab_sel_contents_replaced = (('\n'+tab_sel_contents)
                .replace(tab_sel_contents_find, tab_sel_contents_replace))
                .substring(1),
            sel_end_new = first_line_start+tab_sel_contents_replaced.length;
        this.setSelectionRange(first_line_start, sel_end);
        insertText(this, tab_sel_contents_replaced);
        this.setSelectionRange(first_line_start, sel_end_new);
    });
};

In short, tabs are inserted at the beginning of the selected lines.

JSFiddle: http://jsfiddle.net/iausallc/5Lnabspr/11/

Gist: https://gist.github.com/iautomation/e53647be326cb7d7112d

Example usage: $('textarea').enableTabs('\t')

Cons: Only works on Chrome as is.

How do you use https / SSL on localhost?

If you have IIS Express (with Visual Studio):

To enable the SSL within IIS Express, you have to just set “SSL Enabled = true” in the project properties window.

See the steps and pictures at this code project.

IIS Express will generate a certificate for you (you'll be prompted for it, etc.). Note that depending on configuration the site may still automatically start with the URL rather than the SSL URL. You can see the SSL URL - note the port number and replace it in your browser address bar, you should be able to get in and test.

From there you can right click on your project, click property pages, then start options and assign the start URL - put the new https with the new port (usually 44301 - notice the similarity to port 443) and your project will start correctly from then on.

enter image description here

How can I remove a trailing newline?

If your question is to clean up all the line breaks in a multiple line str object (oldstr), you can split it into a list according to the delimiter '\n' and then join this list into a new str(newstr).

newstr = "".join(oldstr.split('\n'))

error C2065: 'cout' : undeclared identifier

I came here because I had the same problem, but when I did #include "stdafx.h" it said it did not find that file.
What did the trick for me was: #include <algorithm>.
I use Microsoft Visual Studio 2008.
These are the things that you can use then, incl. 'count': Link

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

I am running eclipse with cygwin in Windows.

Project > Properties > C/C++ General > Preprocessor Includes... > Providers and selecting "CDT GCC Built-in Compiler settings Cygwin" in providers list solved problem for me.

XmlSerializer: remove unnecessary xsi and xsd namespaces

//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

//Add an empty namespace and empty value
ns.Add("", "");

//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);

//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns)

How to use mongoimport to import csv

1]We can save xsl as .csv file
2] Got to MongoDB bin pathon cmd - > cd D:\Arkay\soft\MongoDB\bin
3] Run below command
> mongoimport.exe -d dbname -c collectionname --type csv --file "D:\Arkay\test.csv" --headerline
4] Verify on Mongo side using below coomand.
>db.collectioname.find().pretty().limit(1)

When to use "ON UPDATE CASCADE"

I think you've pretty much nailed the points!

If you follow database design best practices and your primary key is never updatable (which I think should always be the case anyway), then you never really need the ON UPDATE CASCADE clause.

Zed made a good point, that if you use a natural key (e.g. a regular field from your database table) as your primary key, then there might be certain situations where you need to update your primary keys. Another recent example would be the ISBN (International Standard Book Numbers) which changed from 10 to 13 digits+characters not too long ago.

This is not the case if you choose to use surrogate (e.g. artifically system-generated) keys as your primary key (which would be my preferred choice in all but the most rare occasions).

So in the end: if your primary key never changes, then you never need the ON UPDATE CASCADE clause.

Marc

How do I restart a service on a remote machine in Windows?

You can use System Internals PSEXEC command to remotely execute a net stop yourservice, then net start yourservice

Get method arguments using Spring AOP?

Yes, the value of any argument can be found using getArgs

@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
public void logBefore(JoinPoint joinPoint) {

   Object[] signatureArgs = thisJoinPoint.getArgs();
   for (Object signatureArg: signatureArgs) {
      System.out.println("Arg: " + signatureArg);
      ...
   }
}

JSON.stringify output to div in pretty print way

Full disclosure I am the author of this package but another way to output JSON or JavaScript objects in a readable way complete with being able skip parts, collapse them, etc. is nodedump, https://github.com/ragamufin/nodedump

How to pass a function as a parameter in Java?

Java supports closures just fine. It just doesn't support functions, so the syntax you're used to for closures is much more awkward and bulky: you have to wrap everything up in a class with a method. For example,

public Runnable foo(final int x) {
  return new Runnable() {
    public void run() {
      System.out.println(x);
    }
  };
}

Will return a Runnable object whose run() method "closes over" the x passed in, just like in any language that supports first-class functions and closures.

Using an HTTP PROXY - Python

You can do it even without the HTTP_PROXY environment variable. Try this sample:

import urllib2

proxy_support = urllib2.ProxyHandler({"http":"http://61.233.25.166:80"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)

html = urllib2.urlopen("http://www.google.com").read()
print html

In your case it really seems that the proxy server is refusing the connection.


Something more to try:

import urllib2

#proxy = "61.233.25.166:80"
proxy = "YOUR_PROXY_GOES_HERE"

proxies = {"http":"http://%s" % proxy}
url = "http://www.google.com/search?q=test"
headers={'User-agent' : 'Mozilla/5.0'}

proxy_support = urllib2.ProxyHandler(proxies)
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
urllib2.install_opener(opener)

req = urllib2.Request(url, None, headers)
html = urllib2.urlopen(req).read()
print html

Edit 2014: This seems to be a popular question / answer. However today I would use third party requests module instead.

For one request just do:

import requests

r = requests.get("http://www.google.com", 
                 proxies={"http": "http://61.233.25.166:80"})
print(r.text)

For multiple requests use Session object so you do not have to add proxies parameter in all your requests:

import requests

s = requests.Session()
s.proxies = {"http": "http://61.233.25.166:80"}

r = s.get("http://www.google.com")
print(r.text)

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

Right to Left support for Twitter Bootstrap 3

finally, I can find a new version for the right to left bootstrap. share here for use by all:

bootstrap-3-3-7-rtl and RTL Bootstrap 4.0.0-alpha.6.1

GitHub link:

https://github.com/parsmizban/RTL-Bootstrap

thank you parsmizban.com for creating and share.

C++ variable has initializer but incomplete type?

It's not related to Ken's case directly, but such an error also can occur if you copied .h file and forgot to change #ifndef directive. In this case compiler will just skip definition of the class thinking that it's a duplication.

JavaScript operator similar to SQL "like"

No, there isn't any.

The list of comparison operators are listed here.

Comparison Operators

For your requirement the best option would be regular expressions.

How to sort a dataFrame in python pandas by two or more columns?

As of pandas 0.17.0, DataFrame.sort() is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values

As such, the answer to your question would now be

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

Handling urllib2's timeout? - Python

In Python 2.7.3:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
    print type(e)    #not catch
except socket.timeout as e:
    print type(e)    #catched
    raise MyException("There was an error: %r" % e)

in_array() and multidimensional array

Please try:

in_array("irix",array_keys($b))
in_array("Linux",array_keys($b["irix"])

Im not sure about the need, but this might work for your requirement

how do I give a div a responsive height

I don't think this is the BEST solution, but it does appear to work. Instead of using the background color, I'm going to just embed an image of the background, position it relatively and then wrap the text in a child element and position it absolute - in the centre.

How to retrieve a module's path?

This was trivial.

Each module has a __file__ variable that shows its relative path from where you are right now.

Therefore, getting a directory for the module to notify it is simple as:

os.path.dirname(__file__)

Subtract days, months, years from a date in JavaScript

You are simply reducing the values from a number. So substracting 6 from 3 (date) will return -3 only.

You need to individually add/remove unit of time in date object

var date = new Date();
date.setDate( date.getDate() - 6 );
date.setFullYear( date.getFullYear() - 1 );
$("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));

Ignore mapping one property with Automapper

When mapping a view model back to a domain model, it can be much cleaner to simply validate the source member list rather than the destination member list

Mapper.CreateMap<OrderModel, Orders>(MemberList.Source); 

Now my mapping validation doesn't fail, requiring another Ignore(), every time I add a property to my domain class.

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

Shortcut way: (windows xp)

1) click Start > run > services.msc

2) Scroll down to 'Windows Presentation Foundation Font Cache 4.0.0.0' and then right click and select properties

Restrict varchar() column to specific values?

When you are editing a table
Right Click -> Check Constraints -> Add -> Type something like Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly') in expression field and a good constraint name in (Name) field.
You are done.

Wait for shell command to complete

Use the WScript.Shell instead, because it has a waitOnReturn option:

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn

(Idea copied from Wait for Shell to finish, then format cells - synchronously execute a command)

Timeout a command in bash without unnecessary delay

You can do this entirely with bash 4.3 and above:

_timeout() { ( set +b; sleep "$1" & "${@:2}" & wait -n; r=$?; kill -9 `jobs -p`; exit $r; ) }
  • Example: _timeout 5 longrunning_command args
  • Example: { _timeout 5 producer || echo KABOOM $?; } | consumer
  • Example: producer | { _timeout 5 consumer1; consumer2; }
  • Example: { while date; do sleep .3; done; } | _timeout 5 cat | less

  • Needs Bash 4.3 for wait -n

  • Gives 137 if the command was killed, else the return value of the command.
  • Works for pipes. (You do not need to go foreground here!)
  • Works with internal shell commands or functions, too.
  • Runs in a subshell, so no variable export into the current shell, sorry.

If you do not need the return code, this can be made even simpler:

_timeout() { ( set +b; sleep "$1" & "${@:2}" & wait -n; kill -9 `jobs -p`; ) }

Notes:

  • Strictly speaking you do not need the ; in ; ), however it makes thing more consistent to the ; }-case. And the set +b probably can be left away, too, but better safe than sorry.

  • Except for --forground (probably) you can implement all variants timeout supports. --preserve-status is a bit difficult, though. This is left as an exercise for the reader ;)

This recipe can be used "naturally" in the shell (as natural as for flock fd):

(
set +b
sleep 20 &
{
YOUR SHELL CODE HERE
} &
wait -n
kill `jobs -p`
)

However, as explained above, you cannot re-export environment variables into the enclosing shell this way naturally.

Edit:

Real world example: Time out __git_ps1 in case it takes too long (for things like slow SSHFS-Links):

eval "__orig$(declare -f __git_ps1)" && __git_ps1() { ( git() { _timeout 0.3 /usr/bin/git "$@"; }; _timeout 0.3 __orig__git_ps1 "$@"; ) }

Edit2: Bugfix. I noticed that exit 137 is not needed and makes _timeout unreliable at the same time.

Edit3: git is a die-hard, so it needs a double-trick to work satisfyingly.

Edit4: Forgot a _ in the first _timeout for the real world GIT example.

Get resultset from oracle stored procedure

In SQL Plus:

SQL> var r refcursor
SQL> set autoprint on
SQL> exec :r := function_returning_refcursor();

Replace the last line with a call to your procedure / function and the contents of the refcursor will be displayed

Show hide divs on click in HTML and CSS without jQuery

Of course! jQuery is just a library that utilizes javascript after all.

You can use document.getElementById to get the element in question, then change its height accordingly, through element.style.height.

elementToChange = document.getElementById('collapseableEl');
elementToChange.style.height = '100%';

Wrap that up in a neat little function that caters for toggling back and forth and you have yourself a solution.

Decrypt password created with htpasswd

.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.

What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.

How to use lodash to find and return an object from Array?

Fetch id basing on name

 {
    "roles": [
     {
      "id": 1,
      "name": "admin",
     },
     {
      "id": 3,
      "name": "manager",
     }
    ]
    }



    fetchIdBasingOnRole() {
          const self = this;
          if (this.employee.roles) {
            var roleid = _.result(
              _.find(this.getRoles, function(obj) {
                return obj.name === self.employee.roles;
              }),
              "id"
            );
          }
          return roleid;
        },

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

Updated Answer

Trying to open multiple panels of a collapse control that is setup as an accordion i.e. with the data-parent attribute set, can prove quite problematic and buggy (see this question on multiple panels open after programmatically opening a panel)

Instead, the best approach would be to:

  1. Allow each panel to toggle individually
  2. Then, enforce the accordion behavior manually where appropriate.

To allow each panel to toggle individually, on the data-toggle="collapse" element, set the data-target attribute to the .collapse panel ID selector (instead of setting the data-parent attribute to the parent control. You can read more about this in the question Modify Twitter Bootstrap collapse plugin to keep accordions open.

Roughly, each panel should look like this:

<div class="panel panel-default">
   <div class="panel-heading">
         <h4 class="panel-title"
             data-toggle="collapse" 
             data-target="#collapseOne">
             Collapsible Group Item #1
         </h4>
    </div>
    <div id="collapseOne" 
         class="panel-collapse collapse">
        <div class="panel-body"></div>
    </div>
</div>

To manually enforce the accordion behavior, you can create a handler for the collapse show event which occurs just before any panels are displayed. Use this to ensure any other open panels are closed before the selected one is shown (see this answer to multiple panels open). You'll also only want the code to execute when the panels are active. To do all that, add the following code:

$('#accordion').on('show.bs.collapse', function () {
    if (active) $('#accordion .in').collapse('hide');
});

Then use show and hide to toggle the visibility of each of the panels and data-toggle to enable and disable the controls.

$('#collapse-init').click(function () {
    if (active) {
        active = false;
        $('.panel-collapse').collapse('show');
        $('.panel-title').attr('data-toggle', '');
        $(this).text('Enable accordion behavior');
    } else {
        active = true;
        $('.panel-collapse').collapse('hide');
        $('.panel-title').attr('data-toggle', 'collapse');
        $(this).text('Disable accordion behavior');
    }
});

Working demo in jsFiddle

Optimal number of threads per core

I thought I'd add another perspective here. The answer depends on whether the question is assuming weak scaling or strong scaling.

From Wikipedia:

Weak scaling: how the solution time varies with the number of processors for a fixed problem size per processor.

Strong scaling: how the solution time varies with the number of processors for a fixed total problem size.

If the question is assuming weak scaling then @Gonzalo's answer suffices. However if the question is assuming strong scaling, there's something more to add. In strong scaling you're assuming a fixed workload size so if you increase the number of threads, the size of the data that each thread needs to work on decreases. On modern CPUs memory accesses are expensive and would be preferable to maintain locality by keeping the data in caches. Therefore, the likely optimal number of threads can be found when the dataset of each thread fits in each core's cache (I'm not going into the details of discussing whether it's L1/L2/L3 cache(s) of the system).

This holds true even when the number of threads exceeds the number of cores. For example assume there's 8 arbitrary unit (or AU) of work in the program which will be executed on a 4 core machine.

Case 1: run with four threads where each thread needs to complete 2AU. Each thread takes 10s to complete (with a lot of cache misses). With four cores the total amount of time will be 10s (10s * 4 threads / 4 cores).

Case 2: run with eight threads where each thread needs to complete 1AU. Each thread takes only 2s (instead of 5s because of the reduced amount of cache misses). With four cores the total amount of time will be 4s (2s * 8 threads / 4 cores).

I've simplified the problem and ignored overheads mentioned in other answers (e.g., context switches) but hope you get the point that it might be beneficial to have more number of threads than the available number of cores, depending on the data size you're dealing with.

How to remove focus without setting focus to another control?

Old question, but I came across it when I had a similar issue and thought I'd share what I ended up doing.

The view that gained focus was different each time so I used the very generic:

View current = getCurrentFocus();
if (current != null) current.clearFocus();

Android: upgrading DB version and adding new table

Handling database versions is very important part of application development. I assume that you already have class AppDbHelper extending SQLiteOpenHelper. When you extend it you will need to implement onCreate and onUpgrade method.

  1. When onCreate and onUpgrade methods called

    • onCreate called when app newly installed.
    • onUpgrade called when app updated.
  2. Organizing Database versions I manage versions in a class methods. Create implementation of interface Migration. E.g. For first version create MigrationV1 class, second version create MigrationV1ToV2 (these are my naming convention)


    public interface Migration {
        void run(SQLiteDatabase db);//create tables, alter tables
    }

Example migration:

public class MigrationV1ToV2 implements Migration{
      public void run(SQLiteDatabase db){
        //create new tables
        //alter existing tables(add column, add/remove constraint)
        //etc.
     }
   }
  1. Using Migration classes

onCreate: Since onCreate will be called when application freshly installed, we also need to execute all migrations(database version updates). So onCreate will looks like this:

public void onCreate(SQLiteDatabase db){
        Migration mV1=new MigrationV1();
       //put your first database schema in this class
        mV1.run(db);
        Migration mV1ToV2=new MigrationV1ToV2();
        mV1ToV2.run(db);
        //other migration if any
  }

onUpgrade: This method will be called when application is already installed and it is updated to new application version. If application contains any database changes then put all database changes in new Migration class and increment database version.

For example, lets say user has installed application which has database version 1, and now database version is updated to 2(all schema updates kept in MigrationV1ToV2). Now when application upgraded, we need to upgrade database by applying database schema changes in MigrationV1ToV2 like this:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion < 2) {
        //means old version is 1
        Migration migration = new MigrationV1ToV2();
        migration.run(db);
    }
    if (oldVersion < 3) {
        //means old version is 2
    }
}

Note: All upgrades (mentioned in onUpgrade) in to database schema should be executed in onCreate

jquery change button color onclick

Use css:

<style>
input[name=btnsubmit]:active {
color: green;
}
</style>

Execute ssh with password authentication via windows command prompt

The sshpass utility is meant for exactly this. First, install sshpass by typing this command:

sudo apt-get install sshpass

Then prepend your ssh/scp command with

sshpass -p '<password>' <ssh/scp command>

This program is easiest to install when using Linux.

User should consider using SSH's more secure public key authentication (with the ssh command) instead.

What's the difference between .NET Core, .NET Framework, and Xamarin?

You can refer in this line - Difference between ASP.NET Core (.NET Core) and ASP.NET Core (.NET Framework)

.NET Framework, .NET Core, Xamarin

Xamarin is not a debate at all. When you want to build mobile (iOS, Android, and Windows Mobile) apps using C#, Xamarin is your only choice.

The .NET Framework supports Windows and Web applications. Today, you can use Windows Forms, WPF, and UWP to build Windows applications in .NET Framework. ASP.NET MVC is used to build Web applications in .NET Framework.

.NET Core is the new open-source and cross-platform framework to build applications for all operating system including Windows, Mac, and Linux. .NET Core supports UWP and ASP.NET Core only. UWP is used to build Windows 10 targets Windows and mobile applications. ASP.NET Core is used to build browser based web applications.

you want more details refer this links
https://blogs.msdn.microsoft.com/dotnet/2016/07/15/net-core-roadmap/ https://docs.microsoft.com/en-us/dotnet/articles/standard/choosing-core-framework-server

./configure : /bin/sh^M : bad interpreter

If you could not found run the command,

CentOS:

# yum install dos2unix*

# dos2unix filename.sh
dos2unix: converting file filename.sh to Unix format ...

Ubuntu / Debian:

# apt-get install dos2unix

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

Selecting specific rows and columns from NumPy array

Fancy indexing requires you to provide all indices for each dimension. You are providing 3 indices for the first one, and only 2 for the second one, hence the error. You want to do something like this:

>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

That is of course a pain to write, so you can let broadcasting help you:

>>> a[[[0], [1], [3]], [0, 2]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

This is much simpler to do if you index with arrays, not lists:

>>> row_idx = np.array([0, 1, 3])
>>> col_idx = np.array([0, 2])
>>> a[row_idx[:, None], col_idx]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

How to search for a string inside an array of strings

Extending the contains function you linked to:

containsRegex(a, regex){
  for(var i = 0; i < a.length; i++) {
    if(a[i].search(regex) > -1){
      return i;
    }
  }
  return -1;
}

Then you call the function with an array of strings and a regex, in your case to look for height:

containsRegex([ '<param name=\"bgcolor\" value=\"#FFFFFF\" />', 'sdafkdf' ], /height/)

You could additionally also return the index where height was found:

containsRegex(a, regex){
  for(var i = 0; i < a.length; i++) {
    int pos = a[i].search(regex);
    if(pos > -1){
      return [i, pos];
    }
  }
  return null;
}

Wordpress keeps redirecting to install-php after migration

I experienced this issue today and started searching on internet. In my case there was no table in my DB. I forgot to import the tables on the online server. I did it and all works fine.

Only allow Numbers in input Tag without Javascript

Of course, you can't fully rely on the client-side (javascript) validation, but that's not a reason to avoid it completely. With or without it, you have to do the server-side validation anyway (since the client can disable javascript). And that's just what you're left with, due to your non-javascript solution constraint.

So, after a submit, if the field value doesn't pass the server-side validation, the client should end up on the very same page, with additional error message specifying the requested value format. You also should provide the value format information beforehands, e.g. as a tool-tip hint (title attribute).

There's most certainly no passive client-side validation mechanism existing in HTML 4 / XHTML.

On the other hand, in HTML 5 you have two options:

  • input of type number:

    <input type="number" min="xxx" max="yyy" title="Format: 3 digits" />
    

    – only validates the range – if user enters a non-number, an empty value is submitted
    – the field visual is enhanced with increment / decrement controls (browser dependent)

  • the pattern attribute:

    <input type="text" pattern="[0-9]{3}" title="Format: 3 digits" />
    <input type="text" pattern="\d{3}" title="Format: 3 digits" />
    

    – this gives you a full contorl over the format (anything you can specify by regular expression)
    – no visual difference / enhancement

But here you still rely on browser capabilities, so do a server-side validation in either case.

How do you force a makefile to rebuild a target

It was already mentioned, but thought I could add to using touch

If you touch all the source files to be compiled, the touch command changes the timestamps of a file to the system time the touch command was executed.

The source file timstamp is what make uses to "know" a file has changed, and needs to be re-compiled

For example: If the project was a c++ project, then do touch *.cpp, then run make again, and make should recompile the entire project.

getting the X/Y coordinates of a mouse click on an image with jQuery

Take a look at http://jsfiddle.net/TroyAlford/ZZEk8/ for a working example of the below:

<img id='myImg' src='/my/img/link.gif' />

<script type="text/javascript">
    $(document).bind('click', function () {
        // Add a click-handler to the image.
        $('#myImg').bind('click', function (ev) {
            var $img = $(ev.target);

            var offset = $img.offset();
            var x = ev.clientX - offset.left;
            var y = ev.clientY - offset.top;

            alert('clicked at x: ' + x + ', y: ' + y);
        });
    });
</script>

Note that the above will get you the x and the y relative to the image's box - but will not correctly take into account margin, border and padding. These elements aren't actually part of the image, in your case - but they might be part of the element that you would want to take into account.

In this case, you should also use $div.outerWidth(true) - $div.width() and $div.outerHeight(true) - $div.height() to calculate the amount of margin / border / etc.

Your new code might look more like:

<img id='myImg' src='/my/img/link.gif' />

<script type="text/javascript">
    $(document).bind('click', function () {
        // Add a click-handler to the image.
        $('#myImg').bind('click', function (ev) {
            var $img = $(ev.target);

            var offset = $img.offset(); // Offset from the corner of the page.
            var xMargin = ($img.outerWidth() - $img.width()) / 2;
            var yMargin = ($img.outerHeight() - $img.height()) / 2;
            // Note that the above calculations assume your left margin is 
            // equal to your right margin, top to bottom, etc. and the same 
            // for borders.

            var x = (ev.clientX + xMargin) - offset.left;
            var y = (ev.clientY + yMargin) - offset.top;

            alert('clicked at x: ' + x + ', y: ' + y);
        });
    });
</script>

Can I apply the required attribute to <select> fields in HTML5?

try this, this gonna work, I have tried this and this works.

<!DOCTYPE html>
<html>
<body>

<form action="#">
<select required>
  <option value="">None</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
<input type="submit">
</form>

</body>
</html>

In Python, how do I create a string of n characters in one line of code?

if you just want any letters:

 'a'*10  # gives 'aaaaaaaaaa'

if you want consecutive letters (up to 26):

 ''.join(['%c' % x for x in range(97, 97+10)])  # gives 'abcdefghij'

Are the shift operators (<<, >>) arithmetic or logical in C?

GCC does

  1. for -ve - > Arithmetic Shift

  2. For +ve -> Logical Shift

Insert Data Into Tables Linked by Foreign Key

You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:

insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

If the customer does not exist, you'll get an sql exception which text will be something like:

null value in column "customer_id" violates not-null constraint

(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:

insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.

Passing additional variables from command line to make

it seems

command args overwrite environment variable

Makefile

send:
    echo $(MESSAGE1) $(MESSAGE2)

Run example

$ MESSAGE1=YES MESSAGE2=NG  make send MESSAGE2=OK
echo YES OK
YES OK

Read entire file in Scala?

One more: https://github.com/pathikrit/better-files#streams-and-codecs

Various ways to slurp a file without loading the contents into memory:

val bytes  : Iterator[Byte]            = file.bytes
val chars  : Iterator[Char]            = file.chars
val lines  : Iterator[String]          = file.lines
val source : scala.io.BufferedSource   = file.content 

You can supply your own codec too for anything that does a read/write (it assumes scala.io.Codec.default if you don't provide one):

val content: String = file.contentAsString  // default codec
// custom codec:
import scala.io.Codec
file.contentAsString(Codec.ISO8859)
//or
import scala.io.Codec.string2codec
file.write("hello world")(codec = "US-ASCII")

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

To start with basics, it is very important to understand binary tree itself to understand different types of it.

A tree is a binary tree if and only if :-

– It has a root node , which may not have any child nodes (0 childnodes, NULL tree)

–Root node may have 1 or 2 child nodes . Each such node forms abinary tree itself 

–Number of child nodes can be 0 ,1 ,2.......not more than 2

–There is a unique path from the root to every other node

Example :

        X
      /    \
     X      X
          /   \
         X     X

Coming to your inquired terminologies:

A binary tree is a complete binary tree ( of height h , we take root node as 0 ) if and only if :-

Level 0 to h-1 represent a full binary tree of height h-1

– One or more nodes in level h-1 may have 0, or 1 child nodes

If j,k are nodes in level h-1, then j has more child nodes than k if and only if j is to the left of k , i.e. the last level (h) can be missing leaf nodes, however the ones present must be shifted to the left

Example :

                          X
                     /          \
                   /              \
                 /                  \
                X                    X
             /     \              /     \
           X       X             X       X
         /   \   /   \         /   \    /  \ 
        X    X   X   X        X    X    X   X 

A binary tree is a strictly binary tree if and only if :-

Each node has exactly two child nodes or no nodes

Example :

         X
       /   \
      X     X 
          /   \
         X      X
        / \    / \ 
       X   X  X   X 

A binary tree is a full binary tree if and only if :-

Each non leaf node has exactly two child nodes

All leaf nodes are at the same level

Example :

                          X
                     /          \
                   /              \
                 /                  \
                X                    X
             /     \              /     \
           X       X             X       X
         /   \   /   \         /   \    /  \ 
        X    X   X   X        X    X    X   X 
      /  \  / \ / \ / \      / \  / \  / \ / \ 
     X   X X  X X X X X     X  X  X X  X X X X 

You should also know what a perfect binary tree is?

A binary tree is a perfect binary tree if and only if :-

– is a full binary tree

– All leaf nodes are at the same level

Example :

                          X
                     /          \
                   /              \
                 /                  \
                X                    X
             /     \              /     \
           X       X             X       X
         /   \   /   \         /   \    /  \ 
        X    X   X   X        X    X    X   X 
      /  \  / \ / \ / \      / \  / \  / \ / \ 
     X   X X  X X X X X     X  X  X X  X X X X 

Well, I am sorry I cannot post images as I do not have 10 reputation. Hope this helps you and others!

Magento - Retrieve products with a specific attribute value

This is a follow up to my original question to help out others with the same problem. If you need to filter by an attribute, rather than manually looking up the id you can use the following code to retrieve all the id, value pairs for an attribute. The data is returned as an array with the attribute name as the key.

function getAttributeOptions($attributeName) {
    $product = Mage::getModel('catalog/product');
    $collection = Mage::getResourceModel('eav/entity_attribute_collection')
              ->setEntityTypeFilter($product->getResource()->getTypeId())
              ->addFieldToFilter('attribute_code', $attributeName);

    $_attribute = $collection->getFirstItem()->setEntity($product->getResource());
    $attribute_options  = $_attribute->getSource()->getAllOptions(false);
    foreach($attribute_options as $val) {
        $attrList[$val['label']] = $val['value'];
    }   

    return $attrList;
}

Here is a function you can use to get products by their attribute set id. Retrieved using the previous function.

function getProductsByAttributeSetId($attributeSetId) {
   $products = Mage::getModel('catalog/product')->getCollection();
   $products->addAttributeToFilter('attribute_set_id',$attributeSetId);

   $products->addAttributeToSelect('*');

   $products->load();
   foreach($products as $val) {
     $productsArray[] = $val->getData();
  }

  return $productsArray;
}

How to call jQuery function onclick?

try this ..

HTML

<input type="submit" value="submit" name="submit" id="submit">

jQuery

$(document).ready(function () {
    $('#submit').click(function () {
        var url = $(location).attr('href');
        $('#spn_url').html('<strong>' + url + '</strong>');
    });
});

Set database timeout in Entity Framework

For Database first Aproach:

We can still set it in a constructor, by override the ContextName.Context.tt T4 Template this way:

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{
    public <#=code.Escape(container)#>()
        : base("name=<#=container.Name#>")
    {
        Database.CommandTimeout = 180;
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
        this.Configuration.LazyLoadingEnabled = false;
<#
}

Database.CommandTimeout = 180; is the acutaly change.

The generated output is this:

public ContextName() : base("name=ContextName")
{
    Database.CommandTimeout = 180;
}

If you change your Database Model, this template stays, but the actualy class will be updated.

Gets last digit of a number

Although the best way to do this is to use % if you insist on using strings this will work

public int lastDigit(int number)
{
return Integer.parseInt(String.valueOf(Integer.toString(number).charAt(Integer.toString(number).length() - 1)));
}

but I just wrote this for completeness. Do not use this code. it is just awful.

jQuery Remove string from string

I assume that the text "username1" is just a placeholder for what will eventually be an actual username. Assuming that,

  • If the username is not allowed to have spaces, then just search for everything before the first space or comma (thus finding both "u1 likes this" and "u1, u2, and u3 like this").
  • If it is allowed to have a space, it would probably be easier to wrap each username in it's own span tag server-side, before sending it to the client, and then just working with the span tags.

Why is Ant giving me a Unsupported major.minor version error

One possible cause of this is an incorrect JRE selected in the Ant build options. After right-clicking the build.xml and choosing 'Run As...' and then 'Ant Build...', make sure the correct JRE is chosen under the JRE Tab of the configuration options dialogue box. You will see a 'Separate JRE' option; make sure the appropriate jdk is chosen from the drop down before clicking 'Run'.

How to change the background color of the options menu?

protected void setMenuBackground() {
    getLayoutInflater().setFactory(new Factory() {
        @Override
        public View onCreateView (String name, Context context, AttributeSet attrs) {
            if (name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) {
                try {
                    // Ask our inflater to create the view
                    LayoutInflater f = getLayoutInflater();
                    final View view = f.createView(name, null, attrs);
                    // Kind of apply our own background
                    new Handler().post( new Runnable() {
                        public void run () {
                            view.setBackgroundResource(R.drawable.gray_gradient_background);
                        }
                    });
                    return view;
                }
                catch (InflateException e) {
                }
                catch (ClassNotFoundException e) {
                }
            }
            return null;
        }
    });
}

this is XML file

gradient 
    android:startColor="#AFAFAF" 
    android:endColor="#000000"
    android:angle="270"
shape

Which type of folder structure should be used with Angular 2?

I think structuring the project by functionalities is a practical method. It makes the project scalable and maintainable easily. And it makes each part of the project working in a total autonomy. Let me know what you think about this structure below: ANGULAR TYPESCRIPT PROJECT STRUCTURE – ANGULAR 2

source : http://www.angulartypescript.com/angular-typescript-project-structure/

Entity framework linq query Include() multiple children entities

How do you construct a LINQ to Entities query to load child objects directly, instead of calling a Reference property or Load()

There is no other way - except implementing lazy loading.

Or manual loading....

myobj = context.MyObjects.First();
myobj.ChildA.Load();
myobj.ChildB.Load();
...

How can I express that two values are not equal to eachother?

if (!secondaryPassword.equals(initialPassword)) 

How to extract duration time from ffmpeg output?

In case of one request parameter it is simplier to use mediainfo and its output formatting like this (for duration; answer in milliseconds)

mediainfo --Output="General;%Duration%" ~/work/files/testfiles/+h263_aac.avi 

outputs

24840

How to implement a SQL like 'LIKE' operator in java?

Check out https://github.com/hrakaroo/glob-library-java.

It's a zero dependency library in Java for doing glob (and sql like) type of comparisons. Over a large data set it is faster than translating to a regular expression.

Basic syntax

MatchingEngine m = GlobPattern.compile("dog%cat\%goat_", '%', '_', GlobPattern.HANDLE_ESCAPES);
if (m.matches(str)) { ... }

How to get object size in memory?

In debug mode

load SOS

and execute dumpheap command.

Spring's overriding bean

Another good approach not mentioned in other posts is to use PropertyOverrideConfigurer in case you just want to override properties of some beans.

For example if you want to override the datasource for testing (i.e. use an in-memory database) in another xml config, you just need to use <context:property-override ..."/> in new config and a .properties file containing key-values taking the format beanName.property=newvalue overriding the main props.

application-mainConfig.xml:

<bean id="dataSource" 
    class="org.apache.commons.dbcp.BasicDataSource" 
    p:driverClassName="org.postgresql.Driver"
    p:url="jdbc:postgresql://localhost:5432/MyAppDB" 
    p:username="myusername" 
    p:password="mypassword"
    destroy-method="close" />

application-testConfig.xml:

<import resource="classpath:path/to/file/application-mainConfig.xml"/>

<!-- override bean props -->
<context:property-override location="classpath:path/to/file/beanOverride.properties"/>

beanOverride.properties:

dataSource.driverClassName=org.h2.Driver
dataSource.url=jdbc:h2:mem:MyTestDB

How to set .net Framework 4.5 version in IIS 7 application pool

There is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:

appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5

Appcmd is located in %windir%\System32\inetsrv. This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5.

MS article on setting .Net version for App Pool

How to insert pandas dataframe via mysqldb into database?

This should do the trick:

import pandas as pd
import pymysql
pymysql.install_as_MySQLdb()
from sqlalchemy import create_engine

# Create engine
engine = create_engine('mysql://USER_NAME_HERE:PASS_HERE@HOST_ADRESS_HERE/DB_NAME_HERE')

# Create the connection and close it(whether successed of failed)
with engine.begin() as connection:
  df.to_sql(name='INSERT_TABLE_NAME_HERE/INSERT_NEW_TABLE_NAME', con=connection, if_exists='append', index=False)

How to access site running apache server over lan without internet connection

nothing to be done for running your wamp sites to another computer. 1. first turn off the firewall. 2. Set Put Online in wamp by clcking in wamp icon at near to clock.

Finally run your browser in another computer and type http:\ip address or computer name e.g. http:\192.168.1.100

Format datetime in asp.net mvc 4

Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.

My finally working solution:

$(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    }
});

You have to include before:

@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")

You can install moment.js using:

Install-Package Moment.js

How do you get the string length in a batch file?

As there is no built in function for string length, you can write your own function like this one:

@echo off
setlocal
REM *** Some tests, to check the functionality ***
REM *** An emptyStr has the length 0
set "emptyString="
call :strlen result emptyString
echo %result%

REM *** This string has the length 14
set "myString=abcdef!%%^^()^!"
call :strlen result myString
echo %result%

REM *** This string has the maximum length of 8191
setlocal EnableDelayedExpansion
set "long=."
FOR /L %%n in (1 1 13) DO set "long=!long:~-4000!!long:~-4000!"
(set^ longString=!long!!long:~-191!)

call :strlen result longString
echo %result%

goto :eof

REM ********* function *****************************
:strlen <resultVar> <stringVar>
(   
    setlocal EnableDelayedExpansion
    (set^ tmp=!%~2!)
    if defined tmp (
        set "len=1"
        for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
            if "!tmp:~%%P,1!" NEQ "" ( 
                set /a "len+=%%P"
                set "tmp=!tmp:~%%P!"
            )
        )
    ) ELSE (
        set len=0
    )
)
( 
    endlocal
    set "%~1=%len%"
    exit /b
)

This function needs always 13 loops, instead of a simple strlen function which needs strlen-loops.
It handles all characters.

The strange expression (set^ tmp=!%~2!) is necessary to handle ultra long strings, else it's not possible to copy them.

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

How can you flush a write using a file descriptor?

fflush() only flushes the buffering added by the stdio fopen() layer, as managed by the FILE * object. The underlying file itself, as seen by the kernel, is not buffered at this level. This means that writes that bypass the FILE * layer, using fileno() and a raw write(), are also not buffered in a way that fflush() would flush.

As others have pointed out, try not mixing the two. If you need to use "raw" I/O functions such as ioctl(), then open() the file yourself directly, without using fopen<() and friends from stdio.

Adding an .env file to React Project

4 steps

  1. npm install dotenv --save

  2. Next add the following line to your app.

    require('dotenv').config()

  3. Then create a .env file at the root directory of your application and add the variables to it.

// contents of .env 

REACT_APP_API_KEY = 'my-secret-api-key'
  1. Finally, add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub.

If you are using create-react-app then you only need step 3 and 4 but keep in mind variable needs to start with REACT_APP_ for it to work.

Reference: https://create-react-app.dev/docs/adding-custom-environment-variables/

NOTE - Need to restart application after adding variable in .env file.

Reference - https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f

Add key value pair to all objects in array

arrOfObj.map(o => { 
  o.isActive = true; 
  return o; 
});

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

Just right click on the ConstrainLayout and select the "convert view" and then "RelativeLayout":

How to get column by number in Pandas?

another way to access a column by number is to use a mapping dictionary where the key is the column name and the value is the column number

dates = pd.date_range('1/1/2000', periods=8)

df = pd.DataFrame(np.random.randn(8, 4),
   index=dates, columns=['A', 'B', 'C', 'D'])
print(df)
dct={'A':0,'B':1,'C':2,'D':3}
columns=df.columns

print(df.iloc[:,dct['D']])

Make .gitignore ignore everything except a few files

I know I am late for the party,but here's my answer.

As @Joakim said, to ignore a file, you can use something like below.

# Ignore everything
*

# But not these files...
!.gitignore
!someFile.txt

but if the file is with in nested directories, it's little bit hard to manually write the rules.

For example, if we want to skip all files in a git project, but not a.txt which is located in aDir/anotherDir/someOtherDir/aDir/bDir/cDir. Then, our .gitignore will be something like this

# Skip all files
*

# But not `aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt`
!aDir/
aDir/*
!aDir/anotherDir/
aDir/anotherDir/*
!aDir/anotherDir/someOtherDir/
aDir/anotherDir/someOtherDir/*
!aDir/anotherDir/someOtherDir/aDir/
aDir/anotherDir/someOtherDir/aDir/*
!aDir/anotherDir/someOtherDir/aDir/bDir/
aDir/anotherDir/someOtherDir/aDir/bDir/*
!aDir/anotherDir/someOtherDir/aDir/bDir/cDir/
aDir/anotherDir/someOtherDir/aDir/bDir/cDir/*
!aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt

The above given .gitignore file will skip all dirs and files except !aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt

As you may have noted, it's hard to define those rules.

To solve this hurdle, I've created a simple console application named git-do-not-ignore which will generate the rules for you. I've hosted the project in github with detailed instruction.

Usage Example

java -jar git-do-not-ignore.jar "aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt"

Output

!aDir/
aDir/*
!aDir/anotherDir/
aDir/anotherDir/*
!aDir/anotherDir/someOtherDir/
aDir/anotherDir/someOtherDir/*
!aDir/anotherDir/someOtherDir/aDir/
aDir/anotherDir/someOtherDir/aDir/*
!aDir/anotherDir/someOtherDir/aDir/bDir/
aDir/anotherDir/someOtherDir/aDir/bDir/*
!aDir/anotherDir/someOtherDir/aDir/bDir/cDir/
aDir/anotherDir/someOtherDir/aDir/bDir/cDir/*
!aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt

There's also a simple web version available here

Thank you.

Excel is not updating cells, options > formula > workbook calculation set to automatic

I had this happen in a worksheet today. Neither F9 nor turning on Iterative Calculation made the cells in question update, but double-clicking the cell and pressing Enter did. I searched the Excel Help and found this in the help article titled Change formula recalculation, iteration, or precision:

CtrlAltF9:
Recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.

CtrlShiftAltF9:
Check dependent formulas, and then recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.

So I tried CtrlShiftAltF9, and sure enough, all of my non-recalculating formulas finally recalculated!

Get column index from label in a data frame

Following on from chimeric's answer above:

To get ALL the column indices in the df, so i used:

which(!names(df)%in%c()) 

or store in a list:

indexLst<-which(!names(df)%in%c())

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

How to export the Html Tables data into PDF using Jspdf

I Used Datatable JS plugin for my purpose of exporting an html table data into various formats. With my experience it was very quick, easy to use and configure with minimal coding.

Below is a sample jquery call using datatable plugin, #example is your table id

$(document).ready(function() {
    $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'copyHtml5',
            'excelHtml5',
            'csvHtml5',
            'pdfHtml5'
        ]
    } );
} );

Please find the complete example in below datatable reference link :

https://datatables.net/extensions/buttons/examples/html5/simple.html

This is how it looks after configuration( from reference site) : enter image description here

You need to have following library references in your html ( some can be found in the above reference link)

jquery-1.12.3.js
jquery.dataTables.min.js
dataTables.buttons.min.js
jszip.min.js
pdfmake.min.js
vfs_fonts.js
buttons.html5.min.js

Remove leading or trailing spaces in an entire column of data

I've found that the best (and easiest) way to delete leading, trailing (and excessive) spaces in Excel is to use a third-party plugin. I've been using ASAP Utilities for Excel and it accomplishes the task as well as adds many other much-needed features. This approach doesn't require writing formulas and can remove spaces on any selection spanning multiple columns and/or rows. I also use this to sanitize and remove the uninvited non-breaking space that often finds its way into Excel data when copying-and-pasting from other Microsoft products.

More information regarding ASAP Utilities and trimming can be found here:

http://www.asap-utilities.com/asap-utilities-excel-tools-tip.php?tip=87enter image description here

Is there a "not equal" operator in Python?

There are two operators in Python for the "not equal" condition -

a.) != If values of the two operands are not equal, then the condition becomes true. (a != b) is true.

b.) <> If values of the two operands are not equal, then the condition becomes true. (a <> b) is true. This is similar to the != operator.

What is the proper way to URL encode Unicode characters?

The general rule seems to be that browsers encode form responses according to the content-type of the page the form was served from. This is a guess that if the server sends us "text/xml; charset=iso-8859-1", then they expect responses back in the same format.

If you're just entering a URL in the URL bar, then the browser doesn't have a base page to work on and therefore just has to guess. So in this case it seems to be doing utf-8 all the time (since both your inputs produced three-octet form values).

The sad truth is that AFAIK there's no standard for what character set the values in a query string, or indeed any characters in the URL, should be interpreted as. At least in the case of values in the query string, there's no reason to suppose that they necessarily do correspond to characters.

It's a known problem that you have to tell your server framework which character set you expect the query string to be encoded as--- for instance, in Tomcat, you have to call request.setEncoding() (or some similar method) before you call any of the request.getParameter() methods. The dearth of documentation on this subject probably reflects the lack of awareness of the problem amongst many developers. (I regularly ask Java interviewees what the difference between a Reader and an InputStream is, and regularly get blank looks)

How do you import classes in JSP?

In the page tag:

<%@ page import="java.util.List" %>

Check if a div exists with jquery

If you are simply checking for the existence of an ID, there is no need to go into jQuery, you could simply:

if(document.getElementById("yourid") !== null)
{
}

getElementById returns null if it can't be found.

Reference.

If however you plan to use the jQuery object later i'd suggest:

$(document).ready(function() {
    var $myDiv = $('#DivID');

    if ( $myDiv.length){
        //you can now reuse  $myDiv here, without having to select it again.
    }


});

A selector always returns a jQuery object, so there shouldn't be a need to check against null (I'd be interested if there is an edge case where you need to check for null - but I don't think there is).

If the selector doesn't find anything then length === 0 which is "falsy" (when converted to bool its false). So if it finds something then it should be "truthy" - so you don't need to check for > 0. Just for it's "truthyness"

You don't have write permissions for the /var/lib/gems/2.3.0 directory

I encountered the same error in GitHub Actions. Adding sudo solved the issue.

sudo gem install bundler

When to catch java.lang.Error?

Generally, never.

However, sometimes you need to catch specific errors.

If you're writing framework-ish code (loading 3rd party classes), it might be wise to catch LinkageError (no class def found, unsatisfied link, incompatible class change).

I've also seen some stupid 3rd-party code throwing subclasses of Error, so you'll have to handle those as well.

By the way, I'm not sure it isn't possible to recover from OutOfMemoryError.

Display current time in 12 hour format with AM/PM

You can use SimpleDateFormat for this.

SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");

Hope this helps you.

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

Try

$sqlupdate1 = "UPDATE table SET commodity_quantity=$qty WHERE user={$rows['user']} ";

You need curly brackets for array access in double quoted strings.

C default arguments

Probably the best way to do this (which may or may not be possible in your case depending on your situation) is to move to C++ and use it as 'a better C'. You can use C++ without using classes, templates, operator overloading or other advanced features.

This will give you a variant of C with function overloading and default parameters (and whatever other features you chose to use). You just have to be a little disciplined if you're really serious about using only a restricted subset of C++.

A lot of people will say it's a terrible idea to use C++ in this way, and they might have a point. But's it's just an opinion; I think it's valid to use features of C++ that you're comfortable with without having to buy into the whole thing. I think a significant part of the reason for the sucess of C++ is that it got used by an awful lot of programmers in it's early days in exactly this way.

Sorting options elements alphabetically using jQuery

html:

<select id="list">
    <option value="op3">option 3</option>
    <option value="op1">option 1</option>
    <option value="op2">option 2</option>
</select>

jQuery:

var options = $("#list option");                    // Collect options         
options.detach().sort(function(a,b) {               // Detach from select, then Sort
    var at = $(a).text();
    var bt = $(b).text();         
    return (at > bt)?1:((at < bt)?-1:0);            // Tell the sort function how to order
});
options.appendTo("#list");                          // Re-attach to select

I used tracevipin's solution, which worked fantastically. I provide a slightly modified version here for anyone like me who likes to find easily readable code, and compress it after it's understood. I've also used .detach instead of .remove to preserve any bindings on the option DOM elements.

Convert string to date in Swift

Try the following date Format.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"
let date = dateFormatter. dateFromString (strDate)

Hope it helps..

Swift 4.1 :

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"
let date = dateFormatter.date(from: strDate)

Converting from hex to string

Like so?

static void Main()
{
    byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
    string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
    hex = hex.Replace("-", "");
    byte[] raw = new byte[hex.Length / 2];
    for (int i = 0; i < raw.Length; i++)
    {
        raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
    }
    return raw;
}

How do you add UI inside cells in a google spreadsheet using app script?

Status 2018:

There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.


This being said, there are some things that you can indeed do:

You can...

You can place images within cells using IMAGE(URL), but they cannot be linked to Apps Script functions.

You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))

You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.