Programs & Examples On #Ispring

How to support placeholder attribute in IE8 and 9

I use thisone, it's only Javascript.

I simply have an input element with a value, and when the user clicks on the input element, it changes it to an input element without a value.

You can easily change the color of the text using CSS. The color of the placeholder is the color in the id #IEinput, and the color your typed text will be is the color in the id #email. Don't use getElementsByClassName, because the versions of IE that don't support a placeholder, don't support getElementsByClassName either!

You can use a placeholder in a password input by setting the type of the original password input to text.

Tinker: http://tinker.io/4f7c5/1 - JSfiddle servers are down!

*sorry for my bad english

JAVASCRIPT

function removeValue() {
    document.getElementById('mailcontainer')
        .innerHTML = "<input id=\"email\" type=\"text\" name=\"mail\">";
    document.getElementById('email').focus(); }

HTML

<span id="mailcontainer">
    <input id="IEinput" onfocus="removeValue()" type="text" name="mail" value="mail">
</span>

In Python, how do I split a string and keep the separators?

I had a similar issue trying to split a file path and struggled to find a simple answer. This worked for me and didn't involve having to substitute delimiters back into the split text:

my_path = 'folder1/folder2/folder3/file1'

import re

re.findall('[^/]+/|[^/]+', my_path)

returns:

['folder1/', 'folder2/', 'folder3/', 'file1']

What is the difference between AF_INET and PF_INET in socket programming?

Beej's famous network programming guide gives a nice explanation:

In some documentation, you'll see mention of a mystical "PF_INET". This is a weird etherial beast that is rarely seen in nature, but I might as well clarify it a bit here. Once a long time ago, it was thought that maybe a address family (what the "AF" in "AF_INET" stands for) might support several protocols that were referenced by their protocol family (what the "PF" in "PF_INET" stands for).
That didn't happen. Oh well. So the correct thing to do is to use AF_INET in your struct sockaddr_in and PF_INET in your call to socket(). But practically speaking, you can use AF_INET everywhere. And, since that's what W. Richard Stevens does in his book, that's what I'll do here.

How to detect simple geometric shapes using OpenCV

You can also use template matching to detect shapes inside an image.

how to POST/Submit an Input Checkbox that is disabled?

Unfortunately there is no 'simple' solution. The attribute readonly cannot be applied to checkboxes. I read the W3 spec about the checkbox and found the culprit:

If a control doesn't have a current value when the form is submitted, user agents are not required to treat it as a successful control. (http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2)

This causes the unchecked state and the disabled state to result in the same parsed value.

  • readonly="readonly" is not a valid attribute for checkboxes.
  • onclick="event.preventDefault();" is not always a good solution as it's triggered on the checkbox itself. But it can work charms in some occasions.
  • Enabling the checkbox onSubmit is not a solution because the control is still not treated as a successful control so the value will not be parsed.
  • Adding another hidden input with the same name in your HTML does not work because the first control value is overwritten by the second control value as it has the same name.

The only full-proof way to do this is to add a hidden input with the same name with javascript on submitting the form.

You can use the small snippet I made for this:

function disabled_checkbox() {
  var theform = document.forms[0];
  var theinputs = theform.getElementsByTagName('input');
  var nrofinputs = theinputs.length;
  for(var inputnr=0;inputnr<nrofinputs;inputnr++) {
    if(theinputs[inputnr].disabled==true) {
      var thevalueis = theinputs[inputnr].checked==true?"on":"";
      var thehiddeninput = document.createElement("input");
      thehiddeninput.setAttribute("type","hidden");
      thehiddeninput.setAttribute("name",theinputs[inputnr].name);
      thehiddeninput.setAttribute("value",thevalueis);
      theinputs[inputnr].parentNode.appendChild(thehiddeninput);
    }
  }
}

This looks for the first form in the document, gathers all inputs and searches for disabled inputs. When a disabled input is found, a hidden input is created in the parentNode with the same name and the value 'on' (if it's state is 'checked') and '' (if it's state is '' - not checked).

This function should be triggered by the event 'onsubmit' in the FORM element as:

<form id='ID' action='ACTION' onsubmit='disabled_checkbox();'>

What does the regex \S mean in JavaScript?

\s matches whitespace (spaces, tabs and new lines). \S is negated \s.

Multi-dimensional associative arrays in JavaScript

_x000D_
_x000D_
<script language="javascript">_x000D_
_x000D_
// Set values to variable_x000D_
var sectionName = "TestSection";_x000D_
var fileMap = "fileMapData";_x000D_
var fileId = "foobar";_x000D_
var fileValue= "foobar.png";_x000D_
var fileId2 = "barfoo";_x000D_
var fileValue2= "barfoo.jpg";_x000D_
_x000D_
// Create top-level image object_x000D_
var images = {};_x000D_
_x000D_
// Create second-level object in images object with_x000D_
// the name of sectionName value_x000D_
images[sectionName] = {};_x000D_
_x000D_
// Create a third level object_x000D_
var fileMapObj = {};_x000D_
_x000D_
// Add the third level object to the second level object_x000D_
images[sectionName][fileMap] = fileMapObj;_x000D_
_x000D_
// Add forth level associate array key and value data_x000D_
images[sectionName][fileMap][fileId] = fileValue;_x000D_
images[sectionName][fileMap][fileId2] = fileValue2;_x000D_
_x000D_
_x000D_
// All variables_x000D_
alert ("Example 1 Value: " + images[sectionName][fileMap][fileId]);_x000D_
_x000D_
// All keys with dots_x000D_
alert ("Example 2 Value: " + images.TestSection.fileMapData.foobar);_x000D_
_x000D_
// Mixed with a different final key_x000D_
alert ("Example 3 Value: " + images[sectionName]['fileMapData'][fileId2]);_x000D_
_x000D_
// Mixed brackets and dots..._x000D_
alert ("Example 4 Value: " + images[sectionName]['fileMapData'].barfoo);_x000D_
_x000D_
// This will FAIL! variable names must be in brackets!_x000D_
alert ("Example 5 Value: " + images[sectionName]['fileMapData'].fileId2);_x000D_
// Produces: "Example 5 Value: undefined"._x000D_
_x000D_
// This will NOT work either. Values must be quoted in brackets._x000D_
alert ("Example 6 Value: " + images[sectionName][fileMapData].barfoo);_x000D_
// Throws and exception and stops execution with error: fileMapData is not defined_x000D_
_x000D_
// We never get here because of the uncaught exception above..._x000D_
alert ("The End!");_x000D_
</script>
_x000D_
_x000D_
_x000D_

Java path..Error of jvm.cfg

  • The simple Solution is just uninstall the javaSE and reinstall it to the default location.

  • Then copy the installed location probably like C:\Program Files\Java\jdk1.8.0_131\bin.

  • After then go to desktop then while selecting right click on My Pc or This pc shortcut the under that select properties >> Advanced system settings >> under Advance tab >> last option Environment Variables..>>path >> edit >> past >> ;(not required if win10)/(required if windows 7)

Fully backup a git repo?

Expanding on the great answers by KingCrunch and VonC

I combined them both:

git clone --mirror [email protected]/reponame reponame.git
cd reponame.git
git bundle create reponame.bundle --all

After that you have a file called reponame.bundle that can be easily copied around. You can then create a new normal git repository from that using git clone reponame.bundle reponame.

Note that git bundle only copies commits that lead to some reference (branch or tag) in the repository. So tangling commits are not stored to the bundle.

How to replace comma (,) with a dot (.) using java

Use this:

String str = " 12,12"
str = str.replaceAll("(\\d+)\\,(\\d+)", "$1.$2");
System.out.println("str:"+str); //-> str:12.12

hope help you.

How to start and stop android service from a adb shell?

I can start service through

am startservice com.xxx/.service.XXXService

but i don't know how to stop it yet.

jQuery: Currency Format Number

function converter()
{

var number = $(.number).text();

var number = 'Rp. '+number;

s(.number).val(number);
}

How do I get a TextBox to only accept numeric input in WPF?

I used some of what was already here and put my own twist on it using a behavior so I don't have to propagate this code throughout a ton of Views...

public class AllowableCharactersTextBoxBehavior : Behavior<TextBox>
{
    public static readonly DependencyProperty RegularExpressionProperty =
         DependencyProperty.Register("RegularExpression", typeof(string), typeof(AllowableCharactersTextBoxBehavior),
         new FrameworkPropertyMetadata(".*"));
    public string RegularExpression
    {
        get
        {
            return (string)base.GetValue(RegularExpressionProperty);
        }
        set
        {
            base.SetValue(RegularExpressionProperty, value);
        }
    }

    public static readonly DependencyProperty MaxLengthProperty =
        DependencyProperty.Register("MaxLength", typeof(int), typeof(AllowableCharactersTextBoxBehavior),
        new FrameworkPropertyMetadata(int.MinValue));
    public int MaxLength
    {
        get
        {
            return (int)base.GetValue(MaxLengthProperty);
        }
        set
        {
            base.SetValue(MaxLengthProperty, value);
        }
    }

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.PreviewTextInput += OnPreviewTextInput;
        DataObject.AddPastingHandler(AssociatedObject, OnPaste);
    }

    private void OnPaste(object sender, DataObjectPastingEventArgs e)
    {
        if (e.DataObject.GetDataPresent(DataFormats.Text))
        {
            string text = Convert.ToString(e.DataObject.GetData(DataFormats.Text));

            if (!IsValid(text, true))
            {
                e.CancelCommand();
            }
        }
        else
        {
            e.CancelCommand();
        }
    }

    void OnPreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
    {
        e.Handled = !IsValid(e.Text, false);
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.PreviewTextInput -= OnPreviewTextInput;
        DataObject.RemovePastingHandler(AssociatedObject, OnPaste);
    }

    private bool IsValid(string newText, bool paste)
    {
        return !ExceedsMaxLength(newText, paste) && Regex.IsMatch(newText, RegularExpression);
    }

    private bool ExceedsMaxLength(string newText, bool paste)
    {
        if (MaxLength == 0) return false;

        return LengthOfModifiedText(newText, paste) > MaxLength;
    }

    private int LengthOfModifiedText(string newText, bool paste)
    {
        var countOfSelectedChars = this.AssociatedObject.SelectedText.Length;
        var caretIndex = this.AssociatedObject.CaretIndex;
        string text = this.AssociatedObject.Text;

        if (countOfSelectedChars > 0 || paste)
        {
            text = text.Remove(caretIndex, countOfSelectedChars);
            return text.Length + newText.Length;
        }
        else
        {
            var insert = Keyboard.IsKeyToggled(Key.Insert);

            return insert && caretIndex < text.Length ? text.Length : text.Length + newText.Length;
        }
    }
}

Here is the relevant view code:

<TextBox MaxLength="50" TextWrapping="Wrap" MaxWidth="150" Margin="4"
 Text="{Binding Path=FileNameToPublish}" >
     <interactivity:Interaction.Behaviors>
         <v:AllowableCharactersTextBoxBehavior RegularExpression="^[0-9.\-]+$" MaxLength="50" />
     </interactivity:Interaction.Behaviors>
</TextBox>

Get Table and Index storage size in sql server

with pages as (
    SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
            SUM (case 
                    when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
                    else lob_used_page_count + row_overflow_used_page_count
                 end) as pages
    FROM sys.dm_db_partition_stats
    group by object_id
), extra as (
    SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
    FROM sys.dm_db_partition_stats p, sys.internal_tables it
    WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
    group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
        pages * 8 as data_kb,
        (CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
        (CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id

Takes into account internal tables, such as those used for XML storage.

Edit: If you divide the data_kb and index_kb values by 1024.0, you will get the numbers you see in the GUI.

Setting Elastic search limit to "unlimited"

Another approach is to first do a searchType: 'count', then and then do a normal search with size set to results.count.

The advantage here is it avoids depending on a magic number for UPPER_BOUND as suggested in this similar SO question, and avoids the extra overhead of building too large of a priority queue that Shay Banon describes here. It also lets you keep your results sorted, unlike scan.

The biggest disadvantage is that it requires two requests. Depending on your circumstance, this may be acceptable.

Optimistic vs. Pessimistic locking

Lot of good things have been said above about optimistic and pessimistic locking. One important point to consider is as follows:

When using optimistic locking, we need to cautious of the fact that how will application recover from these failures.

Specially in asynchronous message driven architectures, this can lead of out of order message processing or lost updates.

Failures scenarios need to be thought through.

How to read a HttpOnly cookie using JavaScript

The whole point of HttpOnly cookies is that they can't be accessed by JavaScript.

The only way (except for exploiting browser bugs) for your script to read them is to have a cooperating script on the server that will read the cookie value and echo it back as part of the response content. But if you can and would do that, why use HttpOnly cookies in the first place?

Why is 22 the default port number for SFTP?

It's the default SSH port and SFTP is usually carried over an SSH tunnel.

Adding values to a C# array

You can do this way -

int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}

Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.

List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
    termsList.Add(value);
}

// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();

Edit: a) for loops on List<T> are a bit more than 2 times cheaper than foreach loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using for is 5 times cheaper than looping on List<T> using foreach (which most of us do).

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

This isn't too difficult with a little CSS, and is much better than using an image for the bullet since you can scale it and colour it and it will keep sharp at all resolutions.

  1. Find the character code of the glyphicon by opening the Bootstrap docs and inspecting the character you want to use.

    Inspecting a glyphicon

  2. Use that character code in the following CSS

    li {
        display: block;
    }
    
    li:before {
        /*Using a Bootstrap glyphicon as the bullet point*/
        content: "\e080";
        font-family: 'Glyphicons Halflings';
        font-size: 9px;
        float: left;
        margin-top: 4px;
        margin-left: -17px;
        color: #CCCCCC;
    }
    

    You may like to tweak the colour and margins to suit your font size and taste.

View Demo & Code

How to store the hostname in a variable in a .bat file?

Just create a .bat file with the line

hostname

in it. That's it. Windows also supports the hostname command.

"pip install unroll": "python setup.py egg_info" failed with error code 1

I got stuck exactly with the same error with psycopg2. It looks like I skipped a few steps while installing Python and related packages.

  1. sudo apt-get install python-dev libpq-dev
  2. Go to your virtual env
  3. pip install psycopg2

(In your case you need to replace psycopg2 with the package you have an issue with.)

It worked seamlessly.

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

Thanks to @user2630576 and @Ed.S.

the following worked a treat:

BACKUP LOG [database] TO DISK = 'D:\database.bak'
GO

ALTER DATABASE [database] SET RECOVERY SIMPLE

use [database]

declare @log_File_Name varchar(200)

select @log_File_Name = name from sysfiles where filename like '%LDF'

declare @i int = FILE_IDEX ( @log_File_Name)

dbcc shrinkfile ( @i , 50)

ALTER DATABASE [database] SET RECOVERY FULL

Change GitHub Account username

Yes, it's possible. But first read, "What happens when I change my username?"

To change your username, click your profile picture in the top right corner, then click Settings. On the left side, click Account. Then click Change username.

How to zip a whole folder using PHP

This will resolve your issue. Please try it.

$zip = new ZipArchive;
$zip->open('testPDFZip.zip', ZipArchive::CREATE);
foreach (glob(APPLICATION_PATH."pages/recruitment/uploads/test_pdf_folder/*") as $file) {
    $new_filename = end(explode("/",$file));
    $zip->addFile($file,"emp/".$new_filename);
}           
$zip->close();

How to pass the id of an element that triggers an `onclick` event to the event handling function

Instead of passing the ID, you can just pass the element itself:

<link onclick="doWithThisElement(this)" />

Or, if you insist on passing the ID:

<link id="foo" onclick="doWithThisElement(this.id)" />

Here's the JSFiddle Demo: http://jsfiddle.net/dRkuv/

Determining the version of Java SDK on the Mac

The simplest solution would be open terminal

$ java -version

it shows the following

java version "1.6.0_65"
  1. Stefan's solution also works for me. Here's the exact input:

$ cd /System/Library/Frameworks/JavaVM.framework/Versions

$ ls -l

Below is the last line of output:

lrwxr-xr-x   1 root  wheel   59 Feb 12 14:57 CurrentJDK -> /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents

1.6.0.jdk would be the answer

Cannot find mysql.sock

I got the exact path using:

netstat -ln | grep -o -m 1 -E '\S*mysqld?\.sock'

Since this only returns the path and doesn't require any input you could potentially use it in a shell script.

MySQL must be currently running on your machine for this to work. Works for MariaDB too.

Parse JSON String into a Particular Object Prototype in JavaScript

I've combined the solutions that I was able to find and compiled it into a generic one that can automatically parse a custom object and all it's fields recursively so you can use prototype methods after deserialization.

One assumption is that you defined a special filed that indicates it's type in every object you want to apply it's type automatically (this.__type in the example).

function Msg(data) {
    //... your init code
    this.data = data //can be another object or an array of objects of custom types. 
                     //If those objects defines `this.__type', their types will be assigned automatically as well
    this.__type = "Msg"; // <- store the object's type to assign it automatically
}

Msg.prototype = {
    createErrorMsg: function(errorMsg){
        return new Msg(0, null, errorMsg)
    },
    isSuccess: function(){
        return this.errorMsg == null;
    }
}

usage:

var responseMsg = //json string of Msg object received;
responseMsg = assignType(responseMsg);

if(responseMsg.isSuccess()){ // isSuccess() is now available
      //furhter logic
      //...
}

Type assignment function (it work recursively to assign types to any nested objects; it also iterates through arrays to find any suitable objects):

function assignType(object){
    if(object && typeof(object) === 'object' && window[object.__type]) {
        object = assignTypeRecursion(object.__type, object);
    }
    return object;
}

function assignTypeRecursion(type, object){
    for (var key in object) {
        if (object.hasOwnProperty(key)) {
            var obj = object[key];
            if(Array.isArray(obj)){
                 for(var i = 0; i < obj.length; ++i){
                     var arrItem = obj[i];
                     if(arrItem && typeof(arrItem) === 'object' && window[arrItem.__type]) {
                         obj[i] = assignTypeRecursion(arrItem.__type, arrItem);
                     }
                 }
            } else  if(obj && typeof(obj) === 'object' && window[obj.__type]) {
                object[key] = assignTypeRecursion(obj.__type, obj);
            }
        }
    }
    return Object.assign(new window[type](), object);
}

How to set opacity in parent div and not affect in child div?

I had the same problem and I fixed by setting transparent png image as background for the parent tag.

This is the 1px x 1px PNG Image that I have created with 60% Opacity of black background !

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

With Bootstrap 4 .hidden-* classes were completely removed (yes, they were replaced by hidden-*-* but those classes are also gone from v4 alphas).

Starting with v4-beta, you can combine .d-*-none and .d-*-block classes to achieve the same result.

visible-* was removed as well; instead of using explicit .visible-* classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:

<div class="col d-none d-sm-block">
    <span class="vcard">
        …
    </span>
</div>
<div class="col d-none d-xl-block">
    <div class="d-none d-md-block">
                …
    </div>
    <div class="d-none d-sm-block">
                …
    </div>
</div>

class="hidden-xs" becomes class="d-none d-sm-block" (or d-none d-sm-inline-block) ...

<span class="d-none d-sm-inline">hidden-xs</span>

<span class="d-none d-sm-inline-block">hidden-xs</span>

An example of Bootstrap 4 responsive utilities:

<div class="d-none d-sm-block"> hidden-xs           
  <div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
    <div class="d-none d-lg-block"> visible-lg and up  (hidden-md and down)
      <div class="d-none d-xl-block"> visible-xl </div>
    </div>
  </div>
</div>

<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>

<div class="d-xl-none"> hidden-xl (visible-lg and down)         
  <div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
    <div class="d-md-none d-lg-none d-xl-none"> visible-sm and down  (or hidden-md and up)
      <div class="d-sm-none"> visible-xs </div>
    </div>
  </div>
</div>

Documentation

How to convert int to QString?

If you need locale-aware number formatting, use QLocale::toString instead.

How to call a JavaScript function from PHP?

Thats not possible. PHP is a Server side language and JavaScript client side and they don't really know a lot about each other. You would need a Server sided JavaScript Interpreter (like Aptanas Jaxer). Maybe what you actually want to do is to use an Ajax like Architecture (JavaScript function calls PHP script asynchronously and does something with the result).

<td onClick= loadxml()><i>Click for Details</i></td>

function loadxml()
{
    result = loadScriptWithAjax("/script.php?event=button_clicked");
    alert(result);
}

// script.php
<?php
    if($_GET['event'] == 'button_clicked')
        echo "\"You clicked a button\"";
?>

Set cellpadding and cellspacing in CSS?

<table>
    <tr>
        <th>Col 1</th>
        <th>Col 2</th>
        <th>Col 3</th>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
</table>

cell-padding can be given by padding in CSS while cell-spacing can be set by setting border-spacing for table.

table {
    border-spacing: 10px;
}
td {
    padding: 10px;
}

Fiddle.

How to paste into a terminal?

Shift + Insert usually works throughout X11.

How do you display a Toast from a background thread on Android?

You can do it by calling an Activity's runOnUiThread method from your thread:

activity.runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
    }
});

Linux command to print directory structure in the form of a tree

This command works to display both folders and files.

find . | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"

Example output:

.
 |-trace.pcap
 |-parent
 | |-chdir1
 | | |-file1.txt
 | |-chdir2
 | | |-file2.txt
 | | |-file3.sh
 |-tmp
 | |-json-c-0.11-4.el7_0.x86_64.rpm

Source: Comment from @javasheriff here. Its submerged as a comment and posting it as answer helps users spot it easily.

Overloading and overriding

Overloading is a part of static polymorphism and is used to implement different method with same name but different signatures. Overriding is used to complete the incomplete method. In my opinion there is no comparison between these two concepts, the only thing is similar is that both come with the same vocabulary that is over.

PHP Regex to check date is in YYYY-MM-DD format

You can make it this way:

if (preg_match("/\d{4}\-\d{2}-\d{2}/", $date)) {
    echo 'true';
} else {
    echo 'false';
}

but you'd better use this one:

$date = DateTime::createFromFormat('Y-m-d', $date);
if ($date) {
    echo $date -> format('Y-m-d');
}

in this case you'll get an object which is muck easier to use than just strings.

Disable Proximity Sensor during call

After trying a whole bunch of fixes including:

  • Phone app's menu option (my phone did not have a option to disable)
  • Proximity Screen Off Lite (did not work)
  • Xposed Framework with sensor disabler (works till phone is rebooted or app updates)
  • Macrodroid macro (Macrodroid does not run on my phone for some reason)
  • put some tin foil in front of it?(i don't know what i was thinking)

Here is My fix: I figured you cannot break it more so I opened up my phone and removed the proximity sensor all together from the motherboard. The sensor tester app now shows "no_value" where it use to give "Distance: 0" and my screen no longer goes black after dialing. Please note I can only confirm this working on a Samsung I8190 Galaxy S III mini with CM MOD 5.1.1. Here is a picture of the device i removed: prox sensor I have removed it using a SMD solder station's heat gun at 400 degrees, some tweezers and flux.But a sharp hobby knife might work too.

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

I am new to JavaScript development and ReactJS. I was unable to find an answer that works for me, until figuring it out by viewing the react-scripts code. Using ReactJS 15.4.1+ using react-scripts you can start with a custom host and/or port by using environment variables:

HOST='0.0.0.0' PORT=8080 npm start

Hopefully this helps newcomers like me.

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

Note: If you are programming in ASP.NET, you can run the script using ScriptManager.RegisterStartupScript in C#:

ScriptManager.RegisterStartupScript(txtField, txtField.GetType(), txtField.AccessKey, "$('#MainContent_txtField').focus(function() { $(this).select(); });", true );

Or just type the script in the HTML page suggested in the other answers.

JBoss debugging in Eclipse

If you set up a JBoss server using the Eclipse WebTools, you can simply start the server in debug mode (debug button in the servers view). This will allow you to set breakpoints in the application that is running inside the JBoss.

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

Blank parameter will result in a warning for best available.
soup = BeautifulSoup(html)

---------------/UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html5lib"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.----------------------/

python --version Python 3.7.7

PyCharm 19.3.4 CE

CSS selector for text input fields?

input[type=text]

This will select all the input type text in a web-page.

Get the value of bootstrap Datetimepicker in JavaScript

I tried all the above methods and I did not get the value properly in the same format, then I found this.

$("#datetimepicker1").find("input")[1].value;

The above code will return the value in the same format as in the datetime picker.

This may help you guys in the future.

Hope this was helpful..

ValidateAntiForgeryToken purpose, explanation and example

MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.

It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.

The feature doesn't prevent any other type of data forgery or tampering based attacks.

To use it, decorate the action method or controller with the ValidateAntiForgeryToken attribute and place a call to @Html.AntiForgeryToken() in the forms posting to the method.

git reset --hard HEAD leaves untracked files behind

If you have files you still want to keep:

git clean -di will do an interactive clean which allows you to only delete the files/dirs you don't want anymore.

Vim for Windows - What do I type to save and exit from a file?

Use:

:wq!

The exclamation mark is used for overriding read-only mode.

Issue with virtualenv - cannot activate

env\Scripts\activate worked for me on windows

angular.min.js.map not found, what is it exactly?

Monkey is right, according to the link given by monkey

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location.

I am not sure if it is angular's fault that no map files were generated. But you can turn off source map files by unchecking this option in chrome console setting

enter image description here

Generate random int value from 3 to 6

DECLARE @min INT = 3;
DECLARE @max INT = 6;
SELECT @min + ROUND(RAND() * (@max - @min), 0);

Step by step

DECLARE @min INT = 3;
DECLARE @max INT = 6;

DECLARE @rand DECIMAL(19,4) = RAND();
DECLARE @difference INT = @max - @min;
DECLARE @chunk INT = ROUND(@rand * @difference, 0);
DECLARE @result INT = @min + @chunk; 
SELECT @result;

Note that a user-defined function thus not allow the use of RAND(). A workaround for this (source: http://blog.sqlauthority.com/2012/11/20/sql-server-using-rand-in-user-defined-functions-udf/) is to create a view first.

CREATE VIEW [dbo].[vw_RandomSeed]
AS
SELECT        RAND() AS seed

and then create the random function

CREATE FUNCTION udf_RandomNumberBetween
(
    @min INT,
    @max INT
)
RETURNS INT
AS
BEGIN
    RETURN @min + ROUND((SELECT TOP 1 seed FROM vw_RandomSeed) * (@max - @min), 0);
END

Reading a simple text file

In Mono For Android....

try
{
    System.IO.Stream StrIn = this.Assets.Open("MyMessage.txt");
    string Content = string.Empty;
    using (System.IO.StreamReader StrRead = new System.IO.StreamReader(StrIn))
    {
      try
      {
            Content = StrRead.ReadToEnd();
            StrRead.Close();
      }  
      catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
      }
          StrIn.Close();
          StrIn = null;
}
catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

The link posted by Jose has been updated and pylab now has a tight_layout() function that does this automatically (in matplotlib version 1.1.0).

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout

http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout

Objective-C for Windows

Expanding on the two previous answers, if you just want Objective-C but not any of the Cocoa frameworks, then gcc will work on any platform. You can use it through Cygwin or get MinGW. However, if you want the Cocoa frameworks, or at least a reasonable subset of them, then GNUStep and Cocotron are your best bets.

Cocotron implements a lot of stuff that GNUStep does not, such as CoreGraphics and CoreData, though I can't vouch for how complete their implementation is on a specific framework. Their aim is to keep Cocotron up to date with the latest version of OS X so that any viable OS X program can run on Windows. Because GNUStep typically uses the latest version of gcc, they also add in support for Objective-C++ and a lot of the Objective-C 2.0 features.

I haven't tested those features with GNUStep, but if you use a sufficiently new version of gcc, you might be able to use them. I was not able to use Objective-C++ with GNUStep a few years ago. However, GNUStep does compile from just about any platform. Cocotron is a very mac-centric project. Although it is probably possible to compile it on other platforms, it comes XCode project files, not makefiles, so you can only compile its frameworks out of the box on OS X. It also comes with instructions on compiling Windows apps on XCode, but not any other platform. Basically, it's probably possible to set up a Windows development environment for Cocotron, but it's not as easy as setting one up for GNUStep, and you'll be on your own, so GNUStep is definitely the way to go if you're developing on Windows as opposed to just for Windows.

For what it's worth, Cocotron is licensed under the MIT license, and GNUStep is licensed under the LGPL.

java how to use classes in other package?

You have to provide the full path that you want to import.

import com.my.stuff.main.Main;
import com.my.stuff.second.*;

So, in your main class, you'd have:

package com.my.stuff.main

import com.my.stuff.second.Second;   // THIS IS THE IMPORTANT LINE FOR YOUR QUESTION

class Main {
   public static void main(String[] args) {
      Second second = new Second();
      second.x();  
   }
}

EDIT: adding example in response to Shawn D's comment

There is another alternative, as Shawn D points out, where you can specify the full package name of the object that you want to use. This is very useful in two locations. First, if you're using the class exactly once:

class Main {
    void function() {
        int x = my.package.heirarchy.Foo.aStaticMethod();

        another.package.heirarchy.Baz b = new another.package.heirarchy.Bax();
    }
}

Alternatively, this is useful when you want to differentiate between two classes with the same short name:

class Main {
    void function() {
        java.util.Date utilDate = ...;
        java.sql.Date sqlDate = ...;
    }
}

Reverse of JSON.stringify?

JSON.parse is the opposite of JSON.stringify.

DataTables fixed headers misaligned with columns in wide tables

I had this very same problem and seen a lot of complicated answers that never seemed to work. I did solve it by simply overriding the CSS (site.css) on the following and it fixed it in Chrome, IE, and Firefox:

table.display td {
padding: 0px 5px;
}
/* this is needed for IE and Firefox if using horizontal scroll*/
table{
    max-width: none;
    min-height: 0%;
}

This overrides the CSS in datatable.jui.css

Add a user control to a wpf window

Make sure there is an namespace definition (xmlns) for the namespace your control belong to.

xmlns:myControls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"
<myControls:thecontrol/>

SELECT where row value contains string MySQL

Use the % wildcard, which matches any number of characters.

SELECT * FROM Accounts WHERE Username LIKE '%query%'

Which UUID version to use?

Postgres documentation describes the differences between UUIDs. A couple of them:

V3:

uuid_generate_v3(namespace uuid, name text) - This function generates a version 3 UUID in the given namespace using the specified input name.

V4:

uuid_generate_v4 - This function generates a version 4 UUID, which is derived entirely from random numbers.

Port 443 in use by "Unable to open process" with PID 4

Probably some process is using that port, i would guess you have another webserver running with ssl/tls already. You must trac down what process is using the port and shut it down. The fact that it does not help to restart your computer makes me think that you may find what you are looking for in msconfig. Try to have a look there, open prompt and write msconfig

post 443 is normaly used by secure http, => https

I have never used windows server but there could be some built in webserver that autostarts, have you ever installed another webserver?

Try use the command Netstat -a -n -o to see what process that is blocking. you can the process pid from the output.

The Routing and RAS - service is your problem i guess look at this post

it does this, thats why its blocking:

SSTP tunneling protocol Secure Socket Tunneling Protocol (SSTP) is a new form of virtual private networking (VPN) tunnel with features that allow traffic to pass through firewalls that block PPTP and L2TP/IPsec traffic. SSTP provides a mechanism to encapsulate PPP traffic over the SSL channel of the HTTPS protocol. The use of PPP allows support for strong authentication methods, such as EAP-TLS. The use of HTTPS means traffic will flow through TCP port 443, a port commonly used for Web access. Secure Sockets Layer (SSL) provides transport-level security with enhanced key negotiation, encryption, and integrity checking.

from tecsupport.ms

Internal and external fragmentation

First of all the term fragmentation cues there's an entity divided into parts — fragments.

  • Internal fragmentation: Typical paper book is a collection of pages (text divided into pages). When a chapter's end isn't located at the end of page and new chapter starts from new page, there's a gap between those chapters and it's a waste of space — a chunk (page for a book) has unused space inside (internally) — "white space"

  • External fragmentation: Say you have a paper diary and you didn't write your thoughts sequentially page after page, but, rather randomly. You might end up with a situation when you'd want to write 3 pages in row, but you can't since there're no 3 clean pages one-by-one, you might have 15 clean pages in the diary totally, but they're not contiguous

What is ANSI format?

Technically, ANSI should be the same as US-ASCII. It refers to the ANSI X3.4 standard, which is simply the ANSI organisation's ratified version of ASCII. Use of the top-bit-set characters is not defined in ASCII/ANSI as it is a 7-bit character set.

However years of misuse of the term by the DOS and subsequently Windows community has left its practical meaning as “the system codepage of whatever machine is being used”. The system codepage is also sometimes known as ‘mbcs’, since on East Asian systems that can be a multiple-byte-per-character encoding. Some code pages can even use top-bit-clear bytes as trailing bytes in a multibyte sequence, so it's not even strict compatible with plain ASCII... but even then, it's still called “ANSI”.

On US and Western European default settings, “ANSI” maps to Windows code page 1252. This is not the same as ISO-8859-1 (although it is quite similar). On other machines it could be anything else at all. This makes “ANSI” utterly useless as an external encoding identifier.

CSS how to make an element fade in and then fade out?

Use css @keyframes

.elementToFadeInAndOut {
    opacity: 1;
    animation: fade 2s linear;
}


@keyframes fade {
  0%,100% { opacity: 0 }
  50% { opacity: 1 }
}

here is a DEMO

_x000D_
_x000D_
.elementToFadeInAndOut {_x000D_
    width:200px;_x000D_
    height: 200px;_x000D_
    background: red;_x000D_
    -webkit-animation: fadeinout 4s linear forwards;_x000D_
    animation: fadeinout 4s linear forwards;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeinout {_x000D_
  0%,100% { opacity: 0; }_x000D_
  50% { opacity: 1; }_x000D_
}_x000D_
_x000D_
@keyframes fadeinout {_x000D_
  0%,100% { opacity: 0; }_x000D_
  50% { opacity: 1; }_x000D_
}
_x000D_
<div class=elementToFadeInAndOut></div>
_x000D_
_x000D_
_x000D_

Reading: Using CSS animations

You can clean the code by doing this:

_x000D_
_x000D_
.elementToFadeInAndOut {_x000D_
    width:200px;_x000D_
    height: 200px;_x000D_
    background: red;_x000D_
    -webkit-animation: fadeinout 4s linear forwards;_x000D_
    animation: fadeinout 4s linear forwards;_x000D_
    opacity: 0;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeinout {_x000D_
  50% { opacity: 1; }_x000D_
}_x000D_
_x000D_
@keyframes fadeinout {_x000D_
  50% { opacity: 1; }_x000D_
}
_x000D_
<div class=elementToFadeInAndOut></div>
_x000D_
_x000D_
_x000D_

Find object by its property in array of objects with AngularJS way

you can use angular's filter https://docs.angularjs.org/api/ng/filter/filter

in your controller:

$filter('filter')(myArray, {'id':73}) 

or in your HTML

{{ myArray | filter : {'id':73} }}

From milliseconds to hour, minutes, seconds and milliseconds

Maybe can be shorter an more elegant. But I did it.

public String getHumanTimeFormatFromMilliseconds(String millisecondS){
    String message = "";
    long milliseconds = Long.valueOf(millisecondS);
    if (milliseconds >= 1000){
        int seconds = (int) (milliseconds / 1000) % 60;
        int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
        int hours = (int) ((milliseconds / (1000 * 60 * 60)) % 24);
        int days = (int) (milliseconds / (1000 * 60 * 60 * 24));
        if((days == 0) && (hours != 0)){
            message = String.format("%d hours %d minutes %d seconds ago", hours, minutes, seconds);
        }else if((hours == 0) && (minutes != 0)){
            message = String.format("%d minutes %d seconds ago", minutes, seconds);
        }else if((days == 0) && (hours == 0) && (minutes == 0)){
            message = String.format("%d seconds ago", seconds);
        }else{
            message = String.format("%d days %d hours %d minutes %d seconds ago", days, hours, minutes, seconds);
        }
    } else{
        message = "Less than a second ago.";
    }
    return message;
}

Using Spring RestTemplate in generic method with generic parameter

I have another way to do this... suppose you swap out your message converter to String for your RestTemplate, then you can receive raw JSON. Using the raw JSON, you can then map it into your Generic Collection using a Jackson Object Mapper. Here's how:

Swap out the message converter:

    List<HttpMessageConverter<?>> oldConverters = new ArrayList<HttpMessageConverter<?>>();
    oldConverters.addAll(template.getMessageConverters());

    List<HttpMessageConverter<?>> stringConverter = new ArrayList<HttpMessageConverter<?>>();
    stringConverter.add(new StringHttpMessageConverter());

    template.setMessageConverters(stringConverter);

Then get your JSON response like this:

    ResponseEntity<String> response = template.exchange(uri, HttpMethod.GET, null, String.class);

Process the response like this:

     String body = null;
     List<T> result = new ArrayList<T>();
     ObjectMapper mapper = new ObjectMapper();

     if (response.hasBody()) {
        body = items.getBody();
        try {
            result = mapper.readValue(body, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            template.setMessageConverters(oldConverters);
        }
        ...

How to use a class object in C++ as a function parameter

holy errors The reason for the code below is to show how to not void main every function and not to type return; for functions...... instead push everything into the sediment for which is the print function prototype... if you need to use useful functions ... you will have to below..... (p.s. this below is for people overwhelmed by these object and T templates which allow different variable declaration types(such as float and char) to use the same passed by value in a user defined function)

char arr[ ] = "This is a test";

string str(arr);


//  You can also assign directly to a string.
str = "This is another string";

can anyone tell me why c++ made arrays into pass by value one at a time and the only way to eliminate spaces and punctuation is the use of string tokens. I couldn't get around the problem when i was trying to delete spaces for a palindrome...

#include <iostream>
#include <iomanip>
using namespace std;
int getgrades(float[]);
int getaverage(float[], float);
int calculateletters(float[], float, float, float[]);
int printResults(float[], float, float, float[]);


int main()
{

int i;
float  maxSize=3, size;
float  lettergrades[5], numericgrades[100], average;

size=getgrades(numericgrades);
average = getaverage(numericgrades, size);
printResults(numericgrades, size, average, lettergrades);
return 0;
}

int getgrades(float a[])
{ 


int i, max=3;

for (i = 0; i <max; i++)
{
    //ask use for input
    cout << "\nPlease Enter grade " << i+1 << " : ";
    cin >> a[i];
    //makes sure that user enters a vlue between 0 and 100

   if(a[i] < 0 || a[i] >100)
    {
        cout << "Wrong input. Please
 enter a value between 0 and 100 only." << endl;
        cout << "\nPlease Reenter grade " << i+1 << " : ";
        cin >> a[i];

        return i;
    }
}
}

int getaverage(float a[], float n) 
{ 
int i;
float sum = 0;
 if (n == 0)
return 0;
for (i = 0; i < n; i++)
sum += a[i];
return sum / n;
}                               


int printResults(float a[], float n, float average, float letters[]) 
{
int i;
cout << "Index Number | input  |
array values address in memory " << endl;

for (i = 0; i < 3; i++)
{
cout <<"     "<< i<<" \t\t"<<setprecision(3)<<
a[i]<<"\t\t" << &a[i] << endl;
}
cout<<"The average of your grades is: "<<setprecision(3)<<average<<endl;

}

setState() inside of componentDidUpdate()

If you use setState inside componentDidUpdate it updates the component, resulting in a call to componentDidUpdate which subsequently calls setState again resulting in the infinite loop. You should conditionally call setState and ensure that the condition violating the call occurs eventually e.g:

componentDidUpdate: function() {
    if (condition) {
        this.setState({..})
    } else {
        //do something else
    }
}

In case you are only updating the component by sending props to it(it is not being updated by setState, except for the case inside componentDidUpdate), you can call setState inside componentWillReceiveProps instead of componentDidUpdate.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

How do you rotate a two dimensional array?

Implementation of dimple's +90 pseudocode (e.g. transpose then reverse each row) in JavaScript:

function rotate90(a){
  // transpose from http://www.codesuck.com/2012/02/transpose-javascript-array-in-one-line.html
  a = Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });
  // row reverse
  for (i in a){
    a[i] = a[i].reverse();
  }
  return a;
}

How to set up default schema name in JPA configuration?

For those who uses last versions of spring boot will help this:

.properties:

spring.jpa.properties.hibernate.default_schema=<name of your schema>

.yml:

spring:
    jpa:
        properties:
            hibernate:
                default_schema: <name of your schema>

How print out the contents of a HashMap<String, String> in ascending order based on its values?

Try:

try
{
    int cnt= m.getSmartPhoneCount("HTC",true);      
    System.out.println("total count of HTC="+cnt);
}  
catch (NoSuchBrandSmartPhoneAvailableException e)
{
    // TODO Auto-generated catch 
    e.printStackTrace();
}

Tips for using Vim as a Java IDE?

I've been a Vim user for years. I'm starting to find myself starting up Eclipse occasionally (using the vi plugin, which, I have to say, has a variety of issues). The main reason is that Java builds take quite a while...and they are just getting slower and slower with the addition of highly componentized build-frameworks like maven. So validating your changes tends to take quite a while, which for me seems to often lead to stacking up a bunch of compile issues I have to resolve later, and filtering through the commit messages takes a while.

When I get too big of a queue of compile issues, I fire up Eclipse. It lets me make cake-work of the changes. It's slow, brutal to use, and not nearly as nice of an editor as Vim is (I've been using Vim for nearly a decade, so it's second nature to me). I find for precision editing—needing to fix a specific bug, needing to refactor some specific bit of logic, or something else...I simply can't be as efficient at editing in Eclipse as I can in Vim.

Also a tip:

:set path=**
:chdir your/project/root

This makes ^wf on a classname a very nice feature for navigating a large project.

So anyway, the skinny is, when I need to add a lot of new code, Vim seems to slow me down simply due to the time spent chasing down compilation issues and similar stuff. When I need to find and edit specific sources, though, Eclipse feels like a sledge hammer. I'm still waiting for the magical IDE for Vim. There's been three major attempts I know of. There's a pure viml IDE-type plugin which adds a lot of features but seems impossible to use. There's eclim, which I've had a lot of trouble with. And there's a plugin for Eclipse which actually embeds Vim. The last one seems the most promising for real serious Java EE work, but it doesn't seem to work very well or really integrate all of Eclipse's features with the embedded Vim.

Things like add a missing import with a keystroke, hilight code with typing issues, etc, seems to be invaluable from your IDE when working on a large Java project.

Adding external library in Android studio

If the library you need is on GitHub then adding it to Android Studio is easy with JitPack.

Step 1. Add the jitpack repository to build.gradle:

allprojects { 
  repositories {
    jcenter()
    maven { url "https://jitpack.io" }
  }
}

Step 2. Add the GitHub repository as a dependency:

dependencies {
    // ...
    compile 'com.github.Username:LibraryRepo:ReleaseTag'
}

JitPack acts as a maven repository and can be used much like Maven Central. The nice thing is that the maintainers don't have to upload the library. Behind the scenes JitPack will check out the code from GitHub and compile it. Therefore for this to work there needs to be a working build file in the git repository.

There is also a guide on how to publish an Android library.

Scala how can I count the number of occurrences in a list

If you want to use it like list.count(2) you have to implement it using an Implicit Class.

implicit class Count[T](list: List[T]) {
  def count(n: T): Int = list.count(_ == n)
}

List(1,2,4,2,4,7,3,2,4).count(2)  // returns 3
List(1,2,4,2,4,7,3,2,4).count(5)  // returns 0

How to display .svg image using swift

You can use this pod called 'SVGParser'. https://cocoapods.org/pods/SVGParser.

After adding it in your pod file, all you have to do is to import this module to the class that you want to use it. You should show the SVG image in an ImageView.

There are three cases you can show this SVGimage:

  1. Load SVG from local path as Data
  2. Load SVG from local path
  3. Load SVG from remote URL

You can also find an example project in GitHub: https://github.com/AndreyMomot/SVGParser. Just download the project and run it to see how it works.

Is there any advantage of using map over unordered_map in case of trivial keys?

I would just point out that... there are many kind of unordered_maps.

Look up the Wikipedia Article on hash map. Depending on which implementation was used, the characteristics in term of look-up, insertion and deletion might vary quite significantly.

And that's what worries me the most with the addition of unordered_map to the STL: they will have to choose a particular implementation as I doubt they'll go down the Policy road, and so we will be stuck with an implementation for the average use and nothing for the other cases...

For example some hash maps have linear rehashing, where instead of rehashing the whole hash map at once, a portion is rehash at each insertion, which helps amortizing the cost.

Another example: some hash maps use a simple list of nodes for a bucket, others use a map, others don't use nodes but find the nearest slot and lastly some will use a list of nodes but reorder it so that the last accessed element is at the front (like a caching thing).

So at the moment I tend to prefer the std::map or perhaps a loki::AssocVector (for frozen data sets).

Don't get me wrong, I'd like to use the std::unordered_map and I may in the future, but it's difficult to "trust" the portability of such a container when you think of all the ways of implementing it and the various performances that result of this.

Select statement to find duplicates on certain fields

If you're using SQL Server 2005 or later (and the tags for your question indicate SQL Server 2008), you can use ranking functions to return the duplicate records after the first one if using joins is less desirable or impractical for some reason. The following example shows this in action, where it also works with null values in the columns examined.

create table Table1 (
 Field1 int,
 Field2 int,
 Field3 int,
 Field4 int 
)

insert  Table1 
values    (1,1,1,1)
        , (1,1,1,2)
        , (1,1,1,3)
        , (2,2,2,1)
        , (3,3,3,1)
        , (3,3,3,2)
        , (null, null, 2, 1)
        , (null, null, 2, 3)

select    *
from     (select      Field1
                    , Field2
                    , Field3
                    , Field4
                    , row_number() over (partition by   Field1
                                                      , Field2
                                                      , Field3
                                         order by       Field4) as occurrence
          from      Table1) x
where     occurrence > 1

Notice after running this example that the first record out of every "group" is excluded, and that records with null values are handled properly.

If you don't have a column available to order the records within a group, you can use the partition-by columns as the order-by columns.

How to change string into QString?

Moreover, to convert whatever you want, you can use the QVariant class.

for example:

std::string str("hello !");
qDebug() << QVariant(str.c_str()).toString();
int test = 10;
double titi = 5.42;
qDebug() << QVariant(test).toString();
qDebug() << QVariant(titi).toString();
qDebug() << QVariant(titi).toInt();

output

"hello !"
"10"
"5.42"
5

jQuery AutoComplete Trigger Change Event

You have to manually bind the event, rather than supply it as a property of the initialization object, to make it available to trigger.

$("#CompanyList").autocomplete({ 
    source: context.companies
}).bind( 'autocompletechange', handleCompanyChanged );

then

$("#CompanyList").trigger("autocompletechange");

It's a bit of a workaround, but I'm in favor of workarounds that improve the semantic uniformity of the library!

How to copy Java Collections list

Most answers here do not realize the problem, the user wants to have a COPY of the elements from first list to the second list, destination list elements are new objects and not reference to the elements of original list. (means changing an element of second list should not change values for corresponding element of source list.) For the mutable objects we cannot use ArrayList(Collection) constructor because it will simple refer to the original list element and will not copy. You need to have a list cloner for each object when copying.

How to change style of a default EditText

Create xml file like edit_text_design.xml and save it to your drawable folder

i have given the Color codes According to my Choice, Please Change Color Codes As per your Choice !

 <?xml version="1.0" encoding="utf-8"?>
  <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item>
    <shape>
        <solid android:color="#c2c2c2" />
    </shape>
</item>

<!-- main color -->
<item
    android:bottom="1.5dp"
    android:left="1.5dp"
    android:right="1.5dp">
    <shape>
        <solid android:color="#000" />
    </shape>
</item>

<!-- draw another block to cut-off the left and right bars -->
<item android:bottom="5.0dp">
    <shape>
        <solid android:color="#000" />
    </shape>
</item>

</layer-list>

your Edit Text Should contain it as Background :

add android:background="@drawable/edit_text_design" to all of your EditText's

and your above EditText should now look like this:

      <EditText
        android:id="@+id/name_edit_text"
        android:background="@drawable/edit_text_design"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/profile_image_view_layout"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="20dp"
        android:ems="15"
        android:hint="@string/name_field"
        android:inputType="text" />

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

Just for completion, here is a code example indicating the differences:

success \ error:

$http.get('/someURL')
.success(function(data, status, header, config) {
    // success handler
})
.error(function(data, status, header, config) {
    // error handler
});

then:

$http.get('/someURL')
.then(function(response) {
    // success handler
}, function(response) {
    // error handler
})
.then(function(response) {
    // success handler
}, function(response) {
    // error handler
})
.then(function(response) {
    // success handler
}, function(response) {
    // error handler
}).

In .NET, which loop runs faster, 'for' or 'foreach'?

In cases where you work with a collection of objects, foreach is better, but if you increment a number, a for loop is better.

Note that in the last case, you could do something like:

foreach (int i in Enumerable.Range(1, 10))...

But it certainly doesn't perform better, it actually has worse performance compared to a for.

How to hide a View programmatically?

Kotlin Solution

view.isVisible = true
view.isInvisible = true
view.isGone = true

// For these to work, you need to use androidx and import:
import androidx.core.view.isVisible // or isInvisible/isGone

Kotlin Extension Solution

If you'd like them to be more consistent length, work for nullable views, and lower the chance of writing the wrong boolean, try using these custom extensions:

// Example
view.hide()

fun View?.show() {
    if (this == null) return
    if (!isVisible) isVisible = true
}

fun View?.hide() {
    if (this == null) return
    if (!isInvisible) isInvisible = true
}

fun View?.gone() {
    if (this == null) return
    if (!isGone) isGone = true
}

To make conditional visibility simple, also add these:

fun View?.show(visible: Boolean) {
    if (visible) show() else gone()
}

fun View?.hide(hide: Boolean) {
    if (hide) hide() else show()
}

fun View?.gone(gone: Boolean = true) {
    if (gone) gone() else show()
}

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

If you are not seeing the certificate under General->About->Certificate Trust Settings, then you probably do not have the ROOT CA installed. Very important -- needs to be a ROOT CA, not an intermediary CA.

I just answered a question here explaining how to obtain the ROOT CA and get things to show up: How to install self-signed certificates in iOS 11

How to create SPF record for multiple IPs?

The open SPF wizard from the previous answer is no longer available, neither the one from Microsoft.

Ruby: How to convert a string to boolean

def true?(obj)
  obj.to_s.downcase == "true"
end

How do I create JavaScript array (JSON format) dynamically?

Our array of objects

var someData = [
   {firstName: "Max", lastName: "Mustermann", age: 40},
   {firstName: "Hagbard", lastName: "Celine", age: 44},
   {firstName: "Karl", lastName: "Koch", age: 42},
];

with for...in

var employees = {
    accounting: []
};

for(var i in someData) {    

    var item = someData[i];   

    employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

or with Array.prototype.map(), which is much cleaner:

var employees = {
    accounting: []
};

someData.map(function(item) {        
   employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

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

Simplest way,

  1. If your query is Model.Objects.get():

    get() will return single instance so you can direct use __dict__ from your instance

    model_dict = Model.Objects.get().__dict__

  2. for filter()/all():

    all()/filter() will return list of instances so you can use values() to get list of objects.

    model_values = Model.Objects.all().values()

Doctrine 2 ArrayCollection filter method

The Boris Guéry answer's at this post, may help you: Doctrine 2, query inside entities

$idsToFilter = array(1,2,3,4);

$member->getComments()->filter(
    function($entry) use ($idsToFilter) {
       return in_array($entry->getId(), $idsToFilter);
    }
); 

How to create a library project in Android Studio and an application project that uses the library project

As theczechsensation comment above I try to search about Gradle Build Varians and I found this link: http://code.tutsplus.com/tutorials/using-gradle-build-variants--cms-25005 This is a very simple solution. This is what I did: - In build.gradle:

flavorDimensions "version"

productFlavors {
    trial{
        applicationId "org.de_studio.recentappswitcher.trial"
        flavorDimension "version"
    }
    pro{
        applicationId "org.de_studio.recentappswitcher.pro"
        flavorDimension "version"
    }

}

Then I have 2 more version of my app: pro and trial with 2 diffrent packageName which is 2 applicationId in above code so I can upload both to Google Play. I still just code in the "main" section and use the getpackageName to switch between to version. Just go to the link I gave for detail.

creating array without declaring the size - java

As others have said, use ArrayList. Here's how:

public class t
{
 private List<Integer> x = new ArrayList<Integer>();

 public void add(int num)
 {
   this.x.add(num);
 }
}

As you can see, your add method just calls the ArrayList's add method. This is only useful if your variable is private (which it is).

Simulating a click in jQuery/JavaScript on a link

Why not just the good ol' javascript?

$('#element')[0].click()

Read remote file with node.js (http.get)

I'd use request for this:

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:

var request = require('request');
request.get('http://www.whatever.com/my.csv', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var csv = body;
        // Continue with your processing here.
    }
});

etc.

Cannot open include file with Visual Studio

By default, Visual Studio searches for headers in the folder where your project is ($ProjectDir) and in the default standard libraries directories. If you need to include something that is not placed in your project directory, you need to add the path to the folder to include:

Go to your Project properties (Project -> Properties -> Configuration Properties -> C/C++ -> General) and in the field Additional Include Directories add the path to your .h file.

You can, also, as suggested by Chris Olen, add the path to VC++ Directories field.

How to remove array element in mongodb?

To remove all array elements irrespective of any given id, use this:

collection.update(
  { },
  { $pull: { 'contact.phone': { number: '+1786543589455' } } }
);

How can I split a JavaScript string by white space or comma?

String.split() can also accept a regular expression:

input.split(/[ ,]+/);

This particular regex splits on a sequence of one or more commas or spaces, so that e.g. multiple consecutive spaces or a comma+space sequence do not produce empty elements in the results.

Measure string size in Bytes in php

Further to PhoneixS answer to get the correct length of string in bytes - Since mb_strlen() is slower than strlen(), for the best performance one can check "mbstring.func_overload" ini setting so that mb_strlen() is used only when it is really required:

$content_length = ini_get('mbstring.func_overload') ? mb_strlen($content , '8bit') : strlen($content);

Why won't bundler install JSON gem?

If the recommended answer didn't help because you are already using a newer version of bundler. Try the solution that worked for me.

Delete everything inside your vendor folder. Add a line to your gemfile

gem 'json', '1.8.0'

Then run - bundle update json.

It seems to be an issue with 1.8.1 so going back to 1.8.0 did the trick for me.

What is the difference between Trap and Interrupt?

A trap is a software interrupt.If you write a program in which you declare a variable having divide by zero value then it is treated as a trap.Whenever you run this program it will throw same error at the same time.System call is a special version of trap in which a program asks os for its required service. In case of interrupt(a general word for hardware interrupts)like an i/o error,the cpu is interrupted at random time and off course it is not the fault of our programmers.It is the hardware that brings them up.

Java Class that implements Map and keeps insertion order?

You can maintain a Map (for fast lookup) and List (for order) but a LinkedHashMap may be the simplest. You can also try a SortedMap e.g. TreeMap, which an have any order you specify.

How To: Best way to draw table in console app (C#)

Use String.Format with alignment values.

For example:

String.Format("|{0,5}|{1,5}|{2,5}|{3,5}|", arg0, arg1, arg2, arg3);

To create one formatted row.

Force Java timezone as GMT/UTC

Wow. I know this is an ancient thread but all I can say is do not call TimeZone.setDefault() in any user-level code. This always sets the Timezone for the whole JVM and is nearly always a very bad idea. Learn to use the joda.time library or the new DateTime class in Java 8 which is very similar to the joda.time library.

Updating GUI (WPF) using a different thread

You can use Dispatcher.Invoke to update your GUI from a secondary thread.

Here is an example:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        new Thread(DoSomething).Start();
    }
    public void DoSomething()
    {
        for (int i = 0; i < 100000000; i++)
        {
               this.Dispatcher.Invoke(()=>{
               textbox.Text=i.ToString();
               });    
        } 
    }

How can I serve static html from spring boot?

You can quickly serve static content in JAVA Spring-boot App via thymeleaf (ref: source)

I assume you have already added Spring Boot plugin apply plugin: 'org.springframework.boot' and the necessary buildscript

Then go ahead and ADD thymeleaf to your build.gradle ==>

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Lets assume you have added home.html at src/main/resources To serve this file, you will need to create a controller.

package com.ajinkya.th.controller;

  import org.springframework.stereotype.Controller;
  import org.springframework.web.bind.annotation.RequestMapping;

  @Controller
  public class HomePageController {

      @RequestMapping("/")
      public String homePage() {
        return "home";
      }

  }

Thats it ! Now restart your gradle server. ./gradlew bootRun

How to apply an XSLT Stylesheet in C#

Here is a tutorial about how to do XSL Transformations in C# on MSDN:

http://support.microsoft.com/kb/307322/en-us/

and here how to write files:

http://support.microsoft.com/kb/816149/en-us

just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):

http://support.microsoft.com/kb/307379/en-us/

i added this just to provide some more information.

Where should I put <script> tags in HTML markup?

Script blocks DOM load untill it's loaded and executed.

If you place scripts at the end of <body> all of DOM has chance to load and render (page will "display" faster). <script> will have access to all of those DOM elements.

In other hand placing it after <body> start or above will execute script (where there's still no DOM elements).

You are including jQuery which means you can place it wherever you wish and use .ready()

One-liner if statements, how to convert this if-else-statement

If expression returns a boolean, you can just return the result of it.

Example

 return (a > b)

How to delete duplicate rows in SQL Server?

DECLARE @TB TABLE(NAME VARCHAR(100));
INSERT INTO @TB VALUES ('Red'),('Red'),('Green'),('Blue'),('White'),('White')
--**Delete by Rank**
;WITH CTE AS(SELECT NAME,DENSE_RANK() OVER (PARTITION BY NAME ORDER BY NEWID()) ID FROM @TB)
DELETE FROM CTE WHERE ID>1
SELECT NAME FROM @TB;
--**Delete by Row Number** 
;WITH CTE AS(SELECT NAME,ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY NAME) ID FROM @TB)
DELETE FROM CTE WHERE ID>1;
SELECT NAME FROM @TB;

Oracle ORA-12154: TNS: Could not resolve service name Error?

This was mentioned in a comment to another answer, but I wanted to move it to an actual answer since this was also the problem in my case and I would have upvoted it if it had been an answer.

I'm on Linux and the tnsnames.ora file was not set to readable by everyone. After making it readable connecting via tns locally worked.

$ chmod +r tnsnames.ora

Understanding Linux /proc/id/maps

memory mapping is not only used to map files into memory but is also a tool to request RAM from kernel. These are those inode 0 entries - your stack, heap, bss segments and more

How to remove files and directories quickly via terminal (bash shell)

Yes, there is. The -r option tells rm to be recursive, and remove the entire file hierarchy rooted at its arguments; in other words, if given a directory, it will remove all of its contents and then perform what is effectively an rmdir.

The other two options you should know are -i and -f. -i stands for interactive; it makes rm prompt you before deleting each and every file. -f stands for force; it goes ahead and deletes everything without asking. -i is safer, but -f is faster; only use it if you're absolutely sure you're deleting the right thing. You can specify these with -r or not; it's an independent setting.

And as usual, you can combine switches: rm -r -i is just rm -ri, and rm -r -f is rm -rf.

Also note that what you're learning applies to bash on every Unix OS: OS X, Linux, FreeBSD, etc. In fact, rm's syntax is the same in pretty much every shell on every Unix OS. OS X, under the hood, is really a BSD Unix system.

React Hooks useState() with Object

, do it like this example :

first creat state of the objects:

const [isSelected, setSelection] = useState({ id_1: false }, { id_2: false }, { id_3: false });

then change the value on of them:

// if the id_1 is false make it true or return it false.

onValueChange={() => isSelected.id_1 == false ? setSelection({ ...isSelected, id_1: true }) : setSelection({ ...isSelected, id_1: false })}

How to check all versions of python installed on osx and centos

The more easy way its by executing the next command:

ls -ls /usr/bin/python*

Output look like this:

/usr/bin/python           /usr/bin/python2.7        /usr/bin/pythonw
/usr/bin/python-config    /usr/bin/python2.7-config /usr/bin/pythonw2.7

Environ Function code samples for VBA

As alluded to by Eric, you can use environ with ComputerName argument like so:

MsgBox Environ("USERNAME")

Some additional information that might be helpful for you to know:

  1. The arguments are not case sensitive.
  2. There is a slightly faster performing string version of the Environ function. To invoke it, use a dollar sign. (Ex: Environ$("username")) This will net you a small performance gain.
  3. You can retrieve all System Environment Variables using this function. (Not just username.) A common use is to get the "ComputerName" value to see which computer the user is logging onto from.
  4. I don't recommend it for most situations, but it can be occasionally useful to know that you can also access the variables with an index. If you use this syntax the the name of argument and the value are returned. In this way you can enumerate all available variables. Valid values are 1 - 255.
    Sub EnumSEVars()
        Dim strVar As String
        Dim i As Long
        For i = 1 To 255
            strVar = Environ$(i)
            If LenB(strVar) = 0& Then Exit For
            Debug.Print strVar
        Next
    End Sub

How to get the URL without any parameters in JavaScript?

Use indexOf

var url = "http://mysite.com/somedir/somefile/?aa";

if (url.indexOf("?")>-1){
url = url.substr(0,url.indexOf("?"));
}

How to input a path with a white space?

I see Federico you've found solution by yourself. The problem was in two places. Assignations need proper quoting, in your case

SOME_PATH="/$COMPANY/someProject/some path"

is one of possible solutions.

But in shell those quotes are not stored in a memory, so when you want to use this variable, you need to quote it again, for example:

NEW_VAR="$SOME_PATH"

because if not, space will be expanded to command level, like this:

NEW_VAR=/YourCompany/someProject/some path

which is not what you want.

For more info you can check out my article about it http://www.cofoh.com/white-shell

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

My problem was solved checking if the process was running on Ubuntu 12.04

ps ax | grep mysql

Then the answer was that it wasn't running, so I did

sudo service mysql start

Or try

sudo /etc/init.d/mysql start

Pandas sort by group aggregate and column

One way to do this is to insert a dummy column with the sums in order to sort:

In [10]: sum_B_over_A = df.groupby('A').sum().B

In [11]: sum_B_over_A
Out[11]: 
A
bar    0.253652
baz   -2.829711
foo    0.551376
Name: B

in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)

In [13]: df
Out[13]: 
     A         B      C  sum_B_over_A
0  foo  1.624345  False      0.551376
1  bar -0.611756   True      0.253652
2  baz -0.528172  False     -2.829711
3  foo -1.072969   True      0.551376
4  bar  0.865408  False      0.253652
5  baz -2.301539   True     -2.829711

In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]: 
     A         B      C   sum_B_over_A
5  baz -2.301539   True      -2.829711
2  baz -0.528172  False      -2.829711
1  bar -0.611756   True       0.253652
4  bar  0.865408  False       0.253652
3  foo -1.072969   True       0.551376
0  foo  1.624345  False       0.551376

and maybe you would drop the dummy row:

In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]: 
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

Where to find Java JDK Source Code?

This file is contained in the standard JDK download. Also your Linux system probably have JDK in the repository. In my Ubuntu Linux file is located here: /usr/lib/jvm/java-6-sun-1.6.0.20/src.zip

Should I add the Visual Studio .suo and .user files to source control?

Others have explained why having the *.suo and *.user files under source control is not a good idea.

I'd like to suggest that you add these patterns to the svn:ignore property for 2 reasons:

  1. So other developers won't wind up with one developer's settings.
  2. So when you view status, or commit files, those files won't clutter the code base and obscure new files you need to add.

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

Sorry for being a bit late to the party. I wanted to add my one liner using cut2 as I didn't know max/min for my data and wanted the groups to be identically large. I read about cut2 in an issue which was marked as duplicate (link below).

library(Hmisc)   #For cut2
set.seed(123)    #To keep answers below identical to my random run

temp <- data.frame(name=letters[1:12], value=rnorm(12), quartile=rep(NA, 12))

temp$quartile <- as.numeric(cut2(temp$value, g=4))   #as.numeric to number the factors
temp$quartileBounds <- cut2(temp$value, g=4)

temp

Result:

> temp
   name       value quartile  quartileBounds
1     a -0.56047565        1 [-1.265,-0.446)
2     b -0.23017749        2 [-0.446, 0.129)
3     c  1.55870831        4 [ 1.224, 1.715]
4     d  0.07050839        2 [-0.446, 0.129)
5     e  0.12928774        3 [ 0.129, 1.224)
6     f  1.71506499        4 [ 1.224, 1.715]
7     g  0.46091621        3 [ 0.129, 1.224)
8     h -1.26506123        1 [-1.265,-0.446)
9     i -0.68685285        1 [-1.265,-0.446)
10    j -0.44566197        2 [-0.446, 0.129)
11    k  1.22408180        4 [ 1.224, 1.715]
12    l  0.35981383        3 [ 0.129, 1.224)

Similar issue where I read about cut2 in detail

In Python, how do I use urllib to see if a website is 404 or 200?

The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.

>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200

How to make Twitter Bootstrap menu dropdown on hover rather than click

Bootstrap v4 Solution - Works in IE

This will allow you to follow top level navigation links.

This is a complete solution that uses the mouseover and mouseleave events and some screen width checking.

This was built with desktop and mobile in mind. Fell free to change the BREAK_POINT variable to suit your needs :D.

jQuery

var WINDOW_WIDTH;
var BREAK_POINT = 991;

(function ($) {

    /** Set window width onload */
    WINDOW_WIDTH = $(window).width(); // Returns width of browser viewport
    /** Set window width if the browser is resized */
    $(window).resize(function () {
        WINDOW_WIDTH = $(window).width(); // Returns width of browser viewport
    });

    /** Dropdown menu on mouseenter */
    $(".nav-item.dropdown").on('mouseenter', function () {
        console.log("mouseenter");
        if (WINDOW_WIDTH >= BREAK_POINT) {
            // Open up the dropdown
            $(this).addClass('show'); // add the class show to the li parent
            $(this).children('.nav-link').removeAttr('data-toggle'); // remove the data-toggle attribute so we can click and follow link
            $(this).children('.dropdown-menu').addClass('show'); // add the class show to the dropdown div sibling
        }
    });
    /** Dropdown menu on mouseleave */
    $(".nav-item.dropdown").on('mouseleave', function () {
        console.log("mouseleave");
        if (WINDOW_WIDTH >= BREAK_POINT) {
            // Open up the dropdown
            $(this).removeClass('show'); // add the class show to the li parent
            $(this).children('.nav-link').attr('data-toggle', 'dropdown'); // remove the data-toggle attribute so we can click and follow link
            $(this).children('.dropdown-menu').removeClass('show'); // add the class show to the dropdown div sibling
        }
    });
});

CSS

@media(min-width:  768px) {
  .dropdown-menu {
    margin-top: 0; // fixes closing on slow mouse transition
  }
}

Java 8: Lambda-Streams, Filter by Method with Exception

To properly add IOException (to RuntimeException) handling code, your method will look like this:

Stream<Account> s =  accounts.values().stream();

s = s.filter(a -> { try { return a.isActive(); } 
  catch (IOException e) { throw new RuntimeException(e); }});

Stream<String> ss = s.map(a -> { try { return a.getNumber() }
  catch (IOException e) { throw new RuntimeException(e); }});

return ss.collect(Collectors.toSet());

The problem now is that the IOException will have to be captured as a RuntimeException and converted back to an IOException -- and that will add even more code to the above method.

Why use Stream when it can be done just like this -- and the method throws IOException so no extra code is needed for that too:

Set<String> set = new HashSet<>();
for(Account a: accounts.values()){
  if(a.isActive()){
     set.add(a.getNumber());
  } 
}
return set;

Alter column in SQL Server

To set a default value to a column, try this:

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status SET DEFAULT 'default value'

What is Linux’s native GUI API?

The closest thing to Win32 in linux would be the libc, as you mention not only the UI but events and "other os stuff"

How to create hyperlink to call phone number on mobile devices?

I used:

Tel: <a href="tel:+123 123456789">+123 123456789</a>

and the result is:

Tel: +123 123456789

Where "Tel:" stands for pure text and only the number is coded and clickable.

How do I find the time difference between two datetime objects in python?

To get the hour, minute and second, you can do this

>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
>>> m,s = divmod(difference.total_seconds(), 60)
>>> print("H:M:S is {}:{}:{}".format(m//60,m%60,s)

C# Convert List<string> to Dictionary<string, string>

By using ToDictionary:

var dictionary = list.ToDictionary(s => s);

If it is possible that any string could be repeated, either do a Distinct call first on the list (to remove duplicates), or use ToLookup which allows for multiple values per key.

Vertically aligning text next to a radio button

I think this is what you might be asking for

http://jsbin.com/ixowuw/2/

CSS

label{
  font-size:18px;
  vertical-align: middle;
}

input[type="radio"]{
  vertical-align: middle;
}

HTML

<span>
  <input type="radio" id="oddsPref" name="oddsPref" value="decimal" />
  <label>Decimal</label>
</span>

fast way to copy formatting in excel

For me, you can't. But if that suits your needs, you could have speed and formatting by copying the whole range at once, instead of looping:

range("B2:B5002").Copy Destination:=Sheets("Output").Cells(startrow, 2)

And, by the way, you can build a custom range string, like Range("B2:B4, B6, B11:B18")


edit: if your source is "sparse", can't you just format the destination at once when the copy is finished ?

Expand a div to fill the remaining width

Im not sure if this is the answer you are expecting but, why don't you set the width of Tree to 'auto' and width of 'View' to 100% ?

How to find the size of a table in SQL?

SQL Server, nicely formatted table for all tables in KB/MB:

SELECT 
    t.NAME AS TableName,
    s.Name AS SchemaName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceMB,
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
    CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN 
    sys.schemas s ON t.schema_id = s.schema_id
WHERE 
    t.NAME NOT LIKE 'dt%' 
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
GROUP BY 
    t.Name, s.Name, p.Rows
ORDER BY 
    t.Name

Live video streaming using Java?

The best video playback/encoding library I have ever seen is ffmpeg. It plays everything you throw at it. (It is used by MPlayer.) It is written in C but I found some Java wrappers.

  • FFMPEG-Java: A Java wrapper around ffmpeg using JNA.
  • jffmpeg: This one integrates to JMF.

CodeIgniter: Create new helper?

Some code that allows you to use CI instance inside the helper:

function yourHelperFunction(){
    $ci=& get_instance();
    $ci->load->database(); 

    $sql = "select * from table"; 
    $query = $ci->db->query($sql);
    $row = $query->result();
}

How to export all collections in MongoDB?

I realize that this is quite an old question and that mongodump/mongorestore is clearly the right way if you want a 100% faithful result, including indexes.

However, I needed a quick and dirty solution that would likely be forwards and backwards compatible between old and new versions of MongoDB, provided there's nothing especially wacky going on. And for that I wanted the answer to the original question.

There are other acceptable solutions above, but this Unix pipeline is relatively short and sweet:

mongo --quiet mydatabase --eval "db.getCollectionNames().join('\n')" | \
grep -v system.indexes | \
xargs -L 1 -I {} mongoexport -d mydatabase -c {} --out {}.json

This produces an appropriately named .json file for each collection.

Note that the database name ("mydatabase") appears twice. I'm assuming the database is local and you don't need to pass credentials but it's easy to do that with both mongo and mongoexport.

Note that I'm using grep -v to discard system.indexes, because I don't want an older version of MongoDB to try to interpret a system collection from a newer one. Instead I'm allowing my application to make its usual ensureIndex calls to recreate the indexes.

Instance member cannot be used on type

I kept getting the same error inspite of making the variable static. Solution: Clean Build, Clean Derived Data, Restart Xcode. Or shortcut Cmd + Shift+Alt+K

UserNotificationCenterWrapper.delegate = self

public static var delegate: UNUserNotificationCenterDelegate? {
        get {
            return UNUserNotificationCenter.current().delegate
        }
        set {
            UNUserNotificationCenter.current().delegate = newValue
        }
    }

How can I get a uitableViewCell by indexPath?

You can use the following code to get last cell.

UITableViewCell *cell = [tableView cellForRowAtIndexPath:lastIndexPath];

Git update submodules recursively

The way I use is:

git submodule update --init --recursive
git submodule foreach --recursive git fetch
git submodule foreach git merge origin master

Check if a file exists or not in Windows PowerShell?

Use Test-Path:

if (!(Test-Path $exactadminfile) -and !(Test-Path $userfile)) {
  Write-Warning "$userFile absent from both locations"
}

Placing the above code in your ForEach loop should do what you want

Row count where data exists

This works for me. Returns the number that Excel displays in the bottom status line when a pivot column is filtered and I need the count of the visible cells.

Global Const DashBoardSheet = "DashBoard"
Global Const ProfileColRng = "$L:$L"
.
.
.
Sub MySub()
Dim myreccnt as long
.
.
.
myreccnt = GetFilteredPivotRowCount(DashBoardSheet, ProfileColRng)
.
.
.
End Sub

Function GetFilteredPivotRowCount(sheetname As String, cntrange As String) As long

Dim reccnt As Long

reccnt = Sheets(sheetname).Range(cntrange).SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count - 1

GetFilteredPivotRowCount = reccnt

End Function

How to to send mail using gmail in Laravel?

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=yourpassword
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME='Name'

allow less secure apps to access your account in the Gmail security setting.

Access a global variable in a PHP function

For many years I have always used this format:

<?php
    $data = "Hello";

    function sayHello(){
        echo $GLOBALS["data"];
    }

    sayHello();
?>

I find it straightforward and easy to follow. The $GLOBALS is how PHP lets you reference a global variable. If you have used things like $_SERVER, $_POST, etc. then you have reference a global variable without knowing it.

How to center a WPF app on screen?

What about the SystemParameters class in PresentationFramework? It has a WorkArea property that seems to be what you are looking for.

But, why won't setting the Window.WindowStartupLocation work? CenterScreen is one of the enum values. Do you have to tweak the centering?

Form Google Maps URL that searches for a specific places near specific coordinates

additional info:

http://maps.google.com/maps?q=loc: put in latitude and longitude after, example:

http://maps.google.com/maps?q=loc:51.03841,-114.01679

this will show pointer on map, but will suppress geocoding of the address, best for a location without an address, or for a location where google maps shows the incorrect address.

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

In case it helps, I've ran into this problem when passing null into a parameter for a generic TValue, to get around this you have to cast your null values:

(string)null

(int)null

etc.

Dataset - Vehicle make/model/year (free)

Apparently there is not much out there. And a lot of doubt that someone would be willing to provide such a repository. So I solved the problem myself, and am sharing my dataset with anyone else who finds themselves facing the same problem.

https://github.com/n8barr/automotive-model-year-data

Java, Shifting Elements in an Array

Assuming your array is {10,20,30,40,50,60,70,80,90,100}

What your loop does is:

Iteration 1: array[1] = array[0]; {10,10,30,40,50,60,70,80,90,100}

Iteration 2: array[2] = array[1]; {10,10,10,40,50,60,70,80,90,100}

What you should be doing is

Object temp = pool[position];

for (int i = (position - 1); i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;

How to Migrate to WKWebView?

Here is how I transitioned from UIWebView to WKWebView.

Note: There is no property like UIWebView that you can drag onto your storyboard, you have to do it programatically.

Make sure you import WebKit/WebKit.h into your header file.

This is my header file:

#import <WebKit/WebKit.h>

@interface ViewController : UIViewController

@property(strong,nonatomic) WKWebView *webView;
@property (strong, nonatomic) NSString *productURL;

@end

Here is my implementation file:

#import "ViewController.h"

@interface ViewController ()

@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.productURL = @"http://www.URL YOU WANT TO VIEW GOES HERE";

    NSURL *url = [NSURL URLWithString:self.productURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    _webView = [[WKWebView alloc] initWithFrame:self.view.frame];  
    [_webView loadRequest:request];
    _webView.frame = CGRectMake(self.view.frame.origin.x,self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
    [self.view addSubview:_webView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

window.location (JS) vs header() (PHP) for redirection

The result is same for all options. Redirect.

<meta> in HTML:

  • Show content of your site, and next redirect user after a few (or 0) seconds.
  • Don't need JavaScript enabled.
  • Don't need PHP.

window.location in JS:

  • Javascript enabled needed.
  • Don't need PHP.
  • Show content of your site, and next redirect user after a few (or 0) seconds.
  • Redirect can be dependent on any conditions if (1 === 1) { window.location.href = 'http://example.com'; }.

header('Location:') in PHP:

  • Don't need JavaScript enabled.
  • PHP needed.
  • Redirect will be executed first, user never see what is after. header() must be the first command in php script, before output any other. If you try output some before header, will receive an Warning: Cannot modify header information - headers already sent

powershell - extract file name and extension

PS C:\Users\joshua> $file = New-Object System.IO.FileInfo('file.type')
PS C:\Users\joshua> $file.BaseName, $file.Extension
file
.type

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance() - Deprecated

As Fragments Version 1.3.0-alpha01

The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).

How do I display the value of a Django form field in a template?

On Django 1.2, {{ form.data.field }} and {{ form.field.data }} are all OK, but not {{ form.field.value }}.
As others said, {{ form.field.value }} is Django 1.3+ only, but there's no specification in https://docs.djangoproject.com/en/1.3/topics/forms/. It can be found in https://docs.djangoproject.com/en/1.4/topics/forms/.

What is the difference between .py and .pyc files?

.pyc contain the compiled bytecode of Python source files. The Python interpreter loads .pyc files before .py files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.

Press Enter to move to next control

You can put a KeyPress handler on your TextBoxes, and see which key was used.

To handle the text selection, put a handler on the GotFocus event.

You may also want to consider how to (or if you need to) handle multi-line TextBoxes.

Should a function have only one return statement?

Well, maybe I'm one of the few people here old enough to remember one of the big reasons why "only one return statement" was pushed so hard. It's so the compiler can emit more efficient code. For each function call, the compiler typically pushes some registers on the stack to preserve their values. This way, the function can use those registers for temporary storage. When the function returns, those saved registers have to be popped off the stack and back into the registers. That's one POP (or MOV -(SP),Rn) instruction per register. If you have a bunch of return statements, then either each one has to pop all the registers (which makes the compiled code bigger) or the compiler has to keep track of which registers might have been modified and only pop those (decreasing code size, but increasing compilation time).

One reason why it still makes sense today to try to stick with one return statement is ease of automated refactoring. If your IDE supports method-extraction refactoring (selecting a range of lines and turning them into a method), it's very difficult to do this if the lines you want to extract have a return statement in them, especially if you're returning a value.

Postgresql, update if row with some unique value exists, else insert

This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671

This solution requires both an UPDATE and INSERT.

UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
       SELECT 3, 'C', 'Z'
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);

With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507

SQL "select where not in subquery" returns no results

If you want the world to be a two-valued boolean place, you must prevent the null (third value) case yourself.

Don't write IN clauses that allow nulls in the list side. Filter them out!

common_id not in
(
  select common_id from Table1
  where common_id is not null
)

No Exception while type casting with a null in java

Many answers here already mention

You can cast null to any reference type

and

If the argument is null, then a string equal to "null"

I wondered where that is specified and looked it up the Java Specification:

The null reference can always be assigned or cast to any reference type (§5.2, §5.3, §5.5).

If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

Notepad++ Setting for Disabling Auto-open Previous Files

Use the menu item Settings>Preferences.

On the MISC tab of the resulting dialog, uncheck "Remember current session for next launch."

MySQL Database won't start in XAMPP Manager-osx

For me the following worked: Change permission into 'read only' for 'everyone' to the file /Applications/XAMPP/xamppfiles/etc/my.cnf. Then start MySQL from XAMPP manager.

Get current application physical path within Application_Start

There is also the static HostingEnvironment.MapPath

How to put a component inside another component in Angular2?

I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent] from decorator.

import {myDirective} from './myDirective';

enable or disable checkbox in html

I know this question is a little old but here is my solution.

 // HTML
 // <input type="checkbox" onClick="setcb1()"/>
 // <input type="checkbox" onClick="setcb2()"/>

 // cb1 = checkbox 1
 // cb2 = checkbox 2
  var cb1 = getId('cb1'), 
      cb2 = getId('cb2');

  function getId(id) {
    return document.getElementById(id);
  }

  function setcb1() {
    if(cb1.checked === true) {
      cb2.checked = false;
      cb2.disabled = "disabled"; // You have to disable the unselected checkbox
    } else if(cb1.checked === false) {
      cb2.disabled = ""; // Then enable it if there isn't one selected.  
    }
  }

  function setcb2() {
    if(cb2.checked === true) {
      cb1.checked = false;
      cb1.disabled = "disabled"
    } else if(cb2.checked === false) {
      cb1.disabled = ""
  }

Hope this helps!

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

In PHP 7.0 it's now possible to use Null coalescing operator:

echo "My index value is: " . ($my_array["my_index"] ?? '');

Equals to:

echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');

PHP manual PHP 7.0

Equal height rows in a flex container

No, you can't achieve that without setting a fixed height (or using a script).


Here are 2 answers of mine, showing how to use a script to achieve something like that:

Zero-pad digits in string

Solution using str_pad:

str_pad($digit,2,'0',STR_PAD_LEFT);

Benchmark on php 5.3

Result str_pad : 0.286863088608

Result sprintf : 0.234171152115

Code:

$start = microtime(true);
for ($i=0;$i<100000;$i++) {
    str_pad(9,2,'0',STR_PAD_LEFT);
    str_pad(15,2,'0',STR_PAD_LEFT);
    str_pad(100,2,'0',STR_PAD_LEFT);
}
$end = microtime(true);
echo "Result str_pad : ",($end-$start),"\n";

$start = microtime(true);
for ($i=0;$i<100000;$i++) {
    sprintf("%02d", 9);
    sprintf("%02d", 15);
    sprintf("%02d", 100);
}
$end = microtime(true);
echo "Result sprintf : ",($end-$start),"\n";

Int or Number DataType for DataAnnotation validation attribute

almost a decade passed but the issue still valid with Asp.Net Core 2.2 as well.

I managed it by adding data-val-number to the input field the use localization on the message:

<input asp-for="Age" data-val-number="@_localize["Please enter a valid number."]"/>

Is there a regular expression to detect a valid regular expression?

Good question.

True regular languages can not decide arbitrarily deeply nested well-formed parenthesis. If your alphabet contains '(' and ')' the goal is to decide if a string of these has well-formed matching parenthesis. Since this is a necessary requirement for regular expressions the answer is no.

However, if you loosen the requirement and add recursion you can probably do it. The reason is that the recursion can act as a stack letting you "count" the current nesting depth by pushing onto this stack.

Russ Cox wrote "Regular Expression Matching Can Be Simple And Fast" which is a wonderful treatise on regex engine implementation.

How to assign an action for UIImageView object in Swift

You'll need a UITapGestureRecognizer. To set up use this:

override func viewDidLoad()
{
    super.viewDidLoad()

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
    imageView.isUserInteractionEnabled = true
    imageView.addGestureRecognizer(tapGestureRecognizer)
}

@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
    let tappedImage = tapGestureRecognizer.view as! UIImageView

    // Your action
}

(You could also use a UIButton and assign an image to it, without text and than simply connect an IBAction)

Ruby 'require' error: cannot load such file

What about including the current directory in the search path?

ruby -I. main.rb

Structs in Javascript

I always use object literals

{id: 1, speaker:"john", country: "au"}

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

If statements for Checkboxes

In VB.Net

If Check1.checked and Not (Check2.checked) Then

ElseIf Check2.Checked and not Check1.Checked then

End If

Android Camera : data intent returns null

To Access the Camera and take pictures and set ImageView on Android

You have to use Uri file = Uri.fromFile(getOutputMediaFile()); for marshmallow.

Use below link to get path

https://androidkennel.org/android-camera-access-tutorial/

Disable/enable an input with jQuery?

this works for me

$("#values:input").attr("disabled",true);
$("#values:input").attr("disabled",false);

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

Find in Files: Search all code in Team Foundation Server

There is currently no way to do this out of the box, but there is a User Voice suggestion for adding it: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2037649-implement-indexed-full-text-search-of-work-items

While I doubt it is as simple as flipping a switch, if everyone that has viewed this question voted for it, MS would probably implement something.

Update: Just read Brian Harry's blog, which shows this request as being on their radar, and the Online version of Visual Studio has limited support for searching where git is used as the vcs: http://blogs.msdn.com/b/visualstudioalm/archive/2015/02/13/announcing-limited-preview-for-visual-studio-online-code-search.aspx. From this I think it's fair to say it is just a matter of time...

Update 2: There is now a Microsoft provided extension,Code Search which enables searching in code as well as in work items.

pip3: command not found but python3-pip is already installed

You can make symbolic link to you pip3:

sudo ln -s $(which pip3) /usr/bin/pip3

It helps me in RHEL 7.6

What does the 'static' keyword do in a class?

This discussion has so far ignored classloader considerations. Strictly speaking, Java static fields are shared between all instances of a class for a given classloader.

Create a .csv file with values from a Python list

This solutions sounds crazy, but works smooth as honey

import csv

with open('filename', 'wb') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL,delimiter='\n')
    wr.writerow(mylist)

The file is being written by csvwriter hence csv properties are maintained i.e. comma separated. The delimiter helps in the main part by moving list items to next line, each time.

How to install pip3 on Windows?

On Windows pip3 should be in the Scripts path of your Python installation:

C:\path\to\python\Scripts\pip3

Use:

where python

to find out where your Python executable(s) is/are located. The result should look like this:

C:\path\to\python\python.exe

or:

C:\path\to\python\python3.exe

You can check if pip3 works with this absolute path:

C:\path\to\python\Scripts\pip3

if yes, add C:\path\to\python\Scripts to your environmental variable PATH .

git repo says it's up-to-date after pull but files are not updated

For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.

How to change Git log date formats

Git 2.7 (Q4 2015) will introduce -local as an instruction.
It means that, in addition to:

--date=(relative|local|default|iso|iso-strict|rfc|short|raw)

you will also have:

--date=(default-local|iso-local|iso-strict-local|rfc-local|short-local)

The -local suffix cannot be used with raw or relative. Reference.

You now can ask for any date format using the local timezone. See

See commit add00ba, commit 547ed71 (03 Sep 2015) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 7b09c45, 05 Oct 2015)

In particular, the last from above (commit add00ba) mentions:

date: make "local" orthogonal to date format:

Most of our "--date" modes are about the format of the date: which items we show and in what order.
But "--date=local" is a bit of an oddball. It means "show the date in the normal format, but using the local timezone".
The timezone we use is orthogonal to the actual format, and there is no reason we could not have "localized iso8601", etc.

This patch adds a "local" boolean field to "struct date_mode", and drops the DATE_LOCAL element from the date_mode_type enum (it's now just DATE_NORMAL plus local=1).
The new feature is accessible to users by adding "-local" to any date mode (e.g., "iso-local"), and we retain "local" as an alias for "default-local" for backwards compatibility.

AngularJs - ng-model in a SELECT

You dont need to define option tags, you can do this using the ngOptions directive: https://docs.angularjs.org/api/ng/directive/ngOptions

<select class="form-control" ng-change="unitChanged()" ng-model="data.unit" ng-options="unit.id as unit.label for unit in units"></select>

How to negate the whole regex?

Use negative lookaround: (?!pattern)

Positive lookarounds can be used to assert that a pattern matches. Negative lookarounds is the opposite: it's used to assert that a pattern DOES NOT match. Some flavor supports assertions; some puts limitations on lookbehind, etc.

Links to regular-expressions.info

See also

More examples

These are attempts to come up with regex solutions to toy problems as exercises; they should be educational if you're trying to learn the various ways you can use lookarounds (nesting them, using them to capture, etc):